blob: 130c8e958ed58b75c47ffa2656550ad299863f80 [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: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200442#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000443/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200444#define debug_printf_parse(...) do {} while (0)
445#define debug_printf_heredoc(...) do {} while (0)
446#define debug_print_tree(a, b) do {} while (0)
447#define debug_printf_exec(...) do {} while (0)
448#define debug_printf_env(...) do {} while (0)
449#define debug_printf_jobs(...) do {} while (0)
450#define debug_printf_expand(...) do {} while (0)
451#define debug_printf_varexp(...) do {} while (0)
452#define debug_printf_glob(...) do {} while (0)
453#define debug_printf_redir(...) do {} while (0)
454#define debug_printf_list(...) do {} while (0)
455#define debug_printf_subst(...) do {} while (0)
456#define debug_printf_prompt(...) do {} while (0)
457#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000458
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000459#define ERR_PTR ((void*)(long)1)
460
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100461#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000462
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200463#define _SPECIAL_VARS_STR "_*@$!?#"
464#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
465#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100466#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200467/* Support / and // replace ops */
468/* Note that // is stored as \ in "encoded" string representation */
469# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
470# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
471# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
472#else
473# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
474# define VAR_SUBST_OPS "%#:-=+?"
475# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
476#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200477
Denys Vlasenko932b9972018-01-11 12:39:48 +0100478#define SPECIAL_VAR_SYMBOL_STR "\3"
479#define SPECIAL_VAR_SYMBOL 3
480/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
481#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000482
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200483struct variable;
484
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000485static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
486
487/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000488 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000489 */
490#if !BB_MMU
491typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200492 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000493 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000494 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000495} nommu_save_t;
496#endif
497
Denys Vlasenko9b782552010-09-08 13:33:26 +0200498enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000499 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000500#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000501 RES_IF ,
502 RES_THEN ,
503 RES_ELIF ,
504 RES_ELSE ,
505 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000506#endif
507#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000508 RES_FOR ,
509 RES_WHILE ,
510 RES_UNTIL ,
511 RES_DO ,
512 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000513#endif
514#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000515 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000516#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000517#if ENABLE_HUSH_CASE
518 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200519 /* three pseudo-keywords support contrived "case" syntax: */
520 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
521 RES_MATCH , /* "word)" */
522 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000523 RES_ESAC ,
524#endif
525 RES_XXXX ,
526 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200527};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000528
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000529typedef struct o_string {
530 char *data;
531 int length; /* position where data is appended */
532 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200533 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000534 /* At least some part of the string was inside '' or "",
535 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200536 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000537 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200538 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000539} o_string;
540enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200541 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
542 EXP_FLAG_GLOB = 0x2,
543 /* Protect newly added chars against globbing
544 * by prepending \ to *, ?, [, \ */
545 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
546};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000547/* Used for initialization: o_string foo = NULL_O_STRING; */
548#define NULL_O_STRING { NULL }
549
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200550#ifndef debug_printf_parse
551static const char *const assignment_flag[] = {
552 "MAYBE_ASSIGNMENT",
553 "DEFINITELY_ASSIGNMENT",
554 "NOT_ASSIGNMENT",
555 "WORD_IS_KEYWORD",
556};
557#endif
558
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000559typedef struct in_str {
560 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200561 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200562 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000564} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000565
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200566/* The descrip member of this structure is only used to make
567 * debugging output pretty */
568static const struct {
569 int mode;
570 signed char default_fd;
571 char descrip[3];
572} redir_table[] = {
573 { O_RDONLY, 0, "<" },
574 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
575 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
576 { O_CREAT|O_RDWR, 1, "<>" },
577 { O_RDONLY, 0, "<<" },
578/* Should not be needed. Bogus default_fd helps in debugging */
579/* { O_RDONLY, 77, "<<" }, */
580};
581
Eric Andersen25f27032001-04-26 23:22:31 +0000582struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000583 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000584 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000585 int rd_fd; /* fd to redirect */
586 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
587 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000588 smallint rd_type; /* (enum redir_type) */
589 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000590 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200591 * bit 0: do we need to trim leading tabs?
592 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000593 */
Eric Andersen25f27032001-04-26 23:22:31 +0000594};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000595typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200596 REDIRECT_INPUT = 0,
597 REDIRECT_OVERWRITE = 1,
598 REDIRECT_APPEND = 2,
599 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000600 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200601 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000602
603 REDIRFD_CLOSE = -3,
604 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000605 REDIRFD_TO_FILE = -1,
606 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000607
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000608 HEREDOC_SKIPTABS = 1,
609 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000610} redir_type;
611
Eric Andersen25f27032001-04-26 23:22:31 +0000612
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000613struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000614 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200615 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100616#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100617 unsigned lineno;
618#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200619 smallint cmd_type; /* CMD_xxx */
620#define CMD_NORMAL 0
621#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200622#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
623/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
624 * "export v=t*"
625 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200626# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000627#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200628#if ENABLE_HUSH_FUNCTIONS
629# define CMD_FUNCDEF 3
630#endif
631
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100632 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200633 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
634 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000635#if !BB_MMU
636 char *group_as_string;
637#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000638#if ENABLE_HUSH_FUNCTIONS
639 struct function *child_func;
640/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200641 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000642 * When we execute "f1() {a;}" cmd, we create new function and clear
643 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200644 * When we execute "f1() {b;}", we notice that f1 exists,
645 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000646 * we put those fields back into cmd->xxx
647 * (struct function has ->parent_cmd ptr to facilitate that).
648 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
649 * Without this trick, loop would execute a;b;b;b;...
650 * instead of correct sequence a;b;a;b;...
651 * When command is freed, it severs the link
652 * (sets ->child_func->parent_cmd to NULL).
653 */
654#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000655 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000656/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
657 * and on execution these are substituted with their values.
658 * Substitution can make _several_ words out of one argv[n]!
659 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000660 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000661 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000662 struct redir_struct *redirects; /* I/O redirections */
663};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000664/* Is there anything in this command at all? */
665#define IS_NULL_CMD(cmd) \
666 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
667
Eric Andersen25f27032001-04-26 23:22:31 +0000668struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000669 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000670 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000671 int alive_cmds; /* number of commands running (not exited) */
672 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000673#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100674 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000675 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000676 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000677#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000678 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000679 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000680 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
681 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000682};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000683typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100684 PIPE_SEQ = 0,
685 PIPE_AND = 1,
686 PIPE_OR = 2,
687 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000688} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000689/* Is there anything in this pipe at all? */
690#define IS_NULL_PIPE(pi) \
691 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000692
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000693/* This holds pointers to the various results of parsing */
694struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000695 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000696 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000697 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000698 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000699 /* last command in pipe (being constructed right now) */
700 struct command *command;
701 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000702 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200703 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000704#if !BB_MMU
705 o_string as_string;
706#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200707 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000708#if HAS_KEYWORDS
709 smallint ctx_res_w;
710 smallint ctx_inverted; /* "! cmd | cmd" */
711#if ENABLE_HUSH_CASE
712 smallint ctx_dsemicolon; /* ";;" seen */
713#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000714 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
715 int old_flag;
716 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000717 * example: "if pipe1; pipe2; then pipe3; fi"
718 * when we see "if" or "then", we malloc and copy current context,
719 * and make ->stack point to it. then we parse pipeN.
720 * when closing "then" / fi" / whatever is found,
721 * we move list_head into ->stack->command->group,
722 * copy ->stack into current context, and delete ->stack.
723 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000724 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000725 struct parse_context *stack;
726#endif
727};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200728enum {
729 MAYBE_ASSIGNMENT = 0,
730 DEFINITELY_ASSIGNMENT = 1,
731 NOT_ASSIGNMENT = 2,
732 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
733 WORD_IS_KEYWORD = 3,
734};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000735
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000736/* On program start, environ points to initial environment.
737 * putenv adds new pointers into it, unsetenv removes them.
738 * Neither of these (de)allocates the strings.
739 * setenv allocates new strings in malloc space and does putenv,
740 * and thus setenv is unusable (leaky) for shell's purposes */
741#define setenv(...) setenv_is_leaky_dont_use()
742struct variable {
743 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000744 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000745 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200746 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000747 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000748 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000749};
750
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000751enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000752 BC_BREAK = 1,
753 BC_CONTINUE = 2,
754};
755
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000756#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000757struct function {
758 struct function *next;
759 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000760 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000761 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200762# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000763 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200764# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000765};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000766#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000767
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000768
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100769/* set -/+o OPT support. (TODO: make it optional)
770 * bash supports the following opts:
771 * allexport off
772 * braceexpand on
773 * emacs on
774 * errexit off
775 * errtrace off
776 * functrace off
777 * hashall on
778 * histexpand off
779 * history on
780 * ignoreeof off
781 * interactive-comments on
782 * keyword off
783 * monitor on
784 * noclobber off
785 * noexec off
786 * noglob off
787 * nolog off
788 * notify off
789 * nounset off
790 * onecmd off
791 * physical off
792 * pipefail off
793 * posix off
794 * privileged off
795 * verbose off
796 * vi off
797 * xtrace off
798 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800799static const char o_opt_strings[] ALIGN1 =
800 "pipefail\0"
801 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200802 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800803#if ENABLE_HUSH_MODE_X
804 "xtrace\0"
805#endif
806 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100807enum {
808 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800809 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200810 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800811#if ENABLE_HUSH_MODE_X
812 OPT_O_XTRACE,
813#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100814 NUM_OPT_O
815};
816
817
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200818struct FILE_list {
819 struct FILE_list *next;
820 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200821 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200822};
823
824
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000825/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000826/* Sorted roughly by size (smaller offsets == smaller code) */
827struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000828 /* interactive_fd != 0 means we are an interactive shell.
829 * If we are, then saved_tty_pgrp can also be != 0, meaning
830 * that controlling tty is available. With saved_tty_pgrp == 0,
831 * job control still works, but terminal signals
832 * (^C, ^Z, ^Y, ^\) won't work at all, and background
833 * process groups can only be created with "cmd &".
834 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
835 * to give tty to the foreground process group,
836 * and will take it back when the group is stopped (^Z)
837 * or killed (^C).
838 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000839#if ENABLE_HUSH_INTERACTIVE
840 /* 'interactive_fd' is a fd# open to ctty, if we have one
841 * _AND_ if we decided to act interactively */
842 int interactive_fd;
843 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200844 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000845# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000846#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000847# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000848#endif
849#if ENABLE_FEATURE_EDITING
850 line_input_t *line_input_state;
851#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000852 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200853 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000854 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200855#if ENABLE_HUSH_RANDOM_SUPPORT
856 random_t random_gen;
857#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000858#if ENABLE_HUSH_JOB
859 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100860 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000861 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000862 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400863# define G_saved_tty_pgrp (G.saved_tty_pgrp)
864#else
865# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000866#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200867 /* How deeply are we in context where "set -e" is ignored */
868 int errexit_depth;
869 /* "set -e" rules (do we follow them correctly?):
870 * Exit if pipe, list, or compound command exits with a non-zero status.
871 * Shell does not exit if failed command is part of condition in
872 * if/while, part of && or || list except the last command, any command
873 * in a pipe but the last, or if the command's return value is being
874 * inverted with !. If a compound command other than a subshell returns a
875 * non-zero status because a command failed while -e was being ignored, the
876 * shell does not exit. A trap on ERR, if set, is executed before the shell
877 * exits [ERR is a bashism].
878 *
879 * If a compound command or function executes in a context where -e is
880 * ignored, none of the commands executed within are affected by the -e
881 * setting. If a compound command or function sets -e while executing in a
882 * context where -e is ignored, that setting does not have any effect until
883 * the compound command or the command containing the function call completes.
884 */
885
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100886 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100887#if ENABLE_HUSH_MODE_X
888# define G_x_mode (G.o_opt[OPT_O_XTRACE])
889#else
890# define G_x_mode 0
891#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200892#if ENABLE_HUSH_INTERACTIVE
893 smallint promptmode; /* 0: PS1, 1: PS2 */
894#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000895 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000896#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000897 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000898#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000899#if ENABLE_HUSH_FUNCTIONS
900 /* 0: outside of a function (or sourced file)
901 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000902 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000903 */
904 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200905# define G_flag_return_in_progress (G.flag_return_in_progress)
906#else
907# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000908#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000909 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200910 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000911 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200912 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200913 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100914#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000915 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000916 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100917# define G_global_args_malloced (G.global_args_malloced)
918#else
919# define G_global_args_malloced 0
920#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000921 /* how many non-NULL argv's we have. NB: $# + 1 */
922 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000923 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000924#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000925 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000926#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000927#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000928 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000929 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000930#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200931#if ENABLE_HUSH_GETOPTS
932 unsigned getopt_count;
933#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000934 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200935 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000936 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200937 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200938 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200939 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200940 unsigned var_nest_level;
941#if ENABLE_HUSH_FUNCTIONS
942# if ENABLE_HUSH_LOCAL
943 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200944# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200945 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000946#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000947 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200948#if ENABLE_HUSH_FAST
949 unsigned count_SIGCHLD;
950 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200951 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200952#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100953#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100954 unsigned lineno;
955 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100956#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200957 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200958 /* Which signals have non-DFL handler (even with no traps set)?
959 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200960 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200961 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200962 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200963 * Other than these two times, never modified.
964 */
965 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200966#if ENABLE_HUSH_JOB
967 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100968# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200969#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200970# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200971#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100972#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000973 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100974# define G_traps G.traps
975#else
976# define G_traps ((char**)NULL)
977#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200978 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100979#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000980 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100981#endif
982#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000983 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000984#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200985 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200986#if ENABLE_FEATURE_EDITING
987 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
988#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000989};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000990#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000991/* Not #defining name to G.name - this quickly gets unwieldy
992 * (too many defines). Also, I actually prefer to see when a variable
993 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000994#define INIT_G() do { \
995 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200996 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
997 sigfillset(&G.sa.sa_mask); \
998 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000999} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001000
1001
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001002/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001003static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001004#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001005static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001006#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001007static int builtin_eval(char **argv) FAST_FUNC;
1008static int builtin_exec(char **argv) FAST_FUNC;
1009static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001010#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001011static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001012#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001013#if ENABLE_HUSH_READONLY
1014static int builtin_readonly(char **argv) FAST_FUNC;
1015#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001016#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001017static int builtin_fg_bg(char **argv) FAST_FUNC;
1018static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001019#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001020#if ENABLE_HUSH_GETOPTS
1021static int builtin_getopts(char **argv) FAST_FUNC;
1022#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001023#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001024static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001025#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001026#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001027static int builtin_history(char **argv) FAST_FUNC;
1028#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001029#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001030static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001031#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001032#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001033static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001034#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001035#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001036static int builtin_printf(char **argv) FAST_FUNC;
1037#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001038static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001039#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001040static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001041#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001042#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001043static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001044#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001045static int builtin_shift(char **argv) FAST_FUNC;
1046static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001047#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001048static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001049#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001050#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001051static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001052#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001053#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001055#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001056#if ENABLE_HUSH_TIMES
1057static int builtin_times(char **argv) FAST_FUNC;
1058#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001060#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001061static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001062#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001063#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001064static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001065#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001066#if ENABLE_HUSH_KILL
1067static int builtin_kill(char **argv) FAST_FUNC;
1068#endif
1069#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001070static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001071#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001072#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001073static int builtin_break(char **argv) FAST_FUNC;
1074static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001075#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001076#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001077static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001078#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001079
1080/* Table of built-in functions. They can be forked or not, depending on
1081 * context: within pipes, they fork. As simple commands, they do not.
1082 * When used in non-forking context, they can change global variables
1083 * in the parent shell process. If forked, of course they cannot.
1084 * For example, 'unset foo | whatever' will parse and run, but foo will
1085 * still be set at the end. */
1086struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001087 const char *b_cmd;
1088 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001089#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001090 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001091# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001092#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001093# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001094#endif
1095};
1096
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001097static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001098 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001099 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001100#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001101 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001102#endif
1103#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001104 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001105#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001106 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001107#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001108 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001109#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001110 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1111 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001112 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001113#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001114 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001115#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001116#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001117 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001118#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001119#if ENABLE_HUSH_GETOPTS
1120 BLTIN("getopts" , builtin_getopts , NULL),
1121#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001122#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001123 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001124#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001125#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001126 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001127#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001128#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001129 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001130#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001131#if ENABLE_HUSH_KILL
1132 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1133#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001134#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001135 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001136#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001137#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001138 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001139#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001140#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001141 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001142#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001143#if ENABLE_HUSH_READONLY
1144 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1145#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001146#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001147 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001148#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001149#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001150 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001151#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001152 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001153#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001154 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001155#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001156#if ENABLE_HUSH_TIMES
1157 BLTIN("times" , builtin_times , NULL),
1158#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001159#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001160 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001161#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001162 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001163#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001164 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001165#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001166#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001167 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001168#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001169#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001171#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001172#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001173 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001174#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001175#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001176 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001177#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001178};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001179/* These builtins won't be used if we are on NOMMU and need to re-exec
1180 * (it's cheaper to run an external program in this case):
1181 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001182static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001183#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001184 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001185#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001186#if BASH_TEST2
1187 BLTIN("[[" , builtin_test , NULL),
1188#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001189#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001190 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001191#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001192#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001193 BLTIN("printf" , builtin_printf , NULL),
1194#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001195 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001196#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001197 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001198#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001199};
1200
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001201
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001202/* Debug printouts.
1203 */
1204#if HUSH_DEBUG
1205/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001206# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001207# define debug_enter() (G.debug_indent++)
1208# define debug_leave() (G.debug_indent--)
1209#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001210# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001211# define debug_enter() ((void)0)
1212# define debug_leave() ((void)0)
1213#endif
1214
1215#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001216# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001217#endif
1218
1219#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001220# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001221#endif
1222
Denys Vlasenko3675c372018-07-23 16:31:21 +02001223#ifndef debug_printf_heredoc
1224# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1225#endif
1226
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001227#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001228#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001229#endif
1230
1231#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001232# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001233#endif
1234
1235#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001236# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001237# define DEBUG_JOBS 1
1238#else
1239# define DEBUG_JOBS 0
1240#endif
1241
1242#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001243# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001244# define DEBUG_EXPAND 1
1245#else
1246# define DEBUG_EXPAND 0
1247#endif
1248
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001249#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001250# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001251#endif
1252
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001253#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001254# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001255# define DEBUG_GLOB 1
1256#else
1257# define DEBUG_GLOB 0
1258#endif
1259
Denys Vlasenko2db74612017-07-07 22:07:28 +02001260#ifndef debug_printf_redir
1261# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1262#endif
1263
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001264#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001265# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001266#endif
1267
1268#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001269# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001270#endif
1271
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001272#ifndef debug_printf_prompt
1273# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1274#endif
1275
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001276#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001277# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001278# define DEBUG_CLEAN 1
1279#else
1280# define DEBUG_CLEAN 0
1281#endif
1282
1283#if DEBUG_EXPAND
1284static void debug_print_strings(const char *prefix, char **vv)
1285{
1286 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001287 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001288 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001289 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001290}
1291#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001292# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001293#endif
1294
1295
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001296/* Leak hunting. Use hush_leaktool.sh for post-processing.
1297 */
1298#if LEAK_HUNTING
1299static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001300{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001301 void *ptr = xmalloc((size + 0xff) & ~0xff);
1302 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1303 return ptr;
1304}
1305static void *xxrealloc(int lineno, void *ptr, size_t size)
1306{
1307 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1308 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1309 return ptr;
1310}
1311static char *xxstrdup(int lineno, const char *str)
1312{
1313 char *ptr = xstrdup(str);
1314 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1315 return ptr;
1316}
1317static void xxfree(void *ptr)
1318{
1319 fdprintf(2, "free %p\n", ptr);
1320 free(ptr);
1321}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001322# define xmalloc(s) xxmalloc(__LINE__, s)
1323# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1324# define xstrdup(s) xxstrdup(__LINE__, s)
1325# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001326#endif
1327
1328
1329/* Syntax and runtime errors. They always abort scripts.
1330 * In interactive use they usually discard unparsed and/or unexecuted commands
1331 * and return to the prompt.
1332 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1333 */
1334#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001335# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001336# define syntax_error(lineno, msg) syntax_error(msg)
1337# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1338# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1339# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1340# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001341#endif
1342
Denys Vlasenko39701202017-08-02 19:44:05 +02001343static void die_if_script(void)
1344{
1345 if (!G_interactive_fd) {
1346 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1347 xfunc_error_retval = G.last_exitcode;
1348 xfunc_die();
1349 }
1350}
1351
1352static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001353{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001354 va_list p;
1355
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001356#if HUSH_DEBUG >= 2
1357 bb_error_msg("hush.c:%u", lineno);
1358#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001359 va_start(p, fmt);
1360 bb_verror_msg(fmt, p, NULL);
1361 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001362 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001363}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001364
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001365static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001366{
1367 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001368 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001369 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001370 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001371 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001372}
1373
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001374static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001375{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001376 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001377 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001378}
1379
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001380static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001381{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001382 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001383//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1384// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001385}
1386
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001387static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001388{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001389 char msg[2] = { ch, '\0' };
1390 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001391}
1392
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001393static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001394{
1395 char msg[2];
1396 msg[0] = ch;
1397 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001398#if HUSH_DEBUG >= 2
1399 bb_error_msg("hush.c:%u", lineno);
1400#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001401 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001402 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001403}
1404
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001405#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001406# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001407# undef syntax_error
1408# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001409# undef syntax_error_unterm_ch
1410# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001411# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001412#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001413# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001414# define syntax_error(msg) syntax_error(__LINE__, msg)
1415# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1416# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1417# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1418# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001419#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001420
Denis Vlasenko552433b2009-04-04 19:29:21 +00001421
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001422#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001423static void cmdedit_update_prompt(void);
1424#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001425# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001426#endif
1427
1428
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001429/* Utility functions
1430 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001431/* Replace each \x with x in place, return ptr past NUL. */
1432static char *unbackslash(char *src)
1433{
Denys Vlasenko71885402009-09-24 01:44:13 +02001434 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001435 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001436 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001437 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001438 if (*src != '\0') {
1439 /* \x -> x */
1440 *dst++ = *src++;
1441 continue;
1442 }
1443 /* else: "\<nul>". Do not delete this backslash.
1444 * Testcase: eval 'echo ok\'
1445 */
1446 *dst++ = '\\';
1447 /* fallthrough */
1448 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001449 if ((*dst++ = *src++) == '\0')
1450 break;
1451 }
1452 return dst;
1453}
1454
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001455static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001456{
1457 int i;
1458 unsigned count1;
1459 unsigned count2;
1460 char **v;
1461
1462 v = strings;
1463 count1 = 0;
1464 if (v) {
1465 while (*v) {
1466 count1++;
1467 v++;
1468 }
1469 }
1470 count2 = 0;
1471 v = add;
1472 while (*v) {
1473 count2++;
1474 v++;
1475 }
1476 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1477 v[count1 + count2] = NULL;
1478 i = count2;
1479 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001480 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001481 return v;
1482}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001483#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001484static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1485{
1486 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1487 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1488 return ptr;
1489}
1490#define add_strings_to_strings(strings, add, need_to_dup) \
1491 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1492#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001493
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001494/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001495static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001496{
1497 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001498 v[0] = add;
1499 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001500 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001501}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001502#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001503static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1504{
1505 char **ptr = add_string_to_strings(strings, add);
1506 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1507 return ptr;
1508}
1509#define add_string_to_strings(strings, add) \
1510 xx_add_string_to_strings(__LINE__, strings, add)
1511#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001512
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001513static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001514{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001515 char **v;
1516
1517 if (!strings)
1518 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001519 v = strings;
1520 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001521 free(*v);
1522 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001523 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001524 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001525}
1526
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001527static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001528{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001529 int newfd;
1530 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001531 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1532 if (newfd >= 0) {
1533 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1534 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1535 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001536 if (errno == EBUSY)
1537 goto repeat;
1538 if (errno == EINTR)
1539 goto repeat;
1540 }
1541 return newfd;
1542}
1543
Denys Vlasenko657e9002017-07-30 23:34:04 +02001544static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001545{
1546 int newfd;
1547 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001548 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001549 if (newfd < 0) {
1550 if (errno == EBUSY)
1551 goto repeat;
1552 if (errno == EINTR)
1553 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001554 /* fd was not open? */
1555 if (errno == EBADF)
1556 return fd;
1557 xfunc_die();
1558 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001559 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1560 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001561 close(fd);
1562 return newfd;
1563}
1564
1565
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001566/* Manipulating the list of open FILEs */
1567static FILE *remember_FILE(FILE *fp)
1568{
1569 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001570 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001571 n->next = G.FILE_list;
1572 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001573 n->fp = fp;
1574 n->fd = fileno(fp);
1575 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001576 }
1577 return fp;
1578}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001579static void fclose_and_forget(FILE *fp)
1580{
1581 struct FILE_list **pp = &G.FILE_list;
1582 while (*pp) {
1583 struct FILE_list *cur = *pp;
1584 if (cur->fp == fp) {
1585 *pp = cur->next;
1586 free(cur);
1587 break;
1588 }
1589 pp = &cur->next;
1590 }
1591 fclose(fp);
1592}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001593static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001594{
1595 struct FILE_list *fl = G.FILE_list;
1596 while (fl) {
1597 if (fd == fl->fd) {
1598 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001599 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001600 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 +02001601 return 1;
1602 }
1603 fl = fl->next;
1604 }
1605 return 0;
1606}
1607static void restore_redirected_FILEs(void)
1608{
1609 struct FILE_list *fl = G.FILE_list;
1610 while (fl) {
1611 int should_be = fileno(fl->fp);
1612 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001613 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001614 xmove_fd(fl->fd, should_be);
1615 fl->fd = should_be;
1616 }
1617 fl = fl->next;
1618 }
1619}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001620#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001621static void close_all_FILE_list(void)
1622{
1623 struct FILE_list *fl = G.FILE_list;
1624 while (fl) {
1625 /* fclose would also free FILE object.
1626 * It is disastrous if we share memory with a vforked parent.
1627 * I'm not sure we never come here after vfork.
1628 * Therefore just close fd, nothing more.
1629 */
1630 /*fclose(fl->fp); - unsafe */
1631 close(fl->fd);
1632 fl = fl->next;
1633 }
1634}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001635#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001636static int fd_in_FILEs(int fd)
1637{
1638 struct FILE_list *fl = G.FILE_list;
1639 while (fl) {
1640 if (fl->fd == fd)
1641 return 1;
1642 fl = fl->next;
1643 }
1644 return 0;
1645}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001646
1647
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001648/* Helpers for setting new $n and restoring them back
1649 */
1650typedef struct save_arg_t {
1651 char *sv_argv0;
1652 char **sv_g_argv;
1653 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001654 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001655} save_arg_t;
1656
1657static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1658{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001659 sv->sv_argv0 = argv[0];
1660 sv->sv_g_argv = G.global_argv;
1661 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001662 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001663
1664 argv[0] = G.global_argv[0]; /* retain $0 */
1665 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001666 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001667
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001668 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001669}
1670
1671static void restore_G_args(save_arg_t *sv, char **argv)
1672{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001673#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001674 if (G.global_args_malloced) {
1675 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001676 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001677 while (*++pp) /* note: does not free $0 */
1678 free(*pp);
1679 free(G.global_argv);
1680 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001681#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001682 argv[0] = sv->sv_argv0;
1683 G.global_argv = sv->sv_g_argv;
1684 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001685 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001686}
1687
1688
Denis Vlasenkod5762932009-03-31 11:22:57 +00001689/* Basic theory of signal handling in shell
1690 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001691 * This does not describe what hush does, rather, it is current understanding
1692 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001693 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1694 *
1695 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1696 * is finished or backgrounded. It is the same in interactive and
1697 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001698 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001699 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001700 * backgrounds (i.e. stops) or kills all members of currently running
1701 * pipe.
1702 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001703 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001704 * or by SIGINT in interactive shell.
1705 *
1706 * Trap handlers will execute even within trap handlers. (right?)
1707 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001708 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1709 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001710 *
1711 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001712 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001713 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001714 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001715 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001716 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001717 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001718 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001719 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001720 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001721 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001722 *
1723 * SIGQUIT: ignore
1724 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001725 * SIGHUP (interactive):
1726 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001727 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001728 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1729 * that all pipe members are stopped. Try this in bash:
1730 * while :; do :; done - ^Z does not background it
1731 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001732 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001733 * of the command line, show prompt. NB: ^C does not send SIGINT
1734 * to interactive shell while shell is waiting for a pipe,
1735 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001736 * Example 1: this waits 5 sec, but does not execute ls:
1737 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1738 * Example 2: this does not wait and does not execute ls:
1739 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1740 * Example 3: this does not wait 5 sec, but executes ls:
1741 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001742 * Example 4: this does not wait and does not execute ls:
1743 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001744 *
1745 * (What happens to signals which are IGN on shell start?)
1746 * (What happens with signal mask on shell start?)
1747 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001748 * Old implementation
1749 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001750 * We use in-kernel pending signal mask to determine which signals were sent.
1751 * We block all signals which we don't want to take action immediately,
1752 * i.e. we block all signals which need to have special handling as described
1753 * above, and all signals which have traps set.
1754 * After each pipe execution, we extract any pending signals via sigtimedwait()
1755 * and act on them.
1756 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001757 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001758 * sigset_t blocked_set: current blocked signal set
1759 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001760 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001761 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001762 * "trap 'cmd' SIGxxx":
1763 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001764 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001765 * unblock signals with special interactive handling
1766 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001767 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001768 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001769 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001770 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001771 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001772 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001773 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001774 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001775 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001776 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001777 * Standard says "When a subshell is entered, traps that are not being ignored
1778 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001779 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001780 *
1781 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001782 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001783 * masked signals are not visible!
1784 *
1785 * New implementation
1786 * ==================
1787 * We record each signal we are interested in by installing signal handler
1788 * for them - a bit like emulating kernel pending signal mask in userspace.
1789 * We are interested in: signals which need to have special handling
1790 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001791 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001792 * After each pipe execution, we extract any pending signals
1793 * and act on them.
1794 *
1795 * unsigned special_sig_mask: a mask of shell-special signals.
1796 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1797 * char *traps[sig] if trap for sig is set (even if it's '').
1798 * sigset_t pending_set: set of sigs we received.
1799 *
1800 * "trap - SIGxxx":
1801 * if sig is in special_sig_mask, set handler back to:
1802 * record_pending_signo, or to IGN if it's a tty stop signal
1803 * if sig is in fatal_sig_mask, set handler back to sigexit.
1804 * else: set handler back to SIG_DFL
1805 * "trap 'cmd' SIGxxx":
1806 * set handler to record_pending_signo.
1807 * "trap '' SIGxxx":
1808 * set handler to SIG_IGN.
1809 * after [v]fork, if we plan to be a shell:
1810 * set signals with special interactive handling to SIG_DFL
1811 * (because child shell is not interactive),
1812 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1813 * after [v]fork, if we plan to exec:
1814 * POSIX says fork clears pending signal mask in child - no need to clear it.
1815 *
1816 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1817 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1818 *
1819 * Note (compat):
1820 * Standard says "When a subshell is entered, traps that are not being ignored
1821 * are set to the default actions". bash interprets it so that traps which
1822 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001823 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001824enum {
1825 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001826 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001827 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001828 | (1 << SIGHUP)
1829 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001830 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001831#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001832 | (1 << SIGTTIN)
1833 | (1 << SIGTTOU)
1834 | (1 << SIGTSTP)
1835#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001836 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001837};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001838
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001839static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001840{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001841 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001842#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001843 if (sig == SIGCHLD) {
1844 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001845//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 +02001846 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001847#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001848}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001849
Denys Vlasenko0806e402011-05-12 23:06:20 +02001850static sighandler_t install_sighandler(int sig, sighandler_t handler)
1851{
1852 struct sigaction old_sa;
1853
1854 /* We could use signal() to install handlers... almost:
1855 * except that we need to mask ALL signals while handlers run.
1856 * I saw signal nesting in strace, race window isn't small.
1857 * SA_RESTART is also needed, but in Linux, signal()
1858 * sets SA_RESTART too.
1859 */
1860 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1861 /* sigfillset(&G.sa.sa_mask); - already done */
1862 /* G.sa.sa_flags = SA_RESTART; - already done */
1863 G.sa.sa_handler = handler;
1864 sigaction(sig, &G.sa, &old_sa);
1865 return old_sa.sa_handler;
1866}
1867
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001868static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001869
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001870static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001871static void restore_ttypgrp_and__exit(void)
1872{
1873 /* xfunc has failed! die die die */
1874 /* no EXIT traps, this is an escape hatch! */
1875 G.exiting = 1;
1876 hush_exit(xfunc_error_retval);
1877}
1878
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001879#if ENABLE_HUSH_JOB
1880
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001881/* Needed only on some libc:
1882 * It was observed that on exit(), fgetc'ed buffered data
1883 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1884 * With the net effect that even after fork(), not vfork(),
1885 * exit() in NOEXECed applet in "sh SCRIPT":
1886 * noexec_applet_here
1887 * echo END_OF_SCRIPT
1888 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1889 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001890 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001891 * and in `cmd` handling.
1892 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1893 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001894static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001895static void fflush_and__exit(void)
1896{
1897 fflush_all();
1898 _exit(xfunc_error_retval);
1899}
1900
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001901/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001902# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001903/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001904# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001905
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001906/* Restores tty foreground process group, and exits.
1907 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001908 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001909 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001910 * We also call it if xfunc is exiting.
1911 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001912static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001913static void sigexit(int sig)
1914{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001915 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001916 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001917 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1918 /* Disable all signals: job control, SIGPIPE, etc.
1919 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1920 */
1921 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001922 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001923 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001924
1925 /* Not a signal, just exit */
1926 if (sig <= 0)
1927 _exit(- sig);
1928
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001929 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001930}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001931#else
1932
Denys Vlasenko8391c482010-05-22 17:50:43 +02001933# define disable_restore_tty_pgrp_on_exit() ((void)0)
1934# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001935
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001936#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001937
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001938static sighandler_t pick_sighandler(unsigned sig)
1939{
1940 sighandler_t handler = SIG_DFL;
1941 if (sig < sizeof(unsigned)*8) {
1942 unsigned sigmask = (1 << sig);
1943
1944#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001945 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001946 if (G_fatal_sig_mask & sigmask)
1947 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001948 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001949#endif
1950 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001951 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001952 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001953 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001954 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001955 * in an endless loop when we try to do some
1956 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001957 */
1958 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1959 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001960 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001961 }
1962 return handler;
1963}
1964
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001965/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001966static void hush_exit(int exitcode)
1967{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001968#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1969 save_history(G.line_input_state);
1970#endif
1971
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001972 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001973 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001974 char *argv[3];
1975 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001976 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001977 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001978 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001979 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001980 * "trap" will still show it, if executed
1981 * in the handler */
1982 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001983 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001984
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001985#if ENABLE_FEATURE_CLEAN_UP
1986 {
1987 struct variable *cur_var;
1988 if (G.cwd != bb_msg_unknown)
1989 free((char*)G.cwd);
1990 cur_var = G.top_var;
1991 while (cur_var) {
1992 struct variable *tmp = cur_var;
1993 if (!cur_var->max_len)
1994 free(cur_var->varstr);
1995 cur_var = cur_var->next;
1996 free(tmp);
1997 }
1998 }
1999#endif
2000
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002001 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002002#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002003 sigexit(- (exitcode & 0xff));
2004#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002005 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002006#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002007}
2008
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002009
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002010//TODO: return a mask of ALL handled sigs?
2011static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002012{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002013 int last_sig = 0;
2014
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002015 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002016 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002017
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002018 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002019 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002020 sig = 0;
2021 do {
2022 sig++;
2023 if (sigismember(&G.pending_set, sig)) {
2024 sigdelset(&G.pending_set, sig);
2025 goto got_sig;
2026 }
2027 } while (sig < NSIG);
2028 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002029 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002030 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002031 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002032 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002033 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002034 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002035 char *argv[3];
2036 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002037 argv[1] = xstrdup(G_traps[sig]);
2038 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002039 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002040 save_rcode = G.last_exitcode;
2041 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002042 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002043//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002044 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002045 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002046 } /* else: "" trap, ignoring signal */
2047 continue;
2048 }
2049 /* not a trap: special action */
2050 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002051 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002052 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002053 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002054 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002055 break;
2056#if ENABLE_HUSH_JOB
2057 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002058//TODO: why are we doing this? ash and dash don't do this,
2059//they have no handler for SIGHUP at all,
2060//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002061 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002062 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002063 /* bash is observed to signal whole process groups,
2064 * not individual processes */
2065 for (job = G.job_list; job; job = job->next) {
2066 if (job->pgrp <= 0)
2067 continue;
2068 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2069 if (kill(- job->pgrp, SIGHUP) == 0)
2070 kill(- job->pgrp, SIGCONT);
2071 }
2072 sigexit(SIGHUP);
2073 }
2074#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002075#if ENABLE_HUSH_FAST
2076 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002077 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002078 G.count_SIGCHLD++;
2079//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2080 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002081 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002082 * This simplifies wait builtin a bit.
2083 */
2084 break;
2085#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002086 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002087 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002088 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002089 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002090 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002091 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002092 * in interactive shell, because TERM is ignored.
2093 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002094 break;
2095 }
2096 }
2097 return last_sig;
2098}
2099
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002100
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002101static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002102{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002103 if (force || G.cwd == NULL) {
2104 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2105 * we must not try to free(bb_msg_unknown) */
2106 if (G.cwd == bb_msg_unknown)
2107 G.cwd = NULL;
2108 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2109 if (!G.cwd)
2110 G.cwd = bb_msg_unknown;
2111 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002112 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002113}
2114
Denis Vlasenko83506862007-11-23 13:11:42 +00002115
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002116/*
2117 * Shell and environment variable support
2118 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002119static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002120{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002121 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002122 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002123
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002124 pp = &G.top_var;
2125 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002126 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002127 return pp;
2128 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129 }
2130 return NULL;
2131}
2132
Denys Vlasenko03dad222010-01-12 23:29:57 +01002133static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002134{
Denys Vlasenko29082232010-07-16 13:52:32 +02002135 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002136 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002137
2138 if (G.expanded_assignments) {
2139 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002140 while (*cpp) {
2141 char *cp = *cpp;
2142 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2143 return cp + len + 1;
2144 cpp++;
2145 }
2146 }
2147
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002148 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002149 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002150 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002151
Denys Vlasenkodea47882009-10-09 15:40:49 +02002152 if (strcmp(name, "PPID") == 0)
2153 return utoa(G.root_ppid);
2154 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002155#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002156 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002157 return utoa(next_random(&G.random_gen));
2158#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002159 return NULL;
2160}
2161
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002162static void handle_changed_special_names(const char *name, unsigned name_len)
2163{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002164 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2165 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2166 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002167 cmdedit_update_prompt();
2168 return;
2169 }
2170
2171 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2172 && name_len == 6
2173 ) {
2174#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002175 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002176 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002177 return;
2178 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002179#endif
2180#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002181 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002182 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002183 return;
2184 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002185#endif
2186 }
2187}
2188
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002189/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002190 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002191 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002192#define SETFLAG_EXPORT (1 << 0)
2193#define SETFLAG_UNEXPORT (1 << 1)
2194#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002195#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002196static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002197{
Denys Vlasenko61407802018-04-04 21:14:28 +02002198 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002199 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002200 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002201 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002203 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002204
Denis Vlasenko950bd722009-04-21 11:23:56 +00002205 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002206 if (HUSH_DEBUG && !eq_sign)
2207 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002208
Denis Vlasenko950bd722009-04-21 11:23:56 +00002209 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002210 cur_pp = &G.top_var;
2211 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002212 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002213 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002214 continue;
2215 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002216
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002217 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002218 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002219 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002220 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002221//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2222//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002223 return -1;
2224 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002225 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002226 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2227 *eq_sign = '\0';
2228 unsetenv(str);
2229 *eq_sign = '=';
2230 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002231 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002232 /* bash 3.2.33(1) and exported vars:
2233 * # export z=z
2234 * # f() { local z=a; env | grep ^z; }
2235 * # f
2236 * z=a
2237 * # env | grep ^z
2238 * z=z
2239 */
2240 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002241 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002242 /* New variable is local ("local VAR=VAL" or
2243 * "VAR=VAL cmd")
2244 * and existing one is global, or local
2245 * on a lower level that new one.
2246 * Remove it from global variable list:
2247 */
2248 *cur_pp = cur->next;
2249 if (G.shadowed_vars_pp) {
2250 /* Save in "shadowed" list */
2251 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2252 cur->flg_export ? "exported " : "",
2253 cur->varstr, cur->var_nest_level, str, local_lvl
2254 );
2255 cur->next = *G.shadowed_vars_pp;
2256 *G.shadowed_vars_pp = cur;
2257 } else {
2258 /* Came from pseudo_exec_argv(), no need to save: delete it */
2259 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2260 cur->flg_export ? "exported " : "",
2261 cur->varstr, cur->var_nest_level, str, local_lvl
2262 );
2263 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2264 free_me = cur->varstr; /* then free it later */
2265 free(cur);
2266 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002267 break;
2268 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002269
Denis Vlasenko950bd722009-04-21 11:23:56 +00002270 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002271 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002272 free_and_exp:
2273 free(str);
2274 goto exp;
2275 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002276
2277 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002278 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002279 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002280 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002281 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002282 strcpy(cur->varstr, str);
2283 goto free_and_exp;
2284 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002285 /* Can't reuse */
2286 cur->max_len = 0;
2287 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002288 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002289 /* max_len == 0 signifies "malloced" var, which we can
2290 * (and have to) free. But we can't free(cur->varstr) here:
2291 * if cur->flg_export is 1, it is in the environment.
2292 * We should either unsetenv+free, or wait until putenv,
2293 * then putenv(new)+free(old).
2294 */
2295 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002296 goto set_str_and_exp;
2297 }
2298
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002299 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002300 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002301 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002302 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002303 cur->next = *cur_pp;
2304 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002305
2306 set_str_and_exp:
2307 cur->varstr = str;
2308 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002309#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002310 if (flags & SETFLAG_MAKE_RO) {
2311 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002312 }
2313#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002314 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315 cur->flg_export = 1;
2316 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002317 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002318 cur->flg_export = 0;
2319 /* unsetenv was already done */
2320 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002321 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002322 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002323 i = putenv(cur->varstr);
2324 /* only now we can free old exported malloced string */
2325 free(free_me);
2326 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002327 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002328 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002329 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002330
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002331 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002332
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002333 return 0;
2334}
2335
Denys Vlasenko6db47842009-09-05 20:15:17 +02002336/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002337static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002338{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002339 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002340}
2341
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002342#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002343static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002344{
2345 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002346 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002347
Denys Vlasenko61407802018-04-04 21:14:28 +02002348 cur_pp = &G.top_var;
2349 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002350 if (strncmp(cur->varstr, name, name_len) == 0
2351 && cur->varstr[name_len] == '='
2352 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002353 if (cur->flg_read_only) {
2354 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002355 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002356 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002357
Denys Vlasenko61407802018-04-04 21:14:28 +02002358 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002359 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2360 bb_unsetenv(cur->varstr);
2361 if (!cur->max_len)
2362 free(cur->varstr);
2363 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002364
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002365 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002366 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002367 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002368 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002369
2370 /* Handle "unset PS1" et al even if did not find the variable to unset */
2371 handle_changed_special_names(name, name_len);
2372
Mike Frysingerd690f682009-03-30 06:50:54 +00002373 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002374}
2375
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002376static int unset_local_var(const char *name)
2377{
2378 return unset_local_var_len(name, strlen(name));
2379}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002380#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002381
Denys Vlasenkob2b14cb2018-06-26 18:09:22 +02002382#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2383 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002384static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002385{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002386 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002387 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002388}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002389#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002390
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002391
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002392/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002393 * Helpers for "var1=val1 var2=val2 cmd" feature
2394 */
2395static void add_vars(struct variable *var)
2396{
2397 struct variable *next;
2398
2399 while (var) {
2400 next = var->next;
2401 var->next = G.top_var;
2402 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002403 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002404 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002405 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002406 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002407 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002408 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002409 var = next;
2410 }
2411}
2412
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002413/* We put strings[i] into variable table and possibly putenv them.
2414 * If variable is read only, we can free the strings[i]
2415 * which attempts to overwrite it.
2416 * The strings[] vector itself is freed.
2417 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002418static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002419{
2420 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002421
2422 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002423 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002424
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002425 s = strings;
2426 while (*s) {
2427 struct variable *var_p;
2428 struct variable **var_pp;
2429 char *eq;
2430
2431 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002432 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002433 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002434 var_pp = get_ptr_to_local_var(*s, eq - *s);
2435 if (var_pp) {
2436 var_p = *var_pp;
2437 if (var_p->flg_read_only) {
2438 char **p;
2439 bb_error_msg("%s: readonly variable", *s);
2440 /*
2441 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2442 * If VAR is readonly, leaving it in the list
2443 * after asssignment error (msg above)
2444 * causes doubled error message later, on unset.
2445 */
2446 debug_printf_env("removing/freeing '%s' element\n", *s);
2447 free(*s);
2448 p = s;
2449 do { *p = p[1]; p++; } while (*p);
2450 goto next;
2451 }
2452 /* below, set_local_var() with nest level will
2453 * "shadow" (remove) this variable from
2454 * global linked list.
2455 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002456 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002457 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2458 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002459 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002460 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002461 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002462 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002463}
2464
2465
2466/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002467 * Unicode helper
2468 */
2469static void reinit_unicode_for_hush(void)
2470{
2471 /* Unicode support should be activated even if LANG is set
2472 * _during_ shell execution, not only if it was set when
2473 * shell was started. Therefore, re-check LANG every time:
2474 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002475 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2476 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002477 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002478 const char *s = get_local_var_value("LC_ALL");
2479 if (!s) s = get_local_var_value("LC_CTYPE");
2480 if (!s) s = get_local_var_value("LANG");
2481 reinit_unicode(s);
2482 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002483}
2484
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002485/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002486 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002487 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002488
2489#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002490/* To test correct lineedit/interactive behavior, type from command line:
2491 * echo $P\
2492 * \
2493 * AT\
2494 * H\
2495 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002496 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002497 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002498# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002499static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002500{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002501 G.PS1 = get_local_var_value("PS1");
2502 if (G.PS1 == NULL)
2503 G.PS1 = "";
2504 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002505 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002506 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002507}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002508# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002509static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002510{
2511 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002512
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002513 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002514
2515 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2516 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002517 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002518 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2519 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002520 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002521 /* bash uses $PWD value, even if it is set by user.
2522 * It uses current dir only if PWD is unset.
2523 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002524 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002525 }
2526 prompt_str = G.PS1;
2527 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002528 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002529 return prompt_str;
2530}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002531static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002532{
2533 int r;
2534 const char *prompt_str;
2535
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002536 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002537# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002538 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002539 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002540 if (G.flag_SIGINT) {
2541 /* There was ^C'ed, make it look prettier: */
2542 bb_putchar('\n');
2543 G.flag_SIGINT = 0;
2544 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002545 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002546 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002547 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002548 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002549 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002550 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002551 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002552 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002553 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002554 if (r != 0 && !G.flag_SIGINT)
2555 break;
2556 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002557 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2558 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002559 G.last_exitcode = 128 + SIGINT;
2560 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002561 if (r < 0) {
2562 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002563 i->p = NULL;
2564 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002565 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002566 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002567 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002568 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002569# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002570 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002571 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002572 if (i->last_char == '\0' || i->last_char == '\n') {
2573 /* Why check_and_run_traps here? Try this interactively:
2574 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2575 * $ <[enter], repeatedly...>
2576 * Without check_and_run_traps, handler never runs.
2577 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002578 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002579 fputs(prompt_str, stdout);
2580 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002581 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002582//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002583 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002584 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2585 * no ^C masking happens during fgetc, no special code for ^C:
2586 * it generates SIGINT as usual.
2587 */
2588 check_and_run_traps();
2589 if (G.flag_SIGINT)
2590 G.last_exitcode = 128 + SIGINT;
2591 if (r != '\0')
2592 break;
2593 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002594 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002595# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002596}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002597/* This is the magic location that prints prompts
2598 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002599static int fgetc_interactive(struct in_str *i)
2600{
2601 int ch;
2602 /* If it's interactive stdin, get new line. */
2603 if (G_interactive_fd && i->file == stdin) {
2604 /* Returns first char (or EOF), the rest is in i->p[] */
2605 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002606 G.promptmode = 1; /* PS2 */
2607 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002608 } else {
2609 /* Not stdin: script file, sourced file, etc */
2610 do ch = fgetc(i->file); while (ch == '\0');
2611 }
2612 return ch;
2613}
2614#else
2615static inline int fgetc_interactive(struct in_str *i)
2616{
2617 int ch;
2618 do ch = fgetc(i->file); while (ch == '\0');
2619 return ch;
2620}
2621#endif /* INTERACTIVE */
2622
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002623static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002624{
2625 int ch;
2626
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002627 if (!i->file) {
2628 /* string-based in_str */
2629 ch = (unsigned char)*i->p;
2630 if (ch != '\0') {
2631 i->p++;
2632 i->last_char = ch;
2633 return ch;
2634 }
2635 return EOF;
2636 }
2637
2638 /* FILE-based in_str */
2639
Denys Vlasenko4074d492016-09-30 01:49:53 +02002640#if ENABLE_FEATURE_EDITING
2641 /* This can be stdin, check line editing char[] buffer */
2642 if (i->p && *i->p != '\0') {
2643 ch = (unsigned char)*i->p++;
2644 goto out;
2645 }
2646#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002647 /* peek_buf[] is an int array, not char. Can contain EOF. */
2648 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002649 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002650 int ch2 = i->peek_buf[1];
2651 i->peek_buf[0] = ch2;
2652 if (ch2 == 0) /* very likely, avoid redundant write */
2653 goto out;
2654 i->peek_buf[1] = 0;
2655 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002656 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002657
Denys Vlasenko4074d492016-09-30 01:49:53 +02002658 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002659 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002660 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002661 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002662#if ENABLE_HUSH_LINENO_VAR
2663 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002664 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002665 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2666 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002667#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002668 return ch;
2669}
2670
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002671static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002672{
2673 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002674
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002675 if (!i->file) {
2676 /* string-based in_str */
2677 /* Doesn't report EOF on NUL. None of the callers care. */
2678 return (unsigned char)*i->p;
2679 }
2680
2681 /* FILE-based in_str */
2682
Denys Vlasenko4074d492016-09-30 01:49:53 +02002683#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002684 /* This can be stdin, check line editing char[] buffer */
2685 if (i->p && *i->p != '\0')
2686 return (unsigned char)*i->p;
2687#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002688 /* peek_buf[] is an int array, not char. Can contain EOF. */
2689 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002690 if (ch != 0)
2691 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002692
Denys Vlasenko4074d492016-09-30 01:49:53 +02002693 /* Need to get a new char */
2694 ch = fgetc_interactive(i);
2695 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2696
2697 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2698#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2699 if (i->p) {
2700 i->p -= 1;
2701 return ch;
2702 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002703#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002704 i->peek_buf[0] = ch;
2705 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002706 return ch;
2707}
2708
Denys Vlasenko4074d492016-09-30 01:49:53 +02002709/* Only ever called if i_peek() was called, and did not return EOF.
2710 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2711 * not end-of-line. Therefore we never need to read a new editing line here.
2712 */
2713static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002714{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002715 int ch;
2716
2717 /* There are two cases when i->p[] buffer exists.
2718 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002719 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002720 * In both cases, we know that i->p[0] exists and not NUL, and
2721 * the peek2 result is in i->p[1].
2722 */
2723 if (i->p)
2724 return (unsigned char)i->p[1];
2725
2726 /* Now we know it is a file-based in_str. */
2727
2728 /* peek_buf[] is an int array, not char. Can contain EOF. */
2729 /* Is there 2nd char? */
2730 ch = i->peek_buf[1];
2731 if (ch == 0) {
2732 /* We did not read it yet, get it now */
2733 do ch = fgetc(i->file); while (ch == '\0');
2734 i->peek_buf[1] = ch;
2735 }
2736
2737 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2738 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002739}
2740
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002741static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2742{
2743 for (;;) {
2744 int ch, ch2;
2745
2746 ch = i_getch(input);
2747 if (ch != '\\')
2748 return ch;
2749 ch2 = i_peek(input);
2750 if (ch2 != '\n')
2751 return ch;
2752 /* backslash+newline, skip it */
2753 i_getch(input);
2754 }
2755}
2756
2757/* Note: this function _eats_ \<newline> pairs, safe to use plain
2758 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2759 */
2760static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2761{
2762 for (;;) {
2763 int ch, ch2;
2764
2765 ch = i_peek(input);
2766 if (ch != '\\')
2767 return ch;
2768 ch2 = i_peek2(input);
2769 if (ch2 != '\n')
2770 return ch;
2771 /* backslash+newline, skip it */
2772 i_getch(input);
2773 i_getch(input);
2774 }
2775}
2776
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002777static void setup_file_in_str(struct in_str *i, FILE *f)
2778{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002779 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002780 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002781 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002782}
2783
2784static void setup_string_in_str(struct in_str *i, const char *s)
2785{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002786 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002787 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002788 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789}
2790
2791
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002792/*
2793 * o_string support
2794 */
2795#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002796
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002797static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002798{
2799 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002800 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002801 if (o->data)
2802 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002803}
2804
Denys Vlasenko18567402018-07-20 17:51:31 +02002805static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002806{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002807 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002808 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002809}
2810
Denys Vlasenko18567402018-07-20 17:51:31 +02002811static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002812{
2813 free(o->data);
2814}
2815
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002816static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002817{
2818 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002819 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002820 o->data = xrealloc(o->data, 1 + o->maxlen);
2821 }
2822}
2823
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002824static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002825{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002826 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002827 if (o->length < o->maxlen) {
2828 /* likely. avoid o_grow_by() call */
2829 add:
2830 o->data[o->length] = ch;
2831 o->length++;
2832 o->data[o->length] = '\0';
2833 return;
2834 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002835 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002836 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002837}
2838
Denys Vlasenko657086a2016-09-29 18:07:42 +02002839#if 0
2840/* Valid only if we know o_string is not empty */
2841static void o_delchr(o_string *o)
2842{
2843 o->length--;
2844 o->data[o->length] = '\0';
2845}
2846#endif
2847
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002848static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002849{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002850 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002851 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002852 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002853}
2854
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002855static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002856{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002857 o_addblock(o, str, strlen(str));
2858}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002859
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002860#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002861static void nommu_addchr(o_string *o, int ch)
2862{
2863 if (o)
2864 o_addchr(o, ch);
2865}
2866#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002867# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002868#endif
2869
2870static void o_addstr_with_NUL(o_string *o, const char *str)
2871{
2872 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002873}
2874
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002875/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002876 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002877 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2878 * Apparently, on unquoted $v bash still does globbing
2879 * ("v='*.txt'; echo $v" prints all .txt files),
2880 * but NOT brace expansion! Thus, there should be TWO independent
2881 * quoting mechanisms on $v expansion side: one protects
2882 * $v from brace expansion, and other additionally protects "$v" against globbing.
2883 * We have only second one.
2884 */
2885
Denys Vlasenko9e800222010-10-03 14:28:04 +02002886#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002887# define MAYBE_BRACES "{}"
2888#else
2889# define MAYBE_BRACES ""
2890#endif
2891
Eric Andersen25f27032001-04-26 23:22:31 +00002892/* My analysis of quoting semantics tells me that state information
2893 * is associated with a destination, not a source.
2894 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002895static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002896{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002897 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002898 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002899 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002900 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002901 o_grow_by(o, sz);
2902 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002903 o->data[o->length] = '\\';
2904 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002905 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002906 o->data[o->length] = ch;
2907 o->length++;
2908 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002909}
2910
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002911static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002912{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002913 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002914 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2915 && strchr("*?[\\" MAYBE_BRACES, ch)
2916 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002917 sz++;
2918 o->data[o->length] = '\\';
2919 o->length++;
2920 }
2921 o_grow_by(o, sz);
2922 o->data[o->length] = ch;
2923 o->length++;
2924 o->data[o->length] = '\0';
2925}
2926
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002927static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002928{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002929 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002930 char ch;
2931 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002932 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002933 if (ordinary_cnt > len) /* paranoia */
2934 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002935 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002936 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002937 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002938 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002939 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002940
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002941 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002942 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002943 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002944 sz++;
2945 o->data[o->length] = '\\';
2946 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002947 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002948 o_grow_by(o, sz);
2949 o->data[o->length] = ch;
2950 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002951 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002952 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002953}
2954
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002955static void o_addQblock(o_string *o, const char *str, int len)
2956{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002957 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002958 o_addblock(o, str, len);
2959 return;
2960 }
2961 o_addqblock(o, str, len);
2962}
2963
Denys Vlasenko38292b62010-09-05 14:49:40 +02002964static void o_addQstr(o_string *o, const char *str)
2965{
2966 o_addQblock(o, str, strlen(str));
2967}
2968
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002969/* A special kind of o_string for $VAR and `cmd` expansion.
2970 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002971 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002972 * list[i] contains an INDEX (int!) into this string data.
2973 * It means that if list[] needs to grow, data needs to be moved higher up
2974 * but list[i]'s need not be modified.
2975 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002976 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002977 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2978 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002979#if DEBUG_EXPAND || DEBUG_GLOB
2980static void debug_print_list(const char *prefix, o_string *o, int n)
2981{
2982 char **list = (char**)o->data;
2983 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2984 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002985
2986 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002987 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 +02002988 prefix, list, n, string_start, o->length, o->maxlen,
2989 !!(o->o_expflags & EXP_FLAG_GLOB),
2990 o->has_quoted_part,
2991 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002992 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002993 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002994 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2995 o->data + (int)(uintptr_t)list[i] + string_start,
2996 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002997 i++;
2998 }
2999 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003000 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003001 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003002 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003003 }
3004}
3005#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003006# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003007#endif
3008
3009/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3010 * in list[n] so that it points past last stored byte so far.
3011 * It returns n+1. */
3012static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003013{
3014 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003015 int string_start;
3016 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003017
3018 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003019 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3020 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003021 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003022 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003023 /* list[n] points to string_start, make space for 16 more pointers */
3024 o->maxlen += 0x10 * sizeof(list[0]);
3025 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003026 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003027 memmove(list + n + 0x10, list + n, string_len);
3028 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003029 } else {
3030 debug_printf_list("list[%d]=%d string_start=%d\n",
3031 n, string_len, string_start);
3032 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003033 } else {
3034 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003035 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3036 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003037 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3038 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003039 o->has_empty_slot = 0;
3040 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003041 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003042 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003043 return n + 1;
3044}
3045
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003046/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003047static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003048{
3049 char **list = (char**)o->data;
3050 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3051
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003052 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003053}
3054
Denys Vlasenko9e800222010-10-03 14:28:04 +02003055#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003056/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3057 * first, it processes even {a} (no commas), second,
3058 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003059 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003060 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003061
3062/* Helper */
3063static int glob_needed(const char *s)
3064{
3065 while (*s) {
3066 if (*s == '\\') {
3067 if (!s[1])
3068 return 0;
3069 s += 2;
3070 continue;
3071 }
3072 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3073 return 1;
3074 s++;
3075 }
3076 return 0;
3077}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003078/* Return pointer to next closing brace or to comma */
3079static const char *next_brace_sub(const char *cp)
3080{
3081 unsigned depth = 0;
3082 cp++;
3083 while (*cp != '\0') {
3084 if (*cp == '\\') {
3085 if (*++cp == '\0')
3086 break;
3087 cp++;
3088 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003089 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003090 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003091 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003092 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003093 depth++;
3094 }
3095
3096 return *cp != '\0' ? cp : NULL;
3097}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003098/* Recursive brace globber. Note: may garble pattern[]. */
3099static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003100{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003101 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003102 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003103 const char *next;
3104 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003105 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003106 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003107
3108 debug_printf_glob("glob_brace('%s')\n", pattern);
3109
3110 begin = pattern;
3111 while (1) {
3112 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003113 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003114 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003115 /* Find the first sub-pattern and at the same time
3116 * find the rest after the closing brace */
3117 next = next_brace_sub(begin);
3118 if (next == NULL) {
3119 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003120 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003121 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003122 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003123 /* "{abc}" with no commas - illegal
3124 * brace expr, disregard and skip it */
3125 begin = next + 1;
3126 continue;
3127 }
3128 break;
3129 }
3130 if (*begin == '\\' && begin[1] != '\0')
3131 begin++;
3132 begin++;
3133 }
3134 debug_printf_glob("begin:%s\n", begin);
3135 debug_printf_glob("next:%s\n", next);
3136
3137 /* Now find the end of the whole brace expression */
3138 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003139 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003140 rest = next_brace_sub(rest);
3141 if (rest == NULL) {
3142 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003143 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003144 }
3145 debug_printf_glob("rest:%s\n", rest);
3146 }
3147 rest_len = strlen(++rest) + 1;
3148
3149 /* We are sure the brace expression is well-formed */
3150
3151 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003152 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003153
3154 /* We have a brace expression. BEGIN points to the opening {,
3155 * NEXT points past the terminator of the first element, and REST
3156 * points past the final }. We will accumulate result names from
3157 * recursive runs for each brace alternative in the buffer using
3158 * GLOB_APPEND. */
3159
3160 p = begin + 1;
3161 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003162 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003163 memcpy(
3164 mempcpy(
3165 mempcpy(new_pattern_buf,
3166 /* We know the prefix for all sub-patterns */
3167 pattern, begin - pattern),
3168 p, next - p),
3169 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003170
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003171 /* Note: glob_brace() may garble new_pattern_buf[].
3172 * That's why we re-copy prefix every time (1st memcpy above).
3173 */
3174 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003175 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003176 /* We saw the last entry */
3177 break;
3178 }
3179 p = next + 1;
3180 next = next_brace_sub(next);
3181 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003182 free(new_pattern_buf);
3183 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003184
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003185 simple_glob:
3186 {
3187 int gr;
3188 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003189
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003190 memset(&globdata, 0, sizeof(globdata));
3191 gr = glob(pattern, 0, NULL, &globdata);
3192 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3193 if (gr != 0) {
3194 if (gr == GLOB_NOMATCH) {
3195 globfree(&globdata);
3196 /* NB: garbles parameter */
3197 unbackslash(pattern);
3198 o_addstr_with_NUL(o, pattern);
3199 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3200 return o_save_ptr_helper(o, n);
3201 }
3202 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003203 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003204 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3205 * but we didn't specify it. Paranoia again. */
3206 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3207 }
3208 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3209 char **argv = globdata.gl_pathv;
3210 while (1) {
3211 o_addstr_with_NUL(o, *argv);
3212 n = o_save_ptr_helper(o, n);
3213 argv++;
3214 if (!*argv)
3215 break;
3216 }
3217 }
3218 globfree(&globdata);
3219 }
3220 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003221}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003222/* Performs globbing on last list[],
3223 * saving each result as a new list[].
3224 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003225static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003226{
3227 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003228
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003229 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003230 if (!o->data)
3231 return o_save_ptr_helper(o, n);
3232 pattern = o->data + o_get_last_ptr(o, n);
3233 debug_printf_glob("glob pattern '%s'\n", pattern);
3234 if (!glob_needed(pattern)) {
3235 /* unbackslash last string in o in place, fix length */
3236 o->length = unbackslash(pattern) - o->data;
3237 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3238 return o_save_ptr_helper(o, n);
3239 }
3240
3241 copy = xstrdup(pattern);
3242 /* "forget" pattern in o */
3243 o->length = pattern - o->data;
3244 n = glob_brace(copy, o, n);
3245 free(copy);
3246 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003247 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003248 return n;
3249}
3250
Denys Vlasenko238081f2010-10-03 14:26:26 +02003251#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003252
3253/* Helper */
3254static int glob_needed(const char *s)
3255{
3256 while (*s) {
3257 if (*s == '\\') {
3258 if (!s[1])
3259 return 0;
3260 s += 2;
3261 continue;
3262 }
3263 if (*s == '*' || *s == '[' || *s == '?')
3264 return 1;
3265 s++;
3266 }
3267 return 0;
3268}
3269/* Performs globbing on last list[],
3270 * saving each result as a new list[].
3271 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003272static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003273{
3274 glob_t globdata;
3275 int gr;
3276 char *pattern;
3277
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003278 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003279 if (!o->data)
3280 return o_save_ptr_helper(o, n);
3281 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003282 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003283 if (!glob_needed(pattern)) {
3284 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003285 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003286 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003287 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003288 return o_save_ptr_helper(o, n);
3289 }
3290
3291 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003292 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3293 * If we glob "*.\*" and don't find anything, we need
3294 * to fall back to using literal "*.*", but GLOB_NOCHECK
3295 * will return "*.\*"!
3296 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003297 gr = glob(pattern, 0, NULL, &globdata);
3298 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003299 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003300 if (gr == GLOB_NOMATCH) {
3301 globfree(&globdata);
3302 goto literal;
3303 }
3304 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003305 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003306 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3307 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003308 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003309 }
3310 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3311 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003312 /* "forget" pattern in o */
3313 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003314 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003315 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003316 n = o_save_ptr_helper(o, n);
3317 argv++;
3318 if (!*argv)
3319 break;
3320 }
3321 }
3322 globfree(&globdata);
3323 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003324 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003325 return n;
3326}
3327
Denys Vlasenko238081f2010-10-03 14:26:26 +02003328#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003329
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003330/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003331 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003332static int o_save_ptr(o_string *o, int n)
3333{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003334 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003335 /* If o->has_empty_slot, list[n] was already globbed
3336 * (if it was requested back then when it was filled)
3337 * so don't do that again! */
3338 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003339 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003340 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003341 return o_save_ptr_helper(o, n);
3342}
3343
3344/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003345static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003346{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003347 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003348 int string_start;
3349
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003350 if (DEBUG_EXPAND)
3351 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003352 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003353 list = (char**)o->data;
3354 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3355 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003356 while (n) {
3357 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003358 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003359 }
3360 return list;
3361}
3362
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003363static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003364
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003365/* Returns pi->next - next pipe in the list */
3366static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003367{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003368 struct pipe *next;
3369 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003370
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003371 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003372 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003373 struct command *command;
3374 struct redir_struct *r, *rnext;
3375
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003376 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003377 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003378 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003379 if (DEBUG_CLEAN) {
3380 int a;
3381 char **p;
3382 for (a = 0, p = command->argv; *p; a++, p++) {
3383 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3384 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003385 }
3386 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003387 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003388 }
3389 /* not "else if": on syntax error, we may have both! */
3390 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003391 debug_printf_clean(" begin group (cmd_type:%d)\n",
3392 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003393 free_pipe_list(command->group);
3394 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003395 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003396 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003397 /* else is crucial here.
3398 * If group != NULL, child_func is meaningless */
3399#if ENABLE_HUSH_FUNCTIONS
3400 else if (command->child_func) {
3401 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3402 command->child_func->parent_cmd = NULL;
3403 }
3404#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003405#if !BB_MMU
3406 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003407 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003408#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003409 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003410 debug_printf_clean(" redirect %d%s",
3411 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003412 /* guard against the case >$FOO, where foo is unset or blank */
3413 if (r->rd_filename) {
3414 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3415 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003416 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003417 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003418 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003419 rnext = r->next;
3420 free(r);
3421 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003422 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003423 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003424 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003425 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003426#if ENABLE_HUSH_JOB
3427 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003428 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003429#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003430
3431 next = pi->next;
3432 free(pi);
3433 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003434}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003435
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003436static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003437{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003438 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003439#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003440 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003441#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003442 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003443 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003444 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003445}
3446
3447
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003448/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003449
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003450#ifndef debug_print_tree
3451static void debug_print_tree(struct pipe *pi, int lvl)
3452{
3453 static const char *const PIPE[] = {
3454 [PIPE_SEQ] = "SEQ",
3455 [PIPE_AND] = "AND",
3456 [PIPE_OR ] = "OR" ,
3457 [PIPE_BG ] = "BG" ,
3458 };
3459 static const char *RES[] = {
3460 [RES_NONE ] = "NONE" ,
3461# if ENABLE_HUSH_IF
3462 [RES_IF ] = "IF" ,
3463 [RES_THEN ] = "THEN" ,
3464 [RES_ELIF ] = "ELIF" ,
3465 [RES_ELSE ] = "ELSE" ,
3466 [RES_FI ] = "FI" ,
3467# endif
3468# if ENABLE_HUSH_LOOPS
3469 [RES_FOR ] = "FOR" ,
3470 [RES_WHILE] = "WHILE",
3471 [RES_UNTIL] = "UNTIL",
3472 [RES_DO ] = "DO" ,
3473 [RES_DONE ] = "DONE" ,
3474# endif
3475# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3476 [RES_IN ] = "IN" ,
3477# endif
3478# if ENABLE_HUSH_CASE
3479 [RES_CASE ] = "CASE" ,
3480 [RES_CASE_IN ] = "CASE_IN" ,
3481 [RES_MATCH] = "MATCH",
3482 [RES_CASE_BODY] = "CASE_BODY",
3483 [RES_ESAC ] = "ESAC" ,
3484# endif
3485 [RES_XXXX ] = "XXXX" ,
3486 [RES_SNTX ] = "SNTX" ,
3487 };
3488 static const char *const CMDTYPE[] = {
3489 "{}",
3490 "()",
3491 "[noglob]",
3492# if ENABLE_HUSH_FUNCTIONS
3493 "func()",
3494# endif
3495 };
3496
3497 int pin, prn;
3498
3499 pin = 0;
3500 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003501 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3502 lvl*2, "",
3503 pin,
3504 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3505 RES[pi->res_word],
3506 pi->followup, PIPE[pi->followup]
3507 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003508 prn = 0;
3509 while (prn < pi->num_cmds) {
3510 struct command *command = &pi->cmds[prn];
3511 char **argv = command->argv;
3512
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003513 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003514 lvl*2, "", prn,
3515 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003516#if ENABLE_HUSH_LINENO_VAR
3517 fdprintf(2, " LINENO:%u", command->lineno);
3518#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003519 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003520 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003521 CMDTYPE[command->cmd_type],
3522 argv
3523# if !BB_MMU
3524 , " group_as_string:", command->group_as_string
3525# else
3526 , "", ""
3527# endif
3528 );
3529 debug_print_tree(command->group, lvl+1);
3530 prn++;
3531 continue;
3532 }
3533 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003534 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003535 argv++;
3536 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003537 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003538 prn++;
3539 }
3540 pi = pi->next;
3541 pin++;
3542 }
3543}
3544#endif /* debug_print_tree */
3545
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003546static struct pipe *new_pipe(void)
3547{
Eric Andersen25f27032001-04-26 23:22:31 +00003548 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003549 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003550 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003551 return pi;
3552}
3553
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003554/* Command (member of a pipe) is complete, or we start a new pipe
3555 * if ctx->command is NULL.
3556 * No errors possible here.
3557 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003558static int done_command(struct parse_context *ctx)
3559{
3560 /* The command is really already in the pipe structure, so
3561 * advance the pipe counter and make a new, null command. */
3562 struct pipe *pi = ctx->pipe;
3563 struct command *command = ctx->command;
3564
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003565#if 0 /* Instead we emit error message at run time */
3566 if (ctx->pending_redirect) {
3567 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003568 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003569 ctx->pending_redirect = NULL;
3570 }
3571#endif
3572
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003573 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003574 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003575 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003576 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003577 }
3578 pi->num_cmds++;
3579 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003580 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003581 } else {
3582 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3583 }
3584
3585 /* Only real trickiness here is that the uncommitted
3586 * command structure is not counted in pi->num_cmds. */
3587 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003588 ctx->command = command = &pi->cmds[pi->num_cmds];
3589 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003590 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003591#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003592 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003593 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003594#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003595 return pi->num_cmds; /* used only for 0/nonzero check */
3596}
3597
3598static void done_pipe(struct parse_context *ctx, pipe_style type)
3599{
3600 int not_null;
3601
3602 debug_printf_parse("done_pipe entered, followup %d\n", type);
3603 /* Close previous command */
3604 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003605#if HAS_KEYWORDS
3606 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3607 ctx->ctx_inverted = 0;
3608 ctx->pipe->res_word = ctx->ctx_res_w;
3609#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003610 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3611 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003612 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3613 * in a backgrounded subshell.
3614 */
3615 struct pipe *pi;
3616 struct command *command;
3617
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003618 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003619 pi = ctx->list_head;
3620 while (pi != ctx->pipe) {
3621 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3622 goto no_conv;
3623 pi = pi->next;
3624 }
3625
3626 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3627 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3628 pi = xzalloc(sizeof(*pi));
3629 pi->followup = PIPE_BG;
3630 pi->num_cmds = 1;
3631 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3632 command = &pi->cmds[0];
3633 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3634 command->cmd_type = CMD_NORMAL;
3635 command->group = ctx->list_head;
3636#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003637 command->group_as_string = xstrndup(
3638 ctx->as_string.data,
3639 ctx->as_string.length - 1 /* do not copy last char, "&" */
3640 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003641#endif
3642 /* Replace all pipes in ctx with one newly created */
3643 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003644 } else {
3645 no_conv:
3646 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003647 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003648
3649 /* Without this check, even just <enter> on command line generates
3650 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003651 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003652 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003653#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003654 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003655#endif
3656#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003657 || ctx->ctx_res_w == RES_DONE
3658 || ctx->ctx_res_w == RES_FOR
3659 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003660#endif
3661#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003662 || ctx->ctx_res_w == RES_ESAC
3663#endif
3664 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003665 struct pipe *new_p;
3666 debug_printf_parse("done_pipe: adding new pipe: "
3667 "not_null:%d ctx->ctx_res_w:%d\n",
3668 not_null, ctx->ctx_res_w);
3669 new_p = new_pipe();
3670 ctx->pipe->next = new_p;
3671 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003672 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003673 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003674 * This is used to control execution.
3675 * RES_FOR and RES_IN are NOT sticky (needed to support
3676 * cases where variable or value happens to match a keyword):
3677 */
3678#if ENABLE_HUSH_LOOPS
3679 if (ctx->ctx_res_w == RES_FOR
3680 || ctx->ctx_res_w == RES_IN)
3681 ctx->ctx_res_w = RES_NONE;
3682#endif
3683#if ENABLE_HUSH_CASE
3684 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003685 ctx->ctx_res_w = RES_CASE_BODY;
3686 if (ctx->ctx_res_w == RES_CASE)
3687 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003688#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003689 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003690 /* Create the memory for command, roughly:
3691 * ctx->pipe->cmds = new struct command;
3692 * ctx->command = &ctx->pipe->cmds[0];
3693 */
3694 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003695 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003696 }
3697 debug_printf_parse("done_pipe return\n");
3698}
3699
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003700static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003701{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003702 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003703 if (MAYBE_ASSIGNMENT != 0)
3704 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003705 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003706 /* Create the memory for command, roughly:
3707 * ctx->pipe->cmds = new struct command;
3708 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003709 */
3710 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003711}
3712
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003713/* If a reserved word is found and processed, parse context is modified
3714 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003715 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003716#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003717struct reserved_combo {
3718 char literal[6];
3719 unsigned char res;
3720 unsigned char assignment_flag;
3721 int flag;
3722};
3723enum {
3724 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003725# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003726 FLAG_IF = (1 << RES_IF ),
3727 FLAG_THEN = (1 << RES_THEN ),
3728 FLAG_ELIF = (1 << RES_ELIF ),
3729 FLAG_ELSE = (1 << RES_ELSE ),
3730 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003731# endif
3732# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003733 FLAG_FOR = (1 << RES_FOR ),
3734 FLAG_WHILE = (1 << RES_WHILE),
3735 FLAG_UNTIL = (1 << RES_UNTIL),
3736 FLAG_DO = (1 << RES_DO ),
3737 FLAG_DONE = (1 << RES_DONE ),
3738 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003739# endif
3740# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003741 FLAG_MATCH = (1 << RES_MATCH),
3742 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003743# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003744 FLAG_START = (1 << RES_XXXX ),
3745};
3746
3747static const struct reserved_combo* match_reserved_word(o_string *word)
3748{
Eric Andersen25f27032001-04-26 23:22:31 +00003749 /* Mostly a list of accepted follow-up reserved words.
3750 * FLAG_END means we are done with the sequence, and are ready
3751 * to turn the compound list into a command.
3752 * FLAG_START means the word must start a new compound list.
3753 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003754 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003755# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003756 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3757 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3758 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3759 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3760 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3761 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003762# endif
3763# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003764 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3765 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3766 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3767 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3768 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3769 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003770# endif
3771# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003772 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3773 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003774# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003775 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003776 const struct reserved_combo *r;
3777
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003778 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003779 if (strcmp(word->data, r->literal) == 0)
3780 return r;
3781 }
3782 return NULL;
3783}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003784/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003785 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003786static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003787{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003788# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003789 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003790 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003791 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003792# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003793 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003794
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003795 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003796 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003797 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003798 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003799 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003800
3801 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003802# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003803 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3804 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003805 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003806 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003807# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003808 if (r->flag == 0) { /* '!' */
3809 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003810 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003811 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003812 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003813 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003814 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003815 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003816 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003817 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003818
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003819 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003820 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003821 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003822 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003823 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003824 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003825 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003826 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003827 } else {
3828 /* "{...} fi" is ok. "{...} if" is not
3829 * Example:
3830 * if { echo foo; } then { echo bar; } fi */
3831 if (ctx->command->group)
3832 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003833 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003834
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003835 ctx->ctx_res_w = r->res;
3836 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003837 ctx->is_assignment = r->assignment_flag;
3838 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003839
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003840 if (ctx->old_flag & FLAG_END) {
3841 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003842
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003843 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003844 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003845 old = ctx->stack;
3846 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003847 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003848# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003849 /* At this point, the compound command's string is in
3850 * ctx->as_string... except for the leading keyword!
3851 * Consider this example: "echo a | if true; then echo a; fi"
3852 * ctx->as_string will contain "true; then echo a; fi",
3853 * with "if " remaining in old->as_string!
3854 */
3855 {
3856 char *str;
3857 int len = old->as_string.length;
3858 /* Concatenate halves */
3859 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02003860 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003861 /* Find where leading keyword starts in first half */
3862 str = old->as_string.data + len;
3863 if (str > old->as_string.data)
3864 str--; /* skip whitespace after keyword */
3865 while (str > old->as_string.data && isalpha(str[-1]))
3866 str--;
3867 /* Ugh, we're done with this horrid hack */
3868 old->command->group_as_string = xstrdup(str);
3869 debug_printf_parse("pop, remembering as:'%s'\n",
3870 old->command->group_as_string);
3871 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003872# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003873 *ctx = *old; /* physical copy */
3874 free(old);
3875 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003876 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003877}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003878#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003879
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003880/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003881 * Normal return is 0. Syntax errors return 1.
3882 * Note: on return, word is reset, but not o_free'd!
3883 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003884static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003885{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003886 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003887
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003888 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3889 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003890 debug_printf_parse("done_word return 0: true null, ignored\n");
3891 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003892 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003893
Eric Andersen25f27032001-04-26 23:22:31 +00003894 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003895 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3896 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003897 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003898 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003899 * If the redirection operator is "<<" or "<<-", the word
3900 * that follows the redirection operator shall be
3901 * subjected to quote removal; it is unspecified whether
3902 * any of the other expansions occur. For the other
3903 * redirection operators, the word that follows the
3904 * redirection operator shall be subjected to tilde
3905 * expansion, parameter expansion, command substitution,
3906 * arithmetic expansion, and quote removal.
3907 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003908 * on the word by a non-interactive shell; an interactive
3909 * shell may perform it, but shall do so only when
3910 * the expansion would result in one word."
3911 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003912//bash does not do parameter/command substitution or arithmetic expansion
3913//for _heredoc_ redirection word: these constructs look for exact eof marker
3914// as written:
3915// <<EOF$t
3916// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003917// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3918
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003919 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003920 /* Cater for >\file case:
3921 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3922 * Same with heredocs:
3923 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3924 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003925 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3926 unbackslash(ctx->pending_redirect->rd_filename);
3927 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003928 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003929 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3930 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003931 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003932 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003933 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003934 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003935#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003936# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003937 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003938 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003939 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003940 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003941 /* ctx->ctx_res_w = RES_MATCH; */
3942 ctx->ctx_dsemicolon = 0;
3943 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003944# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003945 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003946# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003947 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3948 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003949# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003950# if ENABLE_HUSH_CASE
3951 && ctx->ctx_res_w != RES_CASE
3952# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003953 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003954 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003955 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003956 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003957 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003958# if ENABLE_HUSH_LINENO_VAR
3959/* Case:
3960 * "while ...; do
3961 * cmd ..."
3962 * If we don't close the pipe _now_, immediately after "do", lineno logic
3963 * sees "cmd" as starting at "do" - i.e., at the previous line.
3964 */
3965 if (0
3966 IF_HUSH_IF(|| reserved->res == RES_THEN)
3967 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3968 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3969 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3970 ) {
3971 done_pipe(ctx, PIPE_SEQ);
3972 }
3973# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003974 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003975 debug_printf_parse("done_word return %d\n",
3976 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003977 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003978 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003979# if defined(CMD_SINGLEWORD_NOGLOB)
3980 if (0
3981# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003982 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02003983# endif
3984 /* In bash, local/export/readonly are special, args
3985 * are assignments and therefore expansion of them
3986 * should be "one-word" expansion:
3987 * $ export i=`echo 'a b'` # one arg: "i=a b"
3988 * compare with:
3989 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3990 * ls: cannot access i=a: No such file or directory
3991 * ls: cannot access b: No such file or directory
3992 * Note: bash 3.2.33(1) does this only if export word
3993 * itself is not quoted:
3994 * $ export i=`echo 'aaa bbb'`; echo "$i"
3995 * aaa bbb
3996 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3997 * aaa
3998 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003999 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4000 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4001 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004002 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004003 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4004 }
4005 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004006# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004007 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004008#endif /* HAS_KEYWORDS */
4009
Denis Vlasenkobb929512009-04-16 10:59:40 +00004010 if (command->group) {
4011 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004012 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004013 debug_printf_parse("done_word return 1: syntax error, "
4014 "groups and arglists don't mix\n");
4015 return 1;
4016 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004017
4018 /* If this word wasn't an assignment, next ones definitely
4019 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004020 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4021 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004022 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004023 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004024 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004025 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004026 command->assignment_cnt++;
4027 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4028 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004029 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4030 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004031 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004032 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4033 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004034 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004035 }
Eric Andersen25f27032001-04-26 23:22:31 +00004036
Denis Vlasenko06810332007-05-21 23:30:54 +00004037#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004038 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004039 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004040 || !is_well_formed_var_name(command->argv[0], '\0')
4041 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004042 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004043 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004044 return 1;
4045 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004046 /* Force FOR to have just one word (variable name) */
4047 /* NB: basically, this makes hush see "for v in ..."
4048 * syntax as if it is "for v; in ...". FOR and IN become
4049 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004050 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004051 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004052#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004053#if ENABLE_HUSH_CASE
4054 /* Force CASE to have just one word */
4055 if (ctx->ctx_res_w == RES_CASE) {
4056 done_pipe(ctx, PIPE_SEQ);
4057 }
4058#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004059
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004060 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004061
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004062 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004063 return 0;
4064}
4065
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004066
4067/* Peek ahead in the input to find out if we have a "&n" construct,
4068 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004069 * Return:
4070 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4071 * REDIRFD_SYNTAX_ERR if syntax error,
4072 * REDIRFD_TO_FILE if no & was seen,
4073 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004074 */
4075#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004076#define parse_redir_right_fd(as_string, input) \
4077 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004078#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004079static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004080{
4081 int ch, d, ok;
4082
4083 ch = i_peek(input);
4084 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004085 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004086
4087 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004088 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004089 ch = i_peek(input);
4090 if (ch == '-') {
4091 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004092 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004093 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004094 }
4095 d = 0;
4096 ok = 0;
4097 while (ch != EOF && isdigit(ch)) {
4098 d = d*10 + (ch-'0');
4099 ok = 1;
4100 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004101 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004102 ch = i_peek(input);
4103 }
4104 if (ok) return d;
4105
4106//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4107
4108 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004109 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004110}
4111
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004112/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004113 */
4114static int parse_redirect(struct parse_context *ctx,
4115 int fd,
4116 redir_type style,
4117 struct in_str *input)
4118{
4119 struct command *command = ctx->command;
4120 struct redir_struct *redir;
4121 struct redir_struct **redirp;
4122 int dup_num;
4123
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004124 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004125 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004126 /* Check for a '>&1' type redirect */
4127 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4128 if (dup_num == REDIRFD_SYNTAX_ERR)
4129 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004130 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004131 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004132 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004133 if (dup_num) { /* <<-... */
4134 ch = i_getch(input);
4135 nommu_addchr(&ctx->as_string, ch);
4136 ch = i_peek(input);
4137 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004138 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004139
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004140 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004141 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004142 if (ch == '|') {
4143 /* >|FILE redirect ("clobbering" >).
4144 * Since we do not support "set -o noclobber" yet,
4145 * >| and > are the same for now. Just eat |.
4146 */
4147 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004148 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004149 }
4150 }
4151
4152 /* Create a new redir_struct and append it to the linked list */
4153 redirp = &command->redirects;
4154 while ((redir = *redirp) != NULL) {
4155 redirp = &(redir->next);
4156 }
4157 *redirp = redir = xzalloc(sizeof(*redir));
4158 /* redir->next = NULL; */
4159 /* redir->rd_filename = NULL; */
4160 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004161 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004162
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004163 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4164 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004165
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004166 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004167 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004168 /* Erik had a check here that the file descriptor in question
4169 * is legit; I postpone that to "run time"
4170 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004171 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4172 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004173 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004174#if 0 /* Instead we emit error message at run time */
4175 if (ctx->pending_redirect) {
4176 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004177 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004178 }
4179#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004180 /* Set ctx->pending_redirect, so we know what to do at the
4181 * end of the next parsed word. */
4182 ctx->pending_redirect = redir;
4183 }
4184 return 0;
4185}
4186
Eric Andersen25f27032001-04-26 23:22:31 +00004187/* If a redirect is immediately preceded by a number, that number is
4188 * supposed to tell which file descriptor to redirect. This routine
4189 * looks for such preceding numbers. In an ideal world this routine
4190 * needs to handle all the following classes of redirects...
4191 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4192 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4193 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4194 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004195 *
4196 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4197 * "2.7 Redirection
4198 * ... If n is quoted, the number shall not be recognized as part of
4199 * the redirection expression. For example:
4200 * echo \2>a
4201 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004202 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004203 *
4204 * A -1 return means no valid number was found,
4205 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004206 */
4207static int redirect_opt_num(o_string *o)
4208{
4209 int num;
4210
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004211 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004212 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004213 num = bb_strtou(o->data, NULL, 10);
4214 if (errno || num < 0)
4215 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004216 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004217 return num;
4218}
4219
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004220#if BB_MMU
4221#define fetch_till_str(as_string, input, word, skip_tabs) \
4222 fetch_till_str(input, word, skip_tabs)
4223#endif
4224static char *fetch_till_str(o_string *as_string,
4225 struct in_str *input,
4226 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004227 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004228{
4229 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004230 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004231 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004232 int ch;
4233
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004234 /* Starting with "" is necessary for this case:
4235 * cat <<EOF
4236 *
4237 * xxx
4238 * EOF
4239 */
4240 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4241
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004242 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004243
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004244 while (1) {
4245 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004246 if (ch != EOF)
4247 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004248 if (ch == '\n' || ch == EOF) {
4249 check_heredoc_end:
4250 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4251 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4252 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004253 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004254 return heredoc.data;
4255 }
4256 if (ch == '\n') {
4257 /* This is a new line.
4258 * Remember position and backslash-escaping status.
4259 */
4260 o_addchr(&heredoc, ch);
4261 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004262 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004263 past_EOL = heredoc.length;
4264 /* Get 1st char of next line, possibly skipping leading tabs */
4265 do {
4266 ch = i_getch(input);
4267 if (ch != EOF)
4268 nommu_addchr(as_string, ch);
4269 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4270 /* If this immediately ended the line,
4271 * go back to end-of-line checks.
4272 */
4273 if (ch == '\n')
4274 goto check_heredoc_end;
4275 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004276 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004277 }
4278 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004279 o_free(&heredoc);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004280 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004281 }
4282 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004283 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004284 if (prev == '\\' && ch == '\\')
4285 /* Correctly handle foo\\<eol> (not a line cont.) */
4286 prev = 0; /* not \ */
4287 else
4288 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004289 }
4290}
4291
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004292/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4293 * and load them all. There should be exactly heredoc_cnt of them.
4294 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004295static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4296{
4297 struct pipe *pi = ctx->list_head;
4298
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004299 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004300 int i;
4301 struct command *cmd = pi->cmds;
4302
Denys Vlasenko3675c372018-07-23 16:31:21 +02004303 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004304 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004305 cmd->argv ? cmd->argv[0] : "NONE"
4306 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004307 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004308 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004309
Denys Vlasenko3675c372018-07-23 16:31:21 +02004310 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004311 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004312 while (redir) {
4313 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004314 char *p;
4315
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004316 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004317 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004318 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004319 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004320 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004321 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004322 return 1;
4323 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004324 free(redir->rd_filename);
4325 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004326 heredoc_cnt--;
4327 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004328 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004329 }
4330 cmd++;
4331 }
4332 pi = pi->next;
4333 }
4334 /* Should be 0. If it isn't, it's a parse error */
Denys Vlasenko3675c372018-07-23 16:31:21 +02004335 if (HUSH_DEBUG && heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004336 bb_error_msg_and_die("heredoc BUG 2");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004337 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004338}
4339
4340
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004341static int run_list(struct pipe *pi);
4342#if BB_MMU
4343#define parse_stream(pstring, input, end_trigger) \
4344 parse_stream(input, end_trigger)
4345#endif
4346static struct pipe *parse_stream(char **pstring,
4347 struct in_str *input,
4348 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004349
Eric Andersen25f27032001-04-26 23:22:31 +00004350
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004351static int parse_group(struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004352 struct in_str *input, int ch)
4353{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004354 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004355 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004356 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004357#if BB_MMU
4358# define as_string NULL
4359#else
4360 char *as_string = NULL;
4361#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004362 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004363 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004364 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004365
4366 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004367#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004368 if (ch == '(' && !ctx->word.has_quoted_part) {
4369 if (ctx->word.length)
4370 if (done_word(ctx))
Denis Vlasenkobb929512009-04-16 10:59:40 +00004371 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004372 if (!command->argv)
4373 goto skip; /* (... */
4374 if (command->argv[1]) { /* word word ... (... */
4375 syntax_error_unexpected_ch('(');
4376 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004377 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004378 /* it is "word(..." or "word (..." */
4379 do
4380 ch = i_getch(input);
4381 while (ch == ' ' || ch == '\t');
4382 if (ch != ')') {
4383 syntax_error_unexpected_ch(ch);
4384 return 1;
4385 }
4386 nommu_addchr(&ctx->as_string, ch);
4387 do
4388 ch = i_getch(input);
4389 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004390 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004391 syntax_error_unexpected_ch(ch);
4392 return 1;
4393 }
4394 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004395 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004396 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004397 }
4398#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004399
4400#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004401 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004402 || ctx->word.length /* word{... */
4403 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004404 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004405 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004406 debug_printf_parse("parse_group return 1: "
4407 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004408 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004409 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004410#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004411
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004412 IF_HUSH_FUNCTIONS(skip:)
4413
Denis Vlasenko240c2552009-04-03 03:45:05 +00004414 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004415 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004416 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004417 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4418 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004419 } else {
4420 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004421 ch = i_peek(input);
4422 if (ch != ' ' && ch != '\t' && ch != '\n'
4423 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4424 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004425 syntax_error_unexpected_ch(ch);
4426 return 1;
4427 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004428 if (ch != '(') {
4429 ch = i_getch(input);
4430 nommu_addchr(&ctx->as_string, ch);
4431 }
Eric Andersen25f27032001-04-26 23:22:31 +00004432 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004433
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004434 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004435#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004436 if (as_string)
4437 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004438#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004439
4440 /* empty ()/{} or parse error? */
4441 if (!pipe_list || pipe_list == ERR_PTR) {
4442 /* parse_stream already emitted error msg */
4443 if (!BB_MMU)
4444 free(as_string);
4445 debug_printf_parse("parse_group return 1: "
4446 "parse_stream returned %p\n", pipe_list);
4447 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004448 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004449#if !BB_MMU
4450 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4451 command->group_as_string = as_string;
4452 debug_printf_parse("end of group, remembering as:'%s'\n",
4453 command->group_as_string);
4454#endif
4455
4456#if ENABLE_HUSH_FUNCTIONS
4457 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4458 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4459 struct command *cmd2;
4460
4461 cmd2 = xzalloc(sizeof(*cmd2));
4462 cmd2->cmd_type = CMD_SUBSHELL;
4463 cmd2->group = pipe_list;
4464# if !BB_MMU
4465//UNTESTED!
4466 cmd2->group_as_string = command->group_as_string;
4467 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4468# endif
4469
4470 pipe_list = new_pipe();
4471 pipe_list->cmds = cmd2;
4472 pipe_list->num_cmds = 1;
4473 }
4474#endif
4475
4476 command->group = pipe_list;
4477
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004478 debug_printf_parse("parse_group return 0\n");
4479 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004480 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004481#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004482}
4483
Denys Vlasenko0b883582016-12-23 16:49:07 +01004484#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004485/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004486/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004487static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004488{
4489 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004490 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004491 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004492 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004493 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004494 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004495 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004496 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004497 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004498 }
4499}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004500static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4501{
4502 while (1) {
4503 int ch = i_getch(input);
4504 if (ch == EOF) {
4505 syntax_error_unterm_ch('\'');
4506 return 0;
4507 }
4508 if (ch == '\'')
4509 return 1;
4510 o_addqchr(dest, ch);
4511 }
4512}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004513/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004514static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004515static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004516{
4517 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004518 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004519 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004520 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004521 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004522 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004523 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004524 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004525 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004526 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004527 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004528 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004529 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004530 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004531 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4532 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004533 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004534 continue;
4535 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004536 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004537 }
4538}
4539/* Process `cmd` - copy contents until "`" is seen. Complicated by
4540 * \` quoting.
4541 * "Within the backquoted style of command substitution, backslash
4542 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4543 * The search for the matching backquote shall be satisfied by the first
4544 * backquote found without a preceding backslash; during this search,
4545 * if a non-escaped backquote is encountered within a shell comment,
4546 * a here-document, an embedded command substitution of the $(command)
4547 * form, or a quoted string, undefined results occur. A single-quoted
4548 * or double-quoted string that begins, but does not end, within the
4549 * "`...`" sequence produces undefined results."
4550 * Example Output
4551 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4552 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004553static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004554{
4555 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004556 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004557 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004558 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004559 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004560 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4561 ch = i_getch(input);
4562 if (ch != '`'
4563 && ch != '$'
4564 && ch != '\\'
4565 && (!in_dquote || ch != '"')
4566 ) {
4567 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004568 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004569 }
4570 if (ch == EOF) {
4571 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004572 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004573 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004574 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004575 }
4576}
4577/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4578 * quoting and nested ()s.
4579 * "With the $(command) style of command substitution, all characters
4580 * following the open parenthesis to the matching closing parenthesis
4581 * constitute the command. Any valid shell script can be used for command,
4582 * except a script consisting solely of redirections which produces
4583 * unspecified results."
4584 * Example Output
4585 * echo $(echo '(TEST)' BEST) (TEST) BEST
4586 * echo $(echo 'TEST)' BEST) TEST) BEST
4587 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004588 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004589 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004590 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004591 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4592 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004593 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004594#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004595static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004596{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004597 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004598 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004599# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004600 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004601# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004602 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4603
Denys Vlasenko817a2022018-06-26 15:35:17 +02004604#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004605 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004606#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004607 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4608
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004609 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004610 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004611 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004612 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004613 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004614 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004615 if (ch == end_ch
4616# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004617 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004618# endif
4619 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004620 if (!dbl)
4621 break;
4622 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004623 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004624 i_getch(input); /* eat second ')' */
4625 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004626 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004627 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004628 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004629 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004630 if (ch == '(' || ch == '{') {
4631 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004632 if (!add_till_closing_bracket(dest, input, ch))
4633 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004634 o_addchr(dest, ch);
4635 continue;
4636 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004637 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004638 if (!add_till_single_quote(dest, input))
4639 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004640 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004641 continue;
4642 }
4643 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004644 if (!add_till_double_quote(dest, input))
4645 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004646 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004647 continue;
4648 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004649 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004650 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4651 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004652 o_addchr(dest, ch);
4653 continue;
4654 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004655 if (ch == '\\') {
4656 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004657 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004658 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004659 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004660 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004661 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004662#if 0
4663 if (ch == '\n') {
4664 /* "backslash+newline", ignore both */
4665 o_delchr(dest); /* undo insertion of '\' */
4666 continue;
4667 }
4668#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004669 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004670 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004671 continue;
4672 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004673 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004674 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004675 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004676}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004677#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004678
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004679/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004680#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004681#define parse_dollar(as_string, dest, input, quote_mask) \
4682 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004683#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004684#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004685static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004686 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004687 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004688{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004689 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004690
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004691 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004692 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004693 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004694 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004695 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004696 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004697 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004698 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004699 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004700 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004701 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004702 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004703 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004704 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004705 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004706 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004707 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004708 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004709 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004710 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004711 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004712 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004713 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004714 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004715 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004716 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004717 o_addchr(dest, ch | quote_mask);
4718 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004719 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004720 case '$': /* pid */
4721 case '!': /* last bg pid */
4722 case '?': /* last exit code */
4723 case '#': /* number of args */
4724 case '*': /* args */
4725 case '@': /* args */
4726 goto make_one_char_var;
4727 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004728 char len_single_ch;
4729
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004730 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4731
Denys Vlasenko74369502010-05-21 19:52:01 +02004732 ch = i_getch(input); /* eat '{' */
4733 nommu_addchr(as_string, ch);
4734
Denys Vlasenko46e64982016-09-29 19:50:55 +02004735 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004736 /* It should be ${?}, or ${#var},
4737 * or even ${?+subst} - operator acting on a special variable,
4738 * or the beginning of variable name.
4739 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004740 if (ch == EOF
4741 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4742 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004743 bad_dollar_syntax:
4744 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004745 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4746 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004747 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004748 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004749 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004750 ch |= quote_mask;
4751
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004752 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004753 * However, this regresses some of our testsuite cases
4754 * which check invalid constructs like ${%}.
4755 * Oh well... let's check that the var name part is fine... */
4756
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004757 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004758 unsigned pos;
4759
Denys Vlasenko74369502010-05-21 19:52:01 +02004760 o_addchr(dest, ch);
4761 debug_printf_parse(": '%c'\n", ch);
4762
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004763 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004764 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004765 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004766 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004767
Denys Vlasenko74369502010-05-21 19:52:01 +02004768 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004769 unsigned end_ch;
4770 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004771 /* handle parameter expansions
4772 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4773 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004774 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4775 if (len_single_ch != '#'
4776 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4777 || i_peek(input) != '}'
4778 ) {
4779 goto bad_dollar_syntax;
4780 }
4781 /* else: it's "length of C" ${#C} op,
4782 * where C is a single char
4783 * special var name, e.g. ${#!}.
4784 */
4785 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004786 /* Eat everything until closing '}' (or ':') */
4787 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004788 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004789 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004790 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004791 ) {
4792 /* It's ${var:N[:M]} thing */
4793 end_ch = '}' * 0x100 + ':';
4794 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004795 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004796 && ch == '/'
4797 ) {
4798 /* It's ${var/[/]pattern[/repl]} thing */
4799 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4800 i_getch(input);
4801 nommu_addchr(as_string, '/');
4802 ch = '\\';
4803 }
4804 end_ch = '}' * 0x100 + '/';
4805 }
4806 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004807 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004808 if (!BB_MMU)
4809 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004810#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004811 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004812 if (last_ch == 0) /* error? */
4813 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004814#else
4815#error Simple code to only allow ${var} is not implemented
4816#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004817 if (as_string) {
4818 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004819 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004820 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004821
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004822 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4823 && (end_ch & 0xff00)
4824 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004825 /* close the first block: */
4826 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004827 /* while parsing N from ${var:N[:M]}
4828 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004829 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004830 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004831 end_ch = '}';
4832 goto again;
4833 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004834 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004835 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004836 /* it's ${var:N} - emulate :999999999 */
4837 o_addstr(dest, "999999999");
4838 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004839 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004840 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004841 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004842 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004843 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004844 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4845 break;
4846 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004847#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004848 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004849 unsigned pos;
4850
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004851 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004852 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004853# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004854 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004855 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004856 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004857 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4858 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004859 if (!BB_MMU)
4860 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004861 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4862 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004863 if (as_string) {
4864 o_addstr(as_string, dest->data + pos);
4865 o_addchr(as_string, ')');
4866 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004867 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004868 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004869 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004870 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004871# endif
4872# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004873 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4874 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004875 if (!BB_MMU)
4876 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004877 if (!add_till_closing_bracket(dest, input, ')'))
4878 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004879 if (as_string) {
4880 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004881 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004882 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004883 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004884# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004885 break;
4886 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004887#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004888 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004889 goto make_var;
4890#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004891 /* TODO: $_ and $-: */
4892 /* $_ Shell or shell script name; or last argument of last command
4893 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4894 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004895 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004896 ch = i_getch(input);
4897 nommu_addchr(as_string, ch);
4898 ch = i_peek_and_eat_bkslash_nl(input);
4899 if (isalnum(ch)) { /* it's $_name or $_123 */
4900 ch = '_';
4901 goto make_var1;
4902 }
4903 /* else: it's $_ */
4904#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004905 default:
4906 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004907 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004908 debug_printf_parse("parse_dollar return 1 (ok)\n");
4909 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004910#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004911}
4912
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004913#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02004914#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004915 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004916#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004917#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004918static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004919 o_string *dest,
4920 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02004921 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004922{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004923 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004924 int next;
4925
4926 again:
4927 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004928 if (ch != EOF)
4929 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004930 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004931 debug_printf_parse("encode_string return 1 (ok)\n");
4932 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004933 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004934 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004935 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004936 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004937 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004938 }
4939 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004940 if (ch != '\n') {
4941 next = i_peek(input);
4942 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004943 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004944 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02004945 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004946 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02004947 /* Testcase: in interactive shell a file with
4948 * echo "unterminated string\<eof>
4949 * is sourced.
4950 */
4951 syntax_error_unterm_ch('"');
4952 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004953 }
4954 /* bash:
4955 * "The backslash retains its special meaning [in "..."]
4956 * only when followed by one of the following characters:
4957 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004958 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004959 * NB: in (unquoted) heredoc, above does not apply to ",
4960 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004961 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004962 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004963 ch = i_getch(input); /* eat next */
4964 if (ch == '\n')
4965 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004966 } /* else: ch remains == '\\', and we double it below: */
4967 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004968 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004969 goto again;
4970 }
4971 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004972 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4973 debug_printf_parse("encode_string return 0: "
4974 "parse_dollar returned 0 (error)\n");
4975 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004976 }
4977 goto again;
4978 }
4979#if ENABLE_HUSH_TICK
4980 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004981 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004982 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4983 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004984 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4985 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004986 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4987 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004988 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004989 }
4990#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004991 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004992 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004993#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004994}
4995
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004996/*
4997 * Scan input until EOF or end_trigger char.
4998 * Return a list of pipes to execute, or NULL on EOF
4999 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005000 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005001 * reset parsing machinery and start parsing anew,
5002 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005003 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005004static struct pipe *parse_stream(char **pstring,
5005 struct in_str *input,
5006 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005007{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005008 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005009 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005010
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005011 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005012 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005013 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005014 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005015 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005016 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005017
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005018 initialize_context(&ctx);
5019
5020 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5021 * Preventing this:
5022 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005023 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005024
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005025 /* We used to separate words on $IFS here. This was wrong.
5026 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005027 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005028 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005029
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005030 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005031 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005032 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005033 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005034 int ch;
5035 int next;
5036 int redir_fd;
5037 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005038
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005039 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005040 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005041 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005042 if (ch == EOF) {
5043 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005044
5045 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005046 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005047 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005048 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005049 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005050 syntax_error_unterm_ch('(');
5051 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005052 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005053 if (end_trigger == '}') {
5054 syntax_error_unterm_ch('{');
5055 goto parse_error;
5056 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005057
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005058 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005059 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005060 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005061 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005062 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005063 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005064 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005065 /* (this makes bare "&" cmd a no-op.
5066 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005067 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005068 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005069 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005070 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005071 pi = NULL;
5072 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005073#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005074 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005075 if (pstring)
5076 *pstring = ctx.as_string.data;
5077 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005078 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005079#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005080 debug_leave();
5081 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005082 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005083 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005084
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005085 /* Handle "'" and "\" first, as they won't play nice with
5086 * i_peek_and_eat_bkslash_nl() anyway:
5087 * echo z\\
5088 * and
5089 * echo '\
5090 * '
5091 * would break.
5092 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005093 if (ch == '\\') {
5094 ch = i_getch(input);
5095 if (ch == '\n')
5096 continue; /* drop \<newline>, get next char */
5097 nommu_addchr(&ctx.as_string, '\\');
5098 o_addchr(&ctx.word, '\\');
5099 if (ch == EOF) {
5100 /* Testcase: eval 'echo Ok\' */
5101 /* bash-4.3.43 was removing backslash,
5102 * but 4.4.19 retains it, most other shells too
5103 */
5104 continue; /* get next char */
5105 }
5106 /* Example: echo Hello \2>file
5107 * we need to know that word 2 is quoted
5108 */
5109 ctx.word.has_quoted_part = 1;
5110 nommu_addchr(&ctx.as_string, ch);
5111 o_addchr(&ctx.word, ch);
5112 continue; /* get next char */
5113 }
5114 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005115 if (ch == '\'') {
5116 ctx.word.has_quoted_part = 1;
5117 next = i_getch(input);
5118 if (next == '\'' && !ctx.pending_redirect)
5119 goto insert_empty_quoted_str_marker;
5120
5121 ch = next;
5122 while (1) {
5123 if (ch == EOF) {
5124 syntax_error_unterm_ch('\'');
5125 goto parse_error;
5126 }
5127 nommu_addchr(&ctx.as_string, ch);
5128 if (ch == '\'')
5129 break;
5130 if (ch == SPECIAL_VAR_SYMBOL) {
5131 /* Convert raw ^C to corresponding special variable reference */
5132 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5133 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5134 }
5135 o_addqchr(&ctx.word, ch);
5136 ch = i_getch(input);
5137 }
5138 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005139 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005140
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005141 next = '\0';
5142 if (ch != '\n')
5143 next = i_peek_and_eat_bkslash_nl(input);
5144
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005145 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005146 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005147 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005148 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005149 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005150 || ctx.word.length /* word{... - non-special */
5151 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005152 || (next != ';' /* }; - special */
5153 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005154 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005155 && next != '&' /* }& and }&& ... - special */
5156 && next != '|' /* }|| ... - special */
5157 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005158 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005159 ) {
5160 /* They are not special, skip "{}" */
5161 is_special += 2;
5162 }
5163 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005164 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005165
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005166 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005167 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005168 o_addQchr(&ctx.word, ch);
5169 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5170 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005171 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005172 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005173 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005174 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5175 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005176 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005177 continue;
5178 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005179
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005180 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005181#if ENABLE_HUSH_LINENO_VAR
5182/* Case:
5183 * "while ...; do<whitespace><newline>
5184 * cmd ..."
5185 * would think that "cmd" starts in <whitespace> -
5186 * i.e., at the previous line.
5187 * We need to skip all whitespace before newlines.
5188 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005189 while (ch != '\n') {
5190 next = i_peek(input);
5191 if (next != ' ' && next != '\t' && next != '\n')
5192 break; /* next char is not ws */
5193 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005194 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005195 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005196#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005197 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005198 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005199 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005200 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005201 /* Is this a case when newline is simply ignored?
5202 * Some examples:
5203 * "cmd | <newline> cmd ..."
5204 * "case ... in <newline> word) ..."
5205 */
5206 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005207 && ctx.word.length == 0
5208 && !ctx.word.has_quoted_part
5209 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005210 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005211 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005212 * Without check #1, interactive shell
5213 * ignores even bare <newline>,
5214 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005215 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005216 * ps2> _ <=== wrong, should be ps1
5217 * Without check #2, "cmd & <newline>"
5218 * is similarly mistreated.
5219 * (BTW, this makes "cmd & cmd"
5220 * and "cmd && cmd" non-orthogonal.
5221 * Really, ask yourself, why
5222 * "cmd && <newline>" doesn't start
5223 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005224 * The only reason is that it might be
5225 * a "cmd1 && <nl> cmd2 &" construct,
5226 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005227 */
5228 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005229 if (pi->num_cmds != 0 /* check #1 */
5230 && pi->followup != PIPE_BG /* check #2 */
5231 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005232 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005233 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005234 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005235 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005236 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005237 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005238 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005239 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005240 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005241 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005242 heredoc_cnt = 0;
5243 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005244 ctx.is_assignment = MAYBE_ASSIGNMENT;
5245 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005246 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005247 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005248 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005249 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005250 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005251
5252 /* "cmd}" or "cmd }..." without semicolon or &:
5253 * } is an ordinary char in this case, even inside { cmd; }
5254 * Pathological example: { ""}; } should exec "}" cmd
5255 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005256 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005257 if (ctx.word.length != 0 /* word} */
5258 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005259 ) {
5260 goto ordinary_char;
5261 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005262 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5263 /* Generally, there should be semicolon: "cmd; }"
5264 * However, bash allows to omit it if "cmd" is
5265 * a group. Examples:
5266 * { { echo 1; } }
5267 * {(echo 1)}
5268 * { echo 0 >&2 | { echo 1; } }
5269 * { while false; do :; done }
5270 * { case a in b) ;; esac }
5271 */
5272 if (ctx.command->group)
5273 goto term_group;
5274 goto ordinary_char;
5275 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005276 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005277 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005278 goto skip_end_trigger;
5279 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005280 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005281 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005282 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005283 && (ch != ';' || heredoc_cnt == 0)
5284#if ENABLE_HUSH_CASE
5285 && (ch != ')'
5286 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005287 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005288 )
5289#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005290 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005291 if (heredoc_cnt) {
5292 /* This is technically valid:
5293 * { cat <<HERE; }; echo Ok
5294 * heredoc
5295 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005296 * HERE
5297 * but we don't support this.
5298 * We require heredoc to be in enclosing {}/(),
5299 * if any.
5300 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005301 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005302 goto parse_error;
5303 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005304 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005305 goto parse_error;
5306 }
5307 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005308 ctx.is_assignment = MAYBE_ASSIGNMENT;
5309 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005310 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005311 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005312 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005313 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005314 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005315#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005316 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005317 if (pstring)
5318 *pstring = ctx.as_string.data;
5319 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005320 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005321#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005322 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5323 /* Example: bare "{ }", "()" */
5324 G.last_exitcode = 2; /* bash compat */
5325 syntax_error_unexpected_ch(ch);
5326 goto parse_error2;
5327 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005328 debug_printf_parse("parse_stream return %p: "
5329 "end_trigger char found\n",
5330 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005331 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005332 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005333 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005334 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005335
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005336 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005337 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005338
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005339 /* Catch <, > before deciding whether this word is
5340 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5341 switch (ch) {
5342 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005343 redir_fd = redirect_opt_num(&ctx.word);
5344 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005345 goto parse_error;
5346 }
5347 redir_style = REDIRECT_OVERWRITE;
5348 if (next == '>') {
5349 redir_style = REDIRECT_APPEND;
5350 ch = i_getch(input);
5351 nommu_addchr(&ctx.as_string, ch);
5352 }
5353#if 0
5354 else if (next == '(') {
5355 syntax_error(">(process) not supported");
5356 goto parse_error;
5357 }
5358#endif
5359 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5360 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005361 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005362 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005363 redir_fd = redirect_opt_num(&ctx.word);
5364 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005365 goto parse_error;
5366 }
5367 redir_style = REDIRECT_INPUT;
5368 if (next == '<') {
5369 redir_style = REDIRECT_HEREDOC;
5370 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005371 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005372 ch = i_getch(input);
5373 nommu_addchr(&ctx.as_string, ch);
5374 } else if (next == '>') {
5375 redir_style = REDIRECT_IO;
5376 ch = i_getch(input);
5377 nommu_addchr(&ctx.as_string, ch);
5378 }
5379#if 0
5380 else if (next == '(') {
5381 syntax_error("<(process) not supported");
5382 goto parse_error;
5383 }
5384#endif
5385 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5386 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005387 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005388 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005389 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005390 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005391 /* note: we do not add it to &ctx.as_string */
5392/* TODO: in bash:
5393 * comment inside $() goes to the next \n, even inside quoted string (!):
5394 * cmd "$(cmd2 #comment)" - syntax error
5395 * cmd "`cmd2 #comment`" - ok
5396 * We accept both (comment ends where command subst ends, in both cases).
5397 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005398 while (1) {
5399 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005400 if (ch == '\n') {
5401 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005402 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005403 }
5404 ch = i_getch(input);
5405 if (ch == EOF)
5406 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005407 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005408 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005409 }
5410 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005411 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005412 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005413
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005414 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005415 /* check that we are not in word in "a=1 2>word b=1": */
5416 && !ctx.pending_redirect
5417 ) {
5418 /* ch is a special char and thus this word
5419 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005420 ctx.is_assignment = NOT_ASSIGNMENT;
5421 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005422 }
5423
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005424 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5425
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005426 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005427 case SPECIAL_VAR_SYMBOL:
5428 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005429 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5430 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005431 /* fall through */
5432 case '#':
5433 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005434 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005435 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005436 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005437 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005438 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005439 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005440 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005441 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005442 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005443 case '"':
5444 ctx.word.has_quoted_part = 1;
5445 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005446 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005447 insert_empty_quoted_str_marker:
5448 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005449 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5450 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005451 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005452 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005453 if (ctx.is_assignment == NOT_ASSIGNMENT)
5454 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005455 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005456 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005457 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005458 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005459#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005460 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005461 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005462
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005463 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5464 o_addchr(&ctx.word, '`');
5465 USE_FOR_NOMMU(pos = ctx.word.length;)
5466 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005467 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005468# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005469 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005470 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005471# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005472 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5473 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005474 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005475 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005476#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005477 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005478#if ENABLE_HUSH_CASE
5479 case_semi:
5480#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005481 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005482 goto parse_error;
5483 }
5484 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005485#if ENABLE_HUSH_CASE
5486 /* Eat multiple semicolons, detect
5487 * whether it means something special */
5488 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005489 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005490 if (ch != ';')
5491 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005492 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005493 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005494 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005495 ctx.ctx_dsemicolon = 1;
5496 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005497 break;
5498 }
5499 }
5500#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005501 new_cmd:
5502 /* We just finished a cmd. New one may start
5503 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005504 ctx.is_assignment = MAYBE_ASSIGNMENT;
5505 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005506 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005507 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005508 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005509 goto parse_error;
5510 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005511 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005512 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005513 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005514 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005515 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005516 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005517 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005518 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005519 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005520 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005521 goto parse_error;
5522 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005523#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005524 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005525 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005526#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005527 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005528 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005529 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005530 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005531 } else {
5532 /* we could pick up a file descriptor choice here
5533 * with redirect_opt_num(), but bash doesn't do it.
5534 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005535 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005536 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005537 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005538 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005539#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005540 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005541 if (ctx.ctx_res_w == RES_MATCH
5542 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005543 && ctx.word.length == 0 /* not word(... */
5544 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005545 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005546 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005547 }
5548#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005549 case '{':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005550 if (parse_group(&ctx, input, ch) != 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005551 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005552 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005553 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005554 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005555#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005556 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005557 goto case_semi;
5558#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005559 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005560 /* proper use of this character is caught by end_trigger:
5561 * if we see {, we call parse_group(..., end_trigger='}')
5562 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005563 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005564 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005565 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005566 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005567 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005568 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005569 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005570 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005571
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005572 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005573 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005574 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005575 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005576 struct parse_context *pctx;
5577 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005578
5579 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005580 * Sample for finding leaks on syntax error recovery path.
5581 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005582 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005583 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005584 * while if (true | { true;}); then echo ok; fi; do break; done
5585 * 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 +00005586 */
5587 pctx = &ctx;
5588 do {
5589 /* Update pipe/command counts,
5590 * otherwise freeing may miss some */
5591 done_pipe(pctx, PIPE_SEQ);
5592 debug_printf_clean("freeing list %p from ctx %p\n",
5593 pctx->list_head, pctx);
5594 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005595 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005596 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005597#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005598 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005599#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005600 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005601 if (pctx != &ctx) {
5602 free(pctx);
5603 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005604 IF_HAS_KEYWORDS(pctx = p2;)
5605 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005606
Denys Vlasenko18567402018-07-20 17:51:31 +02005607 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005608#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005609 if (pstring)
5610 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005611#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005612 debug_leave();
5613 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005614 }
Eric Andersen25f27032001-04-26 23:22:31 +00005615}
5616
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005617
5618/*** Execution routines ***/
5619
5620/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005621#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005622#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005623 expand_string_to_string(str)
5624#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005625static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005626#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005627static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005628#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005629static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005630
5631/* expand_strvec_to_strvec() takes a list of strings, expands
5632 * all variable references within and returns a pointer to
5633 * a list of expanded strings, possibly with larger number
5634 * of strings. (Think VAR="a b"; echo $VAR).
5635 * This new list is allocated as a single malloc block.
5636 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005637 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005638 * Caller can deallocate entire list by single free(list). */
5639
Denys Vlasenko238081f2010-10-03 14:26:26 +02005640/* A horde of its helpers come first: */
5641
5642static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5643{
5644 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005645 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005646
Denys Vlasenko9e800222010-10-03 14:28:04 +02005647#if ENABLE_HUSH_BRACE_EXPANSION
5648 if (c == '{' || c == '}') {
5649 /* { -> \{, } -> \} */
5650 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005651 /* And now we want to add { or } and continue:
5652 * o_addchr(o, c);
5653 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005654 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005655 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005656 }
5657#endif
5658 o_addchr(o, c);
5659 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005660 /* \z -> \\\z; \<eol> -> \\<eol> */
5661 o_addchr(o, '\\');
5662 if (len) {
5663 len--;
5664 o_addchr(o, '\\');
5665 o_addchr(o, *str++);
5666 }
5667 }
5668 }
5669}
5670
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005671/* Store given string, finalizing the word and starting new one whenever
5672 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005673 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005674 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005675 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5676 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005677static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005678{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005679 int last_is_ifs = 0;
5680
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005681 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005682 int word_len;
5683
5684 if (!*str) /* EOL - do not finalize word */
5685 break;
5686 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005687 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005688 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005689 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005690 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005691 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005692 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005693 * Example: "v='\*'; echo b$v" prints "b\*"
5694 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005695 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005696 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005697 /*/ Why can't we do it easier? */
5698 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5699 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5700 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005701 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005702 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005703 if (!*str) /* EOL - do not finalize word */
5704 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005705 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005706
5707 /* We know str here points to at least one IFS char */
5708 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005709 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005710 if (!*str) /* EOL - do not finalize word */
5711 break;
5712
Denys Vlasenko96786362018-04-11 16:02:58 +02005713 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5714 && strchr(G.ifs, *str) /* the second check would fail */
5715 ) {
5716 /* This is a non-whitespace $IFS char */
5717 /* Skip it and IFS whitespace chars, start new word */
5718 str++;
5719 str += strspn(str, G.ifs_whitespace);
5720 goto new_word;
5721 }
5722
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005723 /* Start new word... but not always! */
5724 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005725 if (output->has_quoted_part
5726 /* Case "v=' a'; echo $v":
5727 * here nothing precedes the space in $v expansion,
5728 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005729 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005730 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005731 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005732 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005733 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005734 o_addchr(output, '\0');
5735 debug_print_list("expand_on_ifs", output, n);
5736 n = o_save_ptr(output, n);
5737 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005738 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005739
Denys Vlasenko168579a2018-07-19 13:45:54 +02005740 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005741 debug_print_list("expand_on_ifs[1]", output, n);
5742 return n;
5743}
5744
5745/* Helper to expand $((...)) and heredoc body. These act as if
5746 * they are in double quotes, with the exception that they are not :).
5747 * Just the rules are similar: "expand only $var and `cmd`"
5748 *
5749 * Returns malloced string.
5750 * As an optimization, we return NULL if expansion is not needed.
5751 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005752static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005753{
5754 char *exp_str;
5755 struct in_str input;
5756 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005757 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005758
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005759 cp = str;
5760 for (;;) {
5761 if (!*cp) return NULL; /* string has no special chars */
5762 if (*cp == '$') break;
5763 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005764#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005765 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005766#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005767 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005768 }
5769
5770 /* We need to expand. Example:
5771 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5772 */
5773 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005774 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005775//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005776 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005777 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005778 EXP_FLAG_ESC_GLOB_CHARS,
5779 /*unbackslash:*/ 1
5780 );
5781 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005782 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005783 return exp_str;
5784}
5785
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005786/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5787 * These can contain single- and double-quoted strings,
5788 * and treated as if the ARG string is initially unquoted. IOW:
5789 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5790 * a dquoted string: "${var#"zz"}"), the difference only comes later
5791 * (word splitting and globbing of the ${var...} result).
5792 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005793#if !BASH_PATTERN_SUBST
5794#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5795 encode_then_expand_vararg(str, handle_squotes)
5796#endif
5797static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5798{
5799#if !BASH_PATTERN_SUBST
5800 const int do_unbackslash = 0;
5801#endif
5802 char *exp_str;
5803 struct in_str input;
5804 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005805 const char *cp;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005806
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005807 cp = str;
5808 for (;;) {
5809 if (!*cp) return NULL; /* string has no special chars */
5810 if (*cp == '$') break;
5811 if (*cp == '\\') break;
5812 if (*cp == '\'') break;
5813 if (*cp == '"') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005814#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005815 if (*cp == '`') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005816#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005817 cp++;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005818 }
5819
Denys Vlasenkob762c782018-07-17 14:21:38 +02005820 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005821 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005822 exp_str = NULL;
5823
5824 for (;;) {
5825 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005826
5827 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005828 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5829 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005830
5831 if (!dest.o_expflags) {
5832 if (ch == EOF)
5833 break;
5834 if (handle_squotes && ch == '\'') {
5835 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02005836 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005837 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005838 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005839 }
5840 if (ch == EOF) {
5841 syntax_error_unterm_ch('"');
5842 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005843 }
5844 if (ch == '"') {
5845 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5846 continue;
5847 }
5848 if (ch == '\\') {
5849 ch = i_getch(&input);
5850 if (ch == EOF) {
5851//example? error message? syntax_error_unterm_ch('"');
5852 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5853 goto ret;
5854 }
5855 o_addqchr(&dest, ch);
5856 continue;
5857 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02005858 if (ch == '$') {
5859 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5860 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5861 goto ret;
5862 }
5863 continue;
5864 }
5865#if ENABLE_HUSH_TICK
5866 if (ch == '`') {
5867 //unsigned pos = dest->length;
5868 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5869 o_addchr(&dest, 0x80 | '`');
5870 if (!add_till_backquote(&dest, &input,
5871 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5872 )
5873 ) {
5874 goto ret; /* error */
5875 }
5876 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5877 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5878 continue;
5879 }
5880#endif
5881 o_addQchr(&dest, ch);
5882 } /* for (;;) */
5883
5884 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5885 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02005886 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5887 do_unbackslash
5888 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02005889 ret:
5890 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005891 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005892 return exp_str;
5893}
5894
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005895/* Expanding ARG in ${var+ARG}, ${var-ARG}
5896 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02005897static int encode_then_append_var_plusminus(o_string *output, int n,
5898 const char *str, int dquoted)
5899{
5900 struct in_str input;
5901 o_string dest = NULL_O_STRING;
5902
5903#if 0 //todo?
5904 const char *cp;
5905 cp = str;
5906 for (;;) {
5907 if (!*cp) return NULL; /* string has no special chars */
5908 if (*cp == '$') break;
5909 if (*cp == '\\') break;
5910 if (*cp == '\'') break;
5911 if (*cp == '"') break;
5912#if ENABLE_HUSH_TICK
5913 if (*cp == '`') break;
5914#endif
5915 cp++;
5916 }
5917#endif
5918
Denys Vlasenko294eb462018-07-20 16:18:59 +02005919 setup_string_in_str(&input, str);
5920
5921 for (;;) {
5922 int ch;
5923
5924 ch = i_getch(&input);
5925 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
5926 __func__, ch, ch, dest.o_expflags);
5927
5928 if (!dest.o_expflags) {
5929 if (ch == EOF)
5930 break;
5931 if (!dquoted && strchr(G.ifs, ch)) {
5932 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
5933 * do not assume we are at the start of the word (PREFIX above).
5934 */
5935 if (dest.data) {
5936 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02005937 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02005938 o_addchr(output, '\0');
5939 n = o_save_ptr(output, n); /* create next word */
5940 } else
5941 if (output->length != o_get_last_ptr(output, n)
5942 || output->has_quoted_part
5943 ) {
5944 /* For these cases:
5945 * f() { for i; do echo "|$i|"; done; }; x=x
5946 * f a${x:+ }b # 1st condition
5947 * |a|
5948 * |b|
5949 * f ""${x:+ }b # 2nd condition
5950 * ||
5951 * |b|
5952 */
5953 o_addchr(output, '\0');
5954 n = o_save_ptr(output, n); /* create next word */
5955 }
5956 continue;
5957 }
5958 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005959 if (!add_till_single_quote_dquoted(&dest, &input))
5960 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02005961 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5962 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02005963 continue;
5964 }
5965 }
5966 if (ch == EOF) {
5967 syntax_error_unterm_ch('"');
5968 goto ret; /* error */
5969 }
5970 if (ch == '"') {
5971 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02005972 if (dest.o_expflags) {
5973 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5974 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5975 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02005976 continue;
5977 }
5978 if (ch == '\\') {
5979 ch = i_getch(&input);
5980 if (ch == EOF) {
5981//example? error message? syntax_error_unterm_ch('"');
5982 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5983 goto ret;
5984 }
5985 o_addqchr(&dest, ch);
5986 continue;
5987 }
5988 if (ch == '$') {
5989 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
5990 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5991 goto ret;
5992 }
5993 continue;
5994 }
5995#if ENABLE_HUSH_TICK
5996 if (ch == '`') {
5997 //unsigned pos = dest->length;
5998 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5999 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6000 if (!add_till_backquote(&dest, &input,
6001 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6002 )
6003 ) {
6004 goto ret; /* error */
6005 }
6006 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6007 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6008 continue;
6009 }
6010#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006011 if (dquoted) {
6012 /* Always glob-protect if in dquotes:
6013 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6014 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6015 */
6016 o_addqchr(&dest, ch);
6017 } else {
6018 /* Glob-protect only if char is quoted:
6019 * x=x; echo ${x:+/bin/c*} - prints many filenames
6020 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6021 */
6022 o_addQchr(&dest, ch);
6023 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006024 } /* for (;;) */
6025
6026 if (dest.data) {
6027 n = expand_vars_to_list(output, n, dest.data);
6028 }
6029 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006030 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006031 return n;
6032}
6033
Denys Vlasenko0b883582016-12-23 16:49:07 +01006034#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006035static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006036{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006037 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006038 arith_t res;
6039 char *exp_str;
6040
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006041 math_state.lookupvar = get_local_var_value;
6042 math_state.setvar = set_local_var_from_halves;
6043 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006044 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006045 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006046 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006047 if (errmsg_p)
6048 *errmsg_p = math_state.errmsg;
6049 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006050 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006051 return res;
6052}
6053#endif
6054
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006055#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006056/* ${var/[/]pattern[/repl]} helpers */
6057static char *strstr_pattern(char *val, const char *pattern, int *size)
6058{
6059 while (1) {
6060 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6061 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6062 if (end) {
6063 *size = end - val;
6064 return val;
6065 }
6066 if (*val == '\0')
6067 return NULL;
6068 /* Optimization: if "*pat" did not match the start of "string",
6069 * we know that "tring", "ring" etc will not match too:
6070 */
6071 if (pattern[0] == '*')
6072 return NULL;
6073 val++;
6074 }
6075}
6076static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6077{
6078 char *result = NULL;
6079 unsigned res_len = 0;
6080 unsigned repl_len = strlen(repl);
6081
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006082 /* Null pattern never matches, including if "var" is empty */
6083 if (!pattern[0])
6084 return result; /* NULL, no replaces happened */
6085
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006086 while (1) {
6087 int size;
6088 char *s = strstr_pattern(val, pattern, &size);
6089 if (!s)
6090 break;
6091
6092 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006093 strcpy(mempcpy(result + res_len, val, s - val), repl);
6094 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006095 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6096
6097 val = s + size;
6098 if (exp_op == '/')
6099 break;
6100 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006101 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006102 result = xrealloc(result, res_len + strlen(val) + 1);
6103 strcpy(result + res_len, val);
6104 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6105 }
6106 debug_printf_varexp("result:'%s'\n", result);
6107 return result;
6108}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006109#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006110
Denys Vlasenko168579a2018-07-19 13:45:54 +02006111static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006112 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006113{
6114 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6115 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6116 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6117 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006118 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006119 } else { /* quoted "$VAR" */
6120 output->has_quoted_part = 1;
6121 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6122 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6123 if (val && val[0])
6124 o_addQstr(output, val);
6125 }
6126 return n;
6127}
6128
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006129/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006130 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006131static NOINLINE int expand_one_var(o_string *output, int n,
6132 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006133{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006134 const char *val;
6135 char *to_be_freed;
6136 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006137 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006138 char exp_op;
6139 char exp_save = exp_save; /* for compiler */
6140 char *exp_saveptr; /* points to expansion operator */
6141 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006142 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006143
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006144 val = NULL;
6145 to_be_freed = NULL;
6146 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006147 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006148 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006149 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006150 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006151 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006152 exp_op = 0;
6153
Denys Vlasenkob762c782018-07-17 14:21:38 +02006154 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006155 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6156 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6157 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006158 ) {
6159 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006160 var++;
6161 exp_op = 'L';
6162 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006163 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006164 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006165 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006166 ) {
6167 /* ${?:0}, ${#[:]%0} etc */
6168 exp_saveptr = var + 1;
6169 } else {
6170 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6171 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6172 }
6173 exp_op = exp_save = *exp_saveptr;
6174 if (exp_op) {
6175 exp_word = exp_saveptr + 1;
6176 if (exp_op == ':') {
6177 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006178//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006179 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006180 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006181 ) {
6182 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6183 exp_op = ':';
6184 exp_word--;
6185 }
6186 }
6187 *exp_saveptr = '\0';
6188 } /* else: it's not an expansion op, but bare ${var} */
6189 }
6190
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006191 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006192 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006193 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006194 int nn = xatoi_positive(var);
6195 if (nn < G.global_argc)
6196 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006197 /* else val remains NULL: $N with too big N */
6198 } else {
6199 switch (var[0]) {
6200 case '$': /* pid */
6201 val = utoa(G.root_pid);
6202 break;
6203 case '!': /* bg pid */
6204 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6205 break;
6206 case '?': /* exitcode */
6207 val = utoa(G.last_exitcode);
6208 break;
6209 case '#': /* argc */
6210 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6211 break;
6212 default:
6213 val = get_local_var_value(var);
6214 }
6215 }
6216
6217 /* Handle any expansions */
6218 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006219 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006220 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006221 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006222 debug_printf_expand("%s\n", val);
6223 } else if (exp_op) {
6224 if (exp_op == '%' || exp_op == '#') {
6225 /* Standard-mandated substring removal ops:
6226 * ${parameter%word} - remove smallest suffix pattern
6227 * ${parameter%%word} - remove largest suffix pattern
6228 * ${parameter#word} - remove smallest prefix pattern
6229 * ${parameter##word} - remove largest prefix pattern
6230 *
6231 * Word is expanded to produce a glob pattern.
6232 * Then var's value is matched to it and matching part removed.
6233 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006234//FIXME: ${x#...${...}...}
6235//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6236//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006237 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006238 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006239 char *exp_exp_word;
6240 char *loc;
6241 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006242 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006243 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006244 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006245 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006246 if (exp_exp_word)
6247 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006248 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6249 /*
6250 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006251 * G.global_argv and results of utoa and get_local_var_value
6252 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006253 * scan_and_match momentarily stores NULs there.
6254 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006255 t = (char*)val;
6256 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006257 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 +02006258 free(exp_exp_word);
6259 if (loc) { /* match was found */
6260 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006261 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006262 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006263 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006264 }
6265 }
6266 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006267#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006268 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006269 /* It's ${var/[/]pattern[/repl]} thing.
6270 * Note that in encoded form it has TWO parts:
6271 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006272 * and if // is used, it is encoded as \:
6273 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006274 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006275 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006276 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006277 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006278 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006279 * >az >bz
6280 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6281 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6282 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6283 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006284 * (note that a*z _pattern_ is never globbed!)
6285 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006286 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006287 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006288 if (!pattern)
6289 pattern = xstrdup(exp_word);
6290 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6291 *p++ = SPECIAL_VAR_SYMBOL;
6292 exp_word = p;
6293 p = strchr(p, SPECIAL_VAR_SYMBOL);
6294 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006295 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006296 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6297 /* HACK ALERT. We depend here on the fact that
6298 * G.global_argv and results of utoa and get_local_var_value
6299 * are actually in writable memory:
6300 * replace_pattern momentarily stores NULs there. */
6301 t = (char*)val;
6302 to_be_freed = replace_pattern(t,
6303 pattern,
6304 (repl ? repl : exp_word),
6305 exp_op);
6306 if (to_be_freed) /* at least one replace happened */
6307 val = to_be_freed;
6308 free(pattern);
6309 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006310 } else {
6311 /* Empty variable always gives nothing */
6312 // "v=''; echo ${v/*/w}" prints "", not "w"
6313 /* Just skip "replace" part */
6314 *p++ = SPECIAL_VAR_SYMBOL;
6315 p = strchr(p, SPECIAL_VAR_SYMBOL);
6316 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006317 }
6318 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006319#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006320 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006321#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006322 /* It's ${var:N[:M]} bashism.
6323 * Note that in encoded form it has TWO parts:
6324 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6325 */
6326 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006327 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006328
Denys Vlasenko063847d2010-09-15 13:33:02 +02006329 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6330 if (errmsg)
6331 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006332 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6333 *p++ = SPECIAL_VAR_SYMBOL;
6334 exp_word = p;
6335 p = strchr(p, SPECIAL_VAR_SYMBOL);
6336 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006337 len = expand_and_evaluate_arith(exp_word, &errmsg);
6338 if (errmsg)
6339 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006340 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006341 if (beg < 0) {
6342 /* negative beg counts from the end */
6343 beg = (arith_t)strlen(val) + beg;
6344 if (beg < 0) /* ${v: -999999} is "" */
6345 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006346 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006347 debug_printf_varexp("from val:'%s'\n", val);
6348 if (len < 0) {
6349 /* in bash, len=-n means strlen()-n */
6350 len = (arith_t)strlen(val) - beg + len;
6351 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006352 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006353 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006354 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006355 arith_err:
6356 val = NULL;
6357 } else {
6358 /* Paranoia. What if user entered 9999999999999
6359 * which fits in arith_t but not int? */
6360 if (len >= INT_MAX)
6361 len = INT_MAX;
6362 val = to_be_freed = xstrndup(val + beg, len);
6363 }
6364 debug_printf_varexp("val:'%s'\n", val);
6365#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006366 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006367 val = NULL;
6368#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006369 } else { /* one of "-=+?" */
6370 /* Standard-mandated substitution ops:
6371 * ${var?word} - indicate error if unset
6372 * If var is unset, word (or a message indicating it is unset
6373 * if word is null) is written to standard error
6374 * and the shell exits with a non-zero exit status.
6375 * Otherwise, the value of var is substituted.
6376 * ${var-word} - use default value
6377 * If var is unset, word is substituted.
6378 * ${var=word} - assign and use default value
6379 * If var is unset, word is assigned to var.
6380 * In all cases, final value of var is substituted.
6381 * ${var+word} - use alternative value
6382 * If var is unset, null is substituted.
6383 * Otherwise, word is substituted.
6384 *
6385 * Word is subjected to tilde expansion, parameter expansion,
6386 * command substitution, and arithmetic expansion.
6387 * If word is not needed, it is not expanded.
6388 *
6389 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6390 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006391 *
6392 * Word-splitting and single quote behavior:
6393 *
6394 * $ f() { for i; do echo "|$i|"; done; };
6395 *
6396 * $ x=; f ${x:?'x y' z}
6397 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6398 * $ x=; f "${x:?'x y' z}"
6399 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6400 *
6401 * $ x=; f ${x:='x y' z}
6402 * |x|
6403 * |y|
6404 * |z|
6405 * $ x=; f "${x:='x y' z}"
6406 * |'x y' z|
6407 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006408 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006409 * |x y|
6410 * |z|
6411 * $ x=x; f "${x:+'x y' z}"
6412 * |'x y' z|
6413 *
6414 * $ x=; f ${x:-'x y' z}
6415 * |x y|
6416 * |z|
6417 * $ x=; f "${x:-'x y' z}"
6418 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006419 */
6420 int use_word = (!val || ((exp_save == ':') && !val[0]));
6421 if (exp_op == '+')
6422 use_word = !use_word;
6423 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6424 (exp_save == ':') ? "true" : "false", use_word);
6425 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006426 if (exp_op == '+' || exp_op == '-') {
6427 /* ${var+word} - use alternative value */
6428 /* ${var-word} - use default value */
6429 n = encode_then_append_var_plusminus(output, n, exp_word,
6430 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006431 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006432 val = NULL;
6433 } else {
6434 /* ${var?word} - indicate error if unset */
6435 /* ${var=word} - assign and use default value */
6436 to_be_freed = encode_then_expand_vararg(exp_word,
6437 /*handle_squotes:*/ !(arg0 & 0x80),
6438 /*unbackslash:*/ 0
6439 );
6440 if (to_be_freed)
6441 exp_word = to_be_freed;
6442 if (exp_op == '?') {
6443 /* mimic bash message */
6444 msg_and_die_if_script("%s: %s",
6445 var,
6446 exp_word[0]
6447 ? exp_word
6448 : "parameter null or not set"
6449 /* ash has more specific messages, a-la: */
6450 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6451 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006452//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006453//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006454// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6455// bash: x: x y z
6456// $
6457// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006458 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006459 val = exp_word;
6460 }
6461 if (exp_op == '=') {
6462 /* ${var=[word]} or ${var:=[word]} */
6463 if (isdigit(var[0]) || var[0] == '#') {
6464 /* mimic bash message */
6465 msg_and_die_if_script("$%s: cannot assign in this way", var);
6466 val = NULL;
6467 } else {
6468 char *new_var = xasprintf("%s=%s", var, val);
6469 set_local_var(new_var, /*flag:*/ 0);
6470 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006471 }
6472 }
6473 }
6474 } /* one of "-=+?" */
6475
6476 *exp_saveptr = exp_save;
6477 } /* if (exp_op) */
6478
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006479 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006480 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006481
Denys Vlasenko168579a2018-07-19 13:45:54 +02006482 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006483
6484 free(to_be_freed);
6485 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006486}
6487
6488/* Expand all variable references in given string, adding words to list[]
6489 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6490 * to be filled). This routine is extremely tricky: has to deal with
6491 * variables/parameters with whitespace, $* and $@, and constructs like
6492 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006493static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006494{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006495 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006496 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006497 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006498 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006499 char *p;
6500
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006501 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6502 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006503 debug_print_list("expand_vars_to_list[0]", output, n);
6504
6505 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6506 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006507#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006508 char arith_buf[sizeof(arith_t)*3 + 2];
6509#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006510
Denys Vlasenko168579a2018-07-19 13:45:54 +02006511 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006512 o_addchr(output, '\0');
6513 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006514 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006515 }
6516
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006517 o_addblock(output, arg, p - arg);
6518 debug_print_list("expand_vars_to_list[1]", output, n);
6519 arg = ++p;
6520 p = strchr(p, SPECIAL_VAR_SYMBOL);
6521
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006522 /* Fetch special var name (if it is indeed one of them)
6523 * and quote bit, force the bit on if singleword expansion -
6524 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006525 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006526
6527 /* Is this variable quoted and thus expansion can't be null?
6528 * "$@" is special. Even if quoted, it can still
6529 * expand to nothing (not even an empty string),
6530 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006531 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006532 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006533
6534 switch (first_ch & 0x7f) {
6535 /* Highest bit in first_ch indicates that var is double-quoted */
6536 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006537 case '@': {
6538 int i;
6539 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006540 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006541 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006542 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006543 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006544 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006545 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006546 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6547 if (G.global_argv[i++][0] && G.global_argv[i]) {
6548 /* this argv[] is not empty and not last:
6549 * put terminating NUL, start new word */
6550 o_addchr(output, '\0');
6551 debug_print_list("expand_vars_to_list[2]", output, n);
6552 n = o_save_ptr(output, n);
6553 debug_print_list("expand_vars_to_list[3]", output, n);
6554 }
6555 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006556 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006557 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006558 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006559 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006560 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006561 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006562 while (1) {
6563 o_addQstr(output, G.global_argv[i]);
6564 if (++i >= G.global_argc)
6565 break;
6566 o_addchr(output, '\0');
6567 debug_print_list("expand_vars_to_list[4]", output, n);
6568 n = o_save_ptr(output, n);
6569 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006570 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006571 while (1) {
6572 o_addQstr(output, G.global_argv[i]);
6573 if (!G.global_argv[++i])
6574 break;
6575 if (G.ifs[0])
6576 o_addchr(output, G.ifs[0]);
6577 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006578 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006579 }
6580 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006581 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006582 case SPECIAL_VAR_SYMBOL: {
6583 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006584 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006585 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006586 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006587 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006588 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006589 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006590 case SPECIAL_VAR_QUOTED_SVS:
6591 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006592 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006593 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006594 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006595 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006596#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006597 case '`': {
6598 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006599 o_string subst_result = NULL_O_STRING;
6600
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006601 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006602 arg++;
6603 /* Can't just stuff it into output o_string,
6604 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006605 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006606 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6607 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006608 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006609 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006610 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006611 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006612 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006613 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006614#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006615#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006616 case '+': {
6617 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006618 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006619
6620 arg++; /* skip '+' */
6621 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6622 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006623 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006624 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6625 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006626 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006627 break;
6628 }
6629#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006630 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006631 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006632 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006633 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006634 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6635
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006636 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6637 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006638 if (*p != SPECIAL_VAR_SYMBOL)
6639 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006640 arg = ++p;
6641 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6642
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006643 if (*arg) {
6644 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006645 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006646 o_addchr(output, '\0');
6647 n = o_save_ptr(output, n);
6648 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006649 debug_print_list("expand_vars_to_list[a]", output, n);
6650 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006651 * if needed (much earlier), do not use o_addQstr here!
6652 */
6653 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006654 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006655 } else
6656 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006657 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6658 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006659 ) {
6660 n--;
6661 /* allow to reuse list[n] later without re-growth */
6662 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006663 }
6664
6665 return n;
6666}
6667
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006668static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006669{
6670 int n;
6671 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006672 o_string output = NULL_O_STRING;
6673
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006674 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006675
6676 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006677 for (;;) {
6678 /* go to next list[n] */
6679 output.ended_in_ifs = 0;
6680 n = o_save_ptr(&output, n);
6681
6682 if (!*argv)
6683 break;
6684
6685 /* expand argv[i] */
6686 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006687 /* if (!output->has_empty_slot) -- need this?? */
6688 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006689 }
6690 debug_print_list("expand_variables", &output, n);
6691
6692 /* output.data (malloced in one block) gets returned in "list" */
6693 list = o_finalize_list(&output, n);
6694 debug_print_strings("expand_variables[1]", list);
6695 return list;
6696}
6697
6698static char **expand_strvec_to_strvec(char **argv)
6699{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006700 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006701}
6702
Denys Vlasenko11752d42018-04-03 08:20:58 +02006703#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006704static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6705{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006706 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006707}
6708#endif
6709
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006710/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006711 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006712 *
6713 * NB: should NOT do globbing!
6714 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6715 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006716static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006717{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006718#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006719 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006720 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006721#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006722 char *argv[2], **list;
6723
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006724 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006725 /* This is generally an optimization, but it also
6726 * handles "", which otherwise trips over !list[0] check below.
6727 * (is this ever happens that we actually get str="" here?)
6728 */
6729 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6730 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006731 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006732 return xstrdup(str);
6733 }
6734
6735 argv[0] = (char*)str;
6736 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006737 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006738 if (!list[0]) {
6739 /* Example where it happens:
6740 * x=; echo ${x:-"$@"}
6741 */
6742 ((char*)list)[0] = '\0';
6743 } else {
6744 if (HUSH_DEBUG)
6745 if (list[1])
6746 bb_error_msg_and_die("BUG in varexp2");
6747 /* actually, just move string 2*sizeof(char*) bytes back */
6748 overlapping_strcpy((char*)list, list[0]);
6749 if (do_unbackslash)
6750 unbackslash((char*)list);
6751 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006752 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006753 return (char*)list;
6754}
6755
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006756#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006757static char* expand_strvec_to_string(char **argv)
6758{
6759 char **list;
6760
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006761 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006762 /* Convert all NULs to spaces */
6763 if (list[0]) {
6764 int n = 1;
6765 while (list[n]) {
6766 if (HUSH_DEBUG)
6767 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6768 bb_error_msg_and_die("BUG in varexp3");
6769 /* bash uses ' ' regardless of $IFS contents */
6770 list[n][-1] = ' ';
6771 n++;
6772 }
6773 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006774 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006775 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6776 return (char*)list;
6777}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006778#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006779
6780static char **expand_assignments(char **argv, int count)
6781{
6782 int i;
6783 char **p;
6784
6785 G.expanded_assignments = p = NULL;
6786 /* Expand assignments into one string each */
6787 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006788 p = add_string_to_strings(p,
6789 expand_string_to_string(argv[i],
6790 EXP_FLAG_ESC_GLOB_CHARS,
6791 /*unbackslash:*/ 1
6792 )
6793 );
6794 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006795 }
6796 G.expanded_assignments = NULL;
6797 return p;
6798}
6799
6800
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006801static void switch_off_special_sigs(unsigned mask)
6802{
6803 unsigned sig = 0;
6804 while ((mask >>= 1) != 0) {
6805 sig++;
6806 if (!(mask & 1))
6807 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006808#if ENABLE_HUSH_TRAP
6809 if (G_traps) {
6810 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006811 /* trap is '', has to remain SIG_IGN */
6812 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006813 free(G_traps[sig]);
6814 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006815 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006816#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006817 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006818 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006819 }
6820}
6821
Denys Vlasenkob347df92011-08-09 22:49:15 +02006822#if BB_MMU
6823/* never called */
6824void re_execute_shell(char ***to_free, const char *s,
6825 char *g_argv0, char **g_argv,
6826 char **builtin_argv) NORETURN;
6827
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006828static void reset_traps_to_defaults(void)
6829{
6830 /* This function is always called in a child shell
6831 * after fork (not vfork, NOMMU doesn't use this function).
6832 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006833 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006834 unsigned mask;
6835
6836 /* Child shells are not interactive.
6837 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6838 * Testcase: (while :; do :; done) + ^Z should background.
6839 * Same goes for SIGTERM, SIGHUP, SIGINT.
6840 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006841 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006842 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006843 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006844
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006845 /* Switch off special sigs */
6846 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006847# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006848 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006849# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006850 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006851 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6852 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006853
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006854# if ENABLE_HUSH_TRAP
6855 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006856 return;
6857
6858 /* Reset all sigs to default except ones with empty traps */
6859 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006860 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006861 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006862 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006863 continue; /* empty trap: has to remain SIG_IGN */
6864 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006865 free(G_traps[sig]);
6866 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006867 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006868 if (sig == 0)
6869 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006870 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006871 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006872# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006873}
6874
6875#else /* !BB_MMU */
6876
6877static void re_execute_shell(char ***to_free, const char *s,
6878 char *g_argv0, char **g_argv,
6879 char **builtin_argv) NORETURN;
6880static void re_execute_shell(char ***to_free, const char *s,
6881 char *g_argv0, char **g_argv,
6882 char **builtin_argv)
6883{
6884# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6885 /* delims + 2 * (number of bytes in printed hex numbers) */
6886 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6887 char *heredoc_argv[4];
6888 struct variable *cur;
6889# if ENABLE_HUSH_FUNCTIONS
6890 struct function *funcp;
6891# endif
6892 char **argv, **pp;
6893 unsigned cnt;
6894 unsigned long long empty_trap_mask;
6895
6896 if (!g_argv0) { /* heredoc */
6897 argv = heredoc_argv;
6898 argv[0] = (char *) G.argv0_for_re_execing;
6899 argv[1] = (char *) "-<";
6900 argv[2] = (char *) s;
6901 argv[3] = NULL;
6902 pp = &argv[3]; /* used as pointer to empty environment */
6903 goto do_exec;
6904 }
6905
6906 cnt = 0;
6907 pp = builtin_argv;
6908 if (pp) while (*pp++)
6909 cnt++;
6910
6911 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006912 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006913 int sig;
6914 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006915 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006916 empty_trap_mask |= 1LL << sig;
6917 }
6918 }
6919
6920 sprintf(param_buf, NOMMU_HACK_FMT
6921 , (unsigned) G.root_pid
6922 , (unsigned) G.root_ppid
6923 , (unsigned) G.last_bg_pid
6924 , (unsigned) G.last_exitcode
6925 , cnt
6926 , empty_trap_mask
6927 IF_HUSH_LOOPS(, G.depth_of_loop)
6928 );
6929# undef NOMMU_HACK_FMT
6930 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6931 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6932 */
6933 cnt += 6;
6934 for (cur = G.top_var; cur; cur = cur->next) {
6935 if (!cur->flg_export || cur->flg_read_only)
6936 cnt += 2;
6937 }
6938# if ENABLE_HUSH_FUNCTIONS
6939 for (funcp = G.top_func; funcp; funcp = funcp->next)
6940 cnt += 3;
6941# endif
6942 pp = g_argv;
6943 while (*pp++)
6944 cnt++;
6945 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6946 *pp++ = (char *) G.argv0_for_re_execing;
6947 *pp++ = param_buf;
6948 for (cur = G.top_var; cur; cur = cur->next) {
6949 if (strcmp(cur->varstr, hush_version_str) == 0)
6950 continue;
6951 if (cur->flg_read_only) {
6952 *pp++ = (char *) "-R";
6953 *pp++ = cur->varstr;
6954 } else if (!cur->flg_export) {
6955 *pp++ = (char *) "-V";
6956 *pp++ = cur->varstr;
6957 }
6958 }
6959# if ENABLE_HUSH_FUNCTIONS
6960 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6961 *pp++ = (char *) "-F";
6962 *pp++ = funcp->name;
6963 *pp++ = funcp->body_as_string;
6964 }
6965# endif
6966 /* We can pass activated traps here. Say, -Tnn:trap_string
6967 *
6968 * However, POSIX says that subshells reset signals with traps
6969 * to SIG_DFL.
6970 * I tested bash-3.2 and it not only does that with true subshells
6971 * of the form ( list ), but with any forked children shells.
6972 * I set trap "echo W" WINCH; and then tried:
6973 *
6974 * { echo 1; sleep 20; echo 2; } &
6975 * while true; do echo 1; sleep 20; echo 2; break; done &
6976 * true | { echo 1; sleep 20; echo 2; } | cat
6977 *
6978 * In all these cases sending SIGWINCH to the child shell
6979 * did not run the trap. If I add trap "echo V" WINCH;
6980 * _inside_ group (just before echo 1), it works.
6981 *
6982 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006983 */
6984 *pp++ = (char *) "-c";
6985 *pp++ = (char *) s;
6986 if (builtin_argv) {
6987 while (*++builtin_argv)
6988 *pp++ = *builtin_argv;
6989 *pp++ = (char *) "";
6990 }
6991 *pp++ = g_argv0;
6992 while (*g_argv)
6993 *pp++ = *g_argv++;
6994 /* *pp = NULL; - is already there */
6995 pp = environ;
6996
6997 do_exec:
6998 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006999 /* Don't propagate SIG_IGN to the child */
7000 if (SPECIAL_JOBSTOP_SIGS != 0)
7001 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007002 execve(bb_busybox_exec_path, argv, pp);
7003 /* Fallback. Useful for init=/bin/hush usage etc */
7004 if (argv[0][0] == '/')
7005 execve(argv[0], argv, pp);
7006 xfunc_error_retval = 127;
7007 bb_error_msg_and_die("can't re-execute the shell");
7008}
7009#endif /* !BB_MMU */
7010
7011
7012static int run_and_free_list(struct pipe *pi);
7013
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007014/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007015 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7016 * end_trigger controls how often we stop parsing
7017 * NUL: parse all, execute, return
7018 * ';': parse till ';' or newline, execute, repeat till EOF
7019 */
7020static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007021{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007022 /* Why we need empty flag?
7023 * An obscure corner case "false; ``; echo $?":
7024 * empty command in `` should still set $? to 0.
7025 * But we can't just set $? to 0 at the start,
7026 * this breaks "false; echo `echo $?`" case.
7027 */
7028 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007029 while (1) {
7030 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007031
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007032#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007033 if (end_trigger == ';') {
7034 G.promptmode = 0; /* PS1 */
7035 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7036 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007037#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007038 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007039 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7040 /* If we are in "big" script
7041 * (not in `cmd` or something similar)...
7042 */
7043 if (pipe_list == ERR_PTR && end_trigger == ';') {
7044 /* Discard cached input (rest of line) */
7045 int ch = inp->last_char;
7046 while (ch != EOF && ch != '\n') {
7047 //bb_error_msg("Discarded:'%c'", ch);
7048 ch = i_getch(inp);
7049 }
7050 /* Force prompt */
7051 inp->p = NULL;
7052 /* This stream isn't empty */
7053 empty = 0;
7054 continue;
7055 }
7056 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007057 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007058 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007059 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007060 debug_print_tree(pipe_list, 0);
7061 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7062 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007063 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007064 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007065 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007066 }
Eric Andersen25f27032001-04-26 23:22:31 +00007067}
7068
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007069static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007070{
7071 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007072 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7073
Eric Andersen25f27032001-04-26 23:22:31 +00007074 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007075 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007076 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007077}
7078
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007079static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00007080{
Eric Andersen25f27032001-04-26 23:22:31 +00007081 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007082 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007083
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007084 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01007085 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007086 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007087 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007088}
7089
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007090#if ENABLE_HUSH_TICK
7091static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
7092{
7093 pid_t pid;
7094 int channel[2];
7095# if !BB_MMU
7096 char **to_free = NULL;
7097# endif
7098
7099 xpipe(channel);
7100 pid = BB_MMU ? xfork() : xvfork();
7101 if (pid == 0) { /* child */
7102 disable_restore_tty_pgrp_on_exit();
7103 /* Process substitution is not considered to be usual
7104 * 'command execution'.
7105 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7106 */
7107 bb_signals(0
7108 + (1 << SIGTSTP)
7109 + (1 << SIGTTIN)
7110 + (1 << SIGTTOU)
7111 , SIG_IGN);
7112 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7113 close(channel[0]); /* NB: close _first_, then move fd! */
7114 xmove_fd(channel[1], 1);
7115 /* Prevent it from trying to handle ctrl-z etc */
7116 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007117# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007118 /* Awful hack for `trap` or $(trap).
7119 *
7120 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7121 * contains an example where "trap" is executed in a subshell:
7122 *
7123 * save_traps=$(trap)
7124 * ...
7125 * eval "$save_traps"
7126 *
7127 * Standard does not say that "trap" in subshell shall print
7128 * parent shell's traps. It only says that its output
7129 * must have suitable form, but then, in the above example
7130 * (which is not supposed to be normative), it implies that.
7131 *
7132 * bash (and probably other shell) does implement it
7133 * (traps are reset to defaults, but "trap" still shows them),
7134 * but as a result, "trap" logic is hopelessly messed up:
7135 *
7136 * # trap
7137 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7138 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7139 * # true | trap <--- trap is in subshell - no output (ditto)
7140 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7141 * trap -- 'echo Ho' SIGWINCH
7142 * # echo `(trap)` <--- in subshell in subshell - output
7143 * trap -- 'echo Ho' SIGWINCH
7144 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7145 * trap -- 'echo Ho' SIGWINCH
7146 *
7147 * The rules when to forget and when to not forget traps
7148 * get really complex and nonsensical.
7149 *
7150 * Our solution: ONLY bare $(trap) or `trap` is special.
7151 */
7152 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007153 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007154 && skip_whitespace(s + 4)[0] == '\0'
7155 ) {
7156 static const char *const argv[] = { NULL, NULL };
7157 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007158 fflush_all(); /* important */
7159 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007160 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007161# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007162# if BB_MMU
7163 reset_traps_to_defaults();
7164 parse_and_run_string(s);
7165 _exit(G.last_exitcode);
7166# else
7167 /* We re-execute after vfork on NOMMU. This makes this script safe:
7168 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7169 * huge=`cat BIG` # was blocking here forever
7170 * echo OK
7171 */
7172 re_execute_shell(&to_free,
7173 s,
7174 G.global_argv[0],
7175 G.global_argv + 1,
7176 NULL);
7177# endif
7178 }
7179
7180 /* parent */
7181 *pid_p = pid;
7182# if ENABLE_HUSH_FAST
7183 G.count_SIGCHLD++;
7184//bb_error_msg("[%d] fork in generate_stream_from_string:"
7185// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7186// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7187# endif
7188 enable_restore_tty_pgrp_on_exit();
7189# if !BB_MMU
7190 free(to_free);
7191# endif
7192 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007193 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007194}
7195
7196/* Return code is exit status of the process that is run. */
7197static int process_command_subs(o_string *dest, const char *s)
7198{
7199 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007200 pid_t pid;
7201 int status, ch, eol_cnt;
7202
7203 fp = generate_stream_from_string(s, &pid);
7204
7205 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007206 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007207 while ((ch = getc(fp)) != EOF) {
7208 if (ch == '\0')
7209 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007210 if (ch == '\n') {
7211 eol_cnt++;
7212 continue;
7213 }
7214 while (eol_cnt) {
7215 o_addchr(dest, '\n');
7216 eol_cnt--;
7217 }
7218 o_addQchr(dest, ch);
7219 }
7220
7221 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007222 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007223 /* We need to extract exitcode. Test case
7224 * "true; echo `sleep 1; false` $?"
7225 * should print 1 */
7226 safe_waitpid(pid, &status, 0);
7227 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7228 return WEXITSTATUS(status);
7229}
7230#endif /* ENABLE_HUSH_TICK */
7231
7232
7233static void setup_heredoc(struct redir_struct *redir)
7234{
7235 struct fd_pair pair;
7236 pid_t pid;
7237 int len, written;
7238 /* the _body_ of heredoc (misleading field name) */
7239 const char *heredoc = redir->rd_filename;
7240 char *expanded;
7241#if !BB_MMU
7242 char **to_free;
7243#endif
7244
7245 expanded = NULL;
7246 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007247 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007248 if (expanded)
7249 heredoc = expanded;
7250 }
7251 len = strlen(heredoc);
7252
7253 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7254 xpiped_pair(pair);
7255 xmove_fd(pair.rd, redir->rd_fd);
7256
7257 /* Try writing without forking. Newer kernels have
7258 * dynamically growing pipes. Must use non-blocking write! */
7259 ndelay_on(pair.wr);
7260 while (1) {
7261 written = write(pair.wr, heredoc, len);
7262 if (written <= 0)
7263 break;
7264 len -= written;
7265 if (len == 0) {
7266 close(pair.wr);
7267 free(expanded);
7268 return;
7269 }
7270 heredoc += written;
7271 }
7272 ndelay_off(pair.wr);
7273
7274 /* Okay, pipe buffer was not big enough */
7275 /* Note: we must not create a stray child (bastard? :)
7276 * for the unsuspecting parent process. Child creates a grandchild
7277 * and exits before parent execs the process which consumes heredoc
7278 * (that exec happens after we return from this function) */
7279#if !BB_MMU
7280 to_free = NULL;
7281#endif
7282 pid = xvfork();
7283 if (pid == 0) {
7284 /* child */
7285 disable_restore_tty_pgrp_on_exit();
7286 pid = BB_MMU ? xfork() : xvfork();
7287 if (pid != 0)
7288 _exit(0);
7289 /* grandchild */
7290 close(redir->rd_fd); /* read side of the pipe */
7291#if BB_MMU
7292 full_write(pair.wr, heredoc, len); /* may loop or block */
7293 _exit(0);
7294#else
7295 /* Delegate blocking writes to another process */
7296 xmove_fd(pair.wr, STDOUT_FILENO);
7297 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7298#endif
7299 }
7300 /* parent */
7301#if ENABLE_HUSH_FAST
7302 G.count_SIGCHLD++;
7303//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7304#endif
7305 enable_restore_tty_pgrp_on_exit();
7306#if !BB_MMU
7307 free(to_free);
7308#endif
7309 close(pair.wr);
7310 free(expanded);
7311 wait(NULL); /* wait till child has died */
7312}
7313
Denys Vlasenko2db74612017-07-07 22:07:28 +02007314struct squirrel {
7315 int orig_fd;
7316 int moved_to;
7317 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7318 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7319};
7320
Denys Vlasenko621fc502017-07-24 12:42:17 +02007321static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7322{
7323 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7324 sq[i].orig_fd = orig;
7325 sq[i].moved_to = moved;
7326 sq[i+1].orig_fd = -1; /* end marker */
7327 return sq;
7328}
7329
Denys Vlasenko2db74612017-07-07 22:07:28 +02007330static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7331{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007332 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007333 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007334
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007335 i = 0;
7336 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007337 /* If we collide with an already moved fd... */
7338 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007339 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007340 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7341 if (sq[i].moved_to < 0) /* what? */
7342 xfunc_die();
7343 return sq;
7344 }
7345 if (fd == sq[i].orig_fd) {
7346 /* Example: echo Hello >/dev/null 1>&2 */
7347 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7348 return sq;
7349 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007350 }
7351
Denys Vlasenko2db74612017-07-07 22:07:28 +02007352 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007353 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007354 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7355 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007356 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007357 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007358}
7359
Denys Vlasenko657e9002017-07-30 23:34:04 +02007360static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7361{
7362 int i;
7363
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007364 i = 0;
7365 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007366 /* If we collide with an already moved fd... */
7367 if (fd == sq[i].orig_fd) {
7368 /* Examples:
7369 * "echo 3>FILE 3>&- 3>FILE"
7370 * "echo 3>&- 3>FILE"
7371 * No need for last redirect to insert
7372 * another "need to close 3" indicator.
7373 */
7374 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7375 return sq;
7376 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007377 }
7378
7379 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7380 return append_squirrel(sq, i, fd, -1);
7381}
7382
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007383/* fd: redirect wants this fd to be used (e.g. 3>file).
7384 * Move all conflicting internally used fds,
7385 * and remember them so that we can restore them later.
7386 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007387static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007388{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007389 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7390 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007391
7392#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007393 if (fd == G.interactive_fd) {
7394 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007395 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007396 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7397 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007398 }
7399#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007400 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7401 * (1) Redirect in a forked child. No need to save FILEs' fds,
7402 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007403 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7404 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007405 * "fileno(fd) = new_fd" can't be done.
7406 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007407 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007408 return 0;
7409
Denys Vlasenko2db74612017-07-07 22:07:28 +02007410 /* If this one of script's fds? */
7411 if (save_FILEs_on_redirect(fd, avoid_fd))
7412 return 1; /* yes. "we closed fd" */
7413
7414 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7415 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7416 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007417}
7418
Denys Vlasenko2db74612017-07-07 22:07:28 +02007419static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007420{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007421 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007422 int i;
7423 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007424 if (sq[i].moved_to >= 0) {
7425 /* We simply die on error */
7426 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7427 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7428 } else {
7429 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7430 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7431 close(sq[i].orig_fd);
7432 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007433 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007434 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007435 }
7436
Denys Vlasenko2db74612017-07-07 22:07:28 +02007437 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007438
7439 restore_redirected_FILEs();
7440}
7441
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007442#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007443static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007444{
7445 if (G_interactive_fd)
7446 close(G_interactive_fd);
7447 close_all_FILE_list();
7448}
7449#endif
7450
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007451static int internally_opened_fd(int fd, struct squirrel *sq)
7452{
7453 int i;
7454
7455#if ENABLE_HUSH_INTERACTIVE
7456 if (fd == G.interactive_fd)
7457 return 1;
7458#endif
7459 /* If this one of script's fds? */
7460 if (fd_in_FILEs(fd))
7461 return 1;
7462
7463 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7464 if (fd == sq[i].moved_to)
7465 return 1;
7466 }
7467 return 0;
7468}
7469
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007470/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7471 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007472static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007473{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007474 struct redir_struct *redir;
7475
7476 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007477 int newfd;
7478 int closed;
7479
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007480 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007481 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007482 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007483 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7484 * of the heredoc */
7485 debug_printf_parse("set heredoc '%s'\n",
7486 redir->rd_filename);
7487 setup_heredoc(redir);
7488 continue;
7489 }
7490
7491 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007492 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007493 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007494 int mode;
7495
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007496 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007497 /*
7498 * Examples:
7499 * "cmd >" (no filename)
7500 * "cmd > <file" (2nd redirect starts too early)
7501 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007502 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007503 continue;
7504 }
7505 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007506 p = expand_string_to_string(redir->rd_filename,
7507 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007508 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007509 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007510 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007511 /* Error message from open_or_warn can be lost
7512 * if stderr has been redirected, but bash
7513 * and ash both lose it as well
7514 * (though zsh doesn't!)
7515 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007516 return 1;
7517 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007518 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007519 /* open() gave us precisely the fd we wanted.
7520 * This means that this fd was not busy
7521 * (not opened to anywhere).
7522 * Remember to close it on restore:
7523 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007524 *sqp = add_squirrel_closed(*sqp, newfd);
7525 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007526 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007527 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007528 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7529 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007530 }
7531
Denys Vlasenko657e9002017-07-30 23:34:04 +02007532 if (newfd == redir->rd_fd)
7533 continue;
7534
7535 /* if "N>FILE": move newfd to redir->rd_fd */
7536 /* if "N>&M": dup newfd to redir->rd_fd */
7537 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7538
7539 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7540 if (newfd == REDIRFD_CLOSE) {
7541 /* "N>&-" means "close me" */
7542 if (!closed) {
7543 /* ^^^ optimization: saving may already
7544 * have closed it. If not... */
7545 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007546 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007547 /* Sometimes we do another close on restore, getting EBADF.
7548 * Consider "echo 3>FILE 3>&-"
7549 * first redirect remembers "need to close 3",
7550 * and second redirect closes 3! Restore code then closes 3 again.
7551 */
7552 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007553 /* if newfd is a script fd or saved fd, simulate EBADF */
7554 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7555 //errno = EBADF;
7556 //bb_perror_msg_and_die("can't duplicate file descriptor");
7557 newfd = -1; /* same effect as code above */
7558 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007559 xdup2(newfd, redir->rd_fd);
7560 if (redir->rd_dup == REDIRFD_TO_FILE)
7561 /* "rd_fd > FILE" */
7562 close(newfd);
7563 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007564 }
7565 }
7566 return 0;
7567}
7568
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007569static char *find_in_path(const char *arg)
7570{
7571 char *ret = NULL;
7572 const char *PATH = get_local_var_value("PATH");
7573
7574 if (!PATH)
7575 return NULL;
7576
7577 while (1) {
7578 const char *end = strchrnul(PATH, ':');
7579 int sz = end - PATH; /* must be int! */
7580
7581 free(ret);
7582 if (sz != 0) {
7583 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7584 } else {
7585 /* We have xxx::yyyy in $PATH,
7586 * it means "use current dir" */
7587 ret = xstrdup(arg);
7588 }
7589 if (access(ret, F_OK) == 0)
7590 break;
7591
7592 if (*end == '\0') {
7593 free(ret);
7594 return NULL;
7595 }
7596 PATH = end + 1;
7597 }
7598
7599 return ret;
7600}
7601
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007602static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007603 const struct built_in_command *x,
7604 const struct built_in_command *end)
7605{
7606 while (x != end) {
7607 if (strcmp(name, x->b_cmd) != 0) {
7608 x++;
7609 continue;
7610 }
7611 debug_printf_exec("found builtin '%s'\n", name);
7612 return x;
7613 }
7614 return NULL;
7615}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007616static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007617{
7618 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7619}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007620static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007621{
7622 const struct built_in_command *x = find_builtin1(name);
7623 if (x)
7624 return x;
7625 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7626}
7627
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007628static void remove_nested_vars(void)
7629{
7630 struct variable *cur;
7631 struct variable **cur_pp;
7632
7633 cur_pp = &G.top_var;
7634 while ((cur = *cur_pp) != NULL) {
7635 if (cur->var_nest_level <= G.var_nest_level) {
7636 cur_pp = &cur->next;
7637 continue;
7638 }
7639 /* Unexport */
7640 if (cur->flg_export) {
7641 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7642 bb_unsetenv(cur->varstr);
7643 }
7644 /* Remove from global list */
7645 *cur_pp = cur->next;
7646 /* Free */
7647 if (!cur->max_len) {
7648 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7649 free(cur->varstr);
7650 }
7651 free(cur);
7652 }
7653}
7654
7655static void enter_var_nest_level(void)
7656{
7657 G.var_nest_level++;
7658 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7659
7660 /* Try: f() { echo -n .; f; }; f
7661 * struct variable::var_nest_level is uint16_t,
7662 * thus limiting recursion to < 2^16.
7663 * In any case, with 8 Mbyte stack SEGV happens
7664 * not too long after 2^16 recursions anyway.
7665 */
7666 if (G.var_nest_level > 0xff00)
7667 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7668}
7669
7670static void leave_var_nest_level(void)
7671{
7672 G.var_nest_level--;
7673 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7674 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7675 bb_error_msg_and_die("BUG: nesting underflow");
7676
7677 remove_nested_vars();
7678}
7679
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007680#if ENABLE_HUSH_FUNCTIONS
7681static struct function **find_function_slot(const char *name)
7682{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007683 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007684 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007685
7686 while ((funcp = *funcpp) != NULL) {
7687 if (strcmp(name, funcp->name) == 0) {
7688 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007689 break;
7690 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007691 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007692 }
7693 return funcpp;
7694}
7695
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007696static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007697{
7698 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007699 return funcp;
7700}
7701
7702/* Note: takes ownership on name ptr */
7703static struct function *new_function(char *name)
7704{
7705 struct function **funcpp = find_function_slot(name);
7706 struct function *funcp = *funcpp;
7707
7708 if (funcp != NULL) {
7709 struct command *cmd = funcp->parent_cmd;
7710 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7711 if (!cmd) {
7712 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7713 free(funcp->name);
7714 /* Note: if !funcp->body, do not free body_as_string!
7715 * This is a special case of "-F name body" function:
7716 * body_as_string was not malloced! */
7717 if (funcp->body) {
7718 free_pipe_list(funcp->body);
7719# if !BB_MMU
7720 free(funcp->body_as_string);
7721# endif
7722 }
7723 } else {
7724 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7725 cmd->argv[0] = funcp->name;
7726 cmd->group = funcp->body;
7727# if !BB_MMU
7728 cmd->group_as_string = funcp->body_as_string;
7729# endif
7730 }
7731 } else {
7732 debug_printf_exec("remembering new function '%s'\n", name);
7733 funcp = *funcpp = xzalloc(sizeof(*funcp));
7734 /*funcp->next = NULL;*/
7735 }
7736
7737 funcp->name = name;
7738 return funcp;
7739}
7740
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007741# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007742static void unset_func(const char *name)
7743{
7744 struct function **funcpp = find_function_slot(name);
7745 struct function *funcp = *funcpp;
7746
7747 if (funcp != NULL) {
7748 debug_printf_exec("freeing function '%s'\n", funcp->name);
7749 *funcpp = funcp->next;
7750 /* funcp is unlinked now, deleting it.
7751 * Note: if !funcp->body, the function was created by
7752 * "-F name body", do not free ->body_as_string
7753 * and ->name as they were not malloced. */
7754 if (funcp->body) {
7755 free_pipe_list(funcp->body);
7756 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007757# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007758 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007759# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007760 }
7761 free(funcp);
7762 }
7763}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007764# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007765
7766# if BB_MMU
7767#define exec_function(to_free, funcp, argv) \
7768 exec_function(funcp, argv)
7769# endif
7770static void exec_function(char ***to_free,
7771 const struct function *funcp,
7772 char **argv) NORETURN;
7773static void exec_function(char ***to_free,
7774 const struct function *funcp,
7775 char **argv)
7776{
7777# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007778 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007779
7780 argv[0] = G.global_argv[0];
7781 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007782 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007783
7784// Example when we are here: "cmd | func"
7785// func will run with saved-redirect fds open.
7786// $ f() { echo /proc/self/fd/*; }
7787// $ true | f
7788// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7789// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7790// Same in script:
7791// $ . ./SCRIPT
7792// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7793// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7794// They are CLOEXEC so external programs won't see them, but
7795// for "more correctness" we might want to close those extra fds here:
7796//? close_saved_fds_and_FILE_fds();
7797
Denys Vlasenko332e4112018-04-04 22:32:59 +02007798 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007799 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007800 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007801 IF_HUSH_LOCAL(G.func_nest_level++;)
7802
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007803 /* On MMU, funcp->body is always non-NULL */
7804 n = run_list(funcp->body);
7805 fflush_all();
7806 _exit(n);
7807# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007808//? close_saved_fds_and_FILE_fds();
7809
7810//TODO: check whether "true | func_with_return" works
7811
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007812 re_execute_shell(to_free,
7813 funcp->body_as_string,
7814 G.global_argv[0],
7815 argv + 1,
7816 NULL);
7817# endif
7818}
7819
7820static int run_function(const struct function *funcp, char **argv)
7821{
7822 int rc;
7823 save_arg_t sv;
7824 smallint sv_flg;
7825
7826 save_and_replace_G_args(&sv, argv);
7827
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007828 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007829 sv_flg = G_flag_return_in_progress;
7830 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007831
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007832 /* Make "local" variables properly shadow previous ones */
7833 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007834 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007835
7836 /* On MMU, funcp->body is always non-NULL */
7837# if !BB_MMU
7838 if (!funcp->body) {
7839 /* Function defined by -F */
7840 parse_and_run_string(funcp->body_as_string);
7841 rc = G.last_exitcode;
7842 } else
7843# endif
7844 {
7845 rc = run_list(funcp->body);
7846 }
7847
Denys Vlasenko332e4112018-04-04 22:32:59 +02007848 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007849 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007850
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007851 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007852
7853 restore_G_args(&sv, argv);
7854
7855 return rc;
7856}
7857#endif /* ENABLE_HUSH_FUNCTIONS */
7858
7859
7860#if BB_MMU
7861#define exec_builtin(to_free, x, argv) \
7862 exec_builtin(x, argv)
7863#else
7864#define exec_builtin(to_free, x, argv) \
7865 exec_builtin(to_free, argv)
7866#endif
7867static void exec_builtin(char ***to_free,
7868 const struct built_in_command *x,
7869 char **argv) NORETURN;
7870static void exec_builtin(char ***to_free,
7871 const struct built_in_command *x,
7872 char **argv)
7873{
7874#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007875 int rcode;
7876 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007877//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007878 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007879 fflush_all();
7880 _exit(rcode);
7881#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007882 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007883 /* On NOMMU, we must never block!
7884 * Example: { sleep 99 | read line; } & echo Ok
7885 */
7886 re_execute_shell(to_free,
7887 argv[0],
7888 G.global_argv[0],
7889 G.global_argv + 1,
7890 argv);
7891#endif
7892}
7893
7894
7895static void execvp_or_die(char **argv) NORETURN;
7896static void execvp_or_die(char **argv)
7897{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007898 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007899 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007900 /* Don't propagate SIG_IGN to the child */
7901 if (SPECIAL_JOBSTOP_SIGS != 0)
7902 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007903 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007904 e = 2;
7905 if (errno == EACCES) e = 126;
7906 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007907 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007908 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007909}
7910
7911#if ENABLE_HUSH_MODE_X
7912static void dump_cmd_in_x_mode(char **argv)
7913{
7914 if (G_x_mode && argv) {
7915 /* We want to output the line in one write op */
7916 char *buf, *p;
7917 int len;
7918 int n;
7919
7920 len = 3;
7921 n = 0;
7922 while (argv[n])
7923 len += strlen(argv[n++]) + 1;
7924 buf = xmalloc(len);
7925 buf[0] = '+';
7926 p = buf + 1;
7927 n = 0;
7928 while (argv[n])
7929 p += sprintf(p, " %s", argv[n++]);
7930 *p++ = '\n';
7931 *p = '\0';
7932 fputs(buf, stderr);
7933 free(buf);
7934 }
7935}
7936#else
7937# define dump_cmd_in_x_mode(argv) ((void)0)
7938#endif
7939
Denys Vlasenko57000292018-01-12 14:41:45 +01007940#if ENABLE_HUSH_COMMAND
7941static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7942{
7943 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007944
Denys Vlasenko57000292018-01-12 14:41:45 +01007945 if (!opt_vV)
7946 return;
7947
7948 to_free = NULL;
7949 if (!explanation) {
7950 char *path = getenv("PATH");
7951 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007952 if (!explanation)
7953 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007954 if (opt_vV != 'V')
7955 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7956 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007957 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007958 free(to_free);
7959 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007960 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007961}
7962#else
7963# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7964#endif
7965
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007966#if BB_MMU
7967#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7968 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7969#define pseudo_exec(nommu_save, command, argv_expanded) \
7970 pseudo_exec(command, argv_expanded)
7971#endif
7972
7973/* Called after [v]fork() in run_pipe, or from builtin_exec.
7974 * Never returns.
7975 * Don't exit() here. If you don't exec, use _exit instead.
7976 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007977 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007978 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007979static void pseudo_exec_argv(nommu_save_t *nommu_save,
7980 char **argv, int assignment_cnt,
7981 char **argv_expanded) NORETURN;
7982static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7983 char **argv, int assignment_cnt,
7984 char **argv_expanded)
7985{
Denys Vlasenko57000292018-01-12 14:41:45 +01007986 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007987 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007988 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007989 IF_HUSH_COMMAND(char opt_vV = 0;)
7990 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007991
7992 new_env = expand_assignments(argv, assignment_cnt);
7993 dump_cmd_in_x_mode(new_env);
7994
7995 if (!argv[assignment_cnt]) {
7996 /* Case when we are here: ... | var=val | ...
7997 * (note that we do not exit early, i.e., do not optimize out
7998 * expand_assignments(): think about ... | var=`sleep 1` | ...
7999 */
8000 free_strings(new_env);
8001 _exit(EXIT_SUCCESS);
8002 }
8003
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008004 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008005#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008006 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008007#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008008 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008009 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008010#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008011 set_vars_and_save_old(new_env);
8012 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008013
8014 if (argv_expanded) {
8015 argv = argv_expanded;
8016 } else {
8017 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8018#if !BB_MMU
8019 nommu_save->argv = argv;
8020#endif
8021 }
8022 dump_cmd_in_x_mode(argv);
8023
8024#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8025 if (strchr(argv[0], '/') != NULL)
8026 goto skip;
8027#endif
8028
Denys Vlasenko75481d32017-07-31 05:27:09 +02008029#if ENABLE_HUSH_FUNCTIONS
8030 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008031 funcp = find_function(argv[0]);
8032 if (funcp)
8033 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008034#endif
8035
Denys Vlasenko57000292018-01-12 14:41:45 +01008036#if ENABLE_HUSH_COMMAND
8037 /* "command BAR": run BAR without looking it up among functions
8038 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8039 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8040 */
8041 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8042 char *p;
8043
8044 argv++;
8045 p = *argv;
8046 if (p[0] != '-' || !p[1])
8047 continue; /* bash allows "command command command [-OPT] BAR" */
8048
8049 for (;;) {
8050 p++;
8051 switch (*p) {
8052 case '\0':
8053 argv++;
8054 p = *argv;
8055 if (p[0] != '-' || !p[1])
8056 goto after_opts;
8057 continue; /* next arg is also -opts, process it too */
8058 case 'v':
8059 case 'V':
8060 opt_vV = *p;
8061 continue;
8062 default:
8063 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8064 }
8065 }
8066 }
8067 after_opts:
8068# if ENABLE_HUSH_FUNCTIONS
8069 if (opt_vV && find_function(argv[0]))
8070 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8071# endif
8072#endif
8073
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008074 /* Check if the command matches any of the builtins.
8075 * Depending on context, this might be redundant. But it's
8076 * easier to waste a few CPU cycles than it is to figure out
8077 * if this is one of those cases.
8078 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008079 /* Why "BB_MMU ? :" difference in logic? -
8080 * On NOMMU, it is more expensive to re-execute shell
8081 * just in order to run echo or test builtin.
8082 * It's better to skip it here and run corresponding
8083 * non-builtin later. */
8084 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8085 if (x) {
8086 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8087 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008088 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008089
8090#if ENABLE_FEATURE_SH_STANDALONE
8091 /* Check if the command matches any busybox applets */
8092 {
8093 int a = find_applet_by_name(argv[0]);
8094 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008095 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008096# if BB_MMU /* see above why on NOMMU it is not allowed */
8097 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008098 /* Do not leak open fds from opened script files etc.
8099 * Testcase: interactive "ls -l /proc/self/fd"
8100 * should not show tty fd open.
8101 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008102 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008103//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008104//This casuses test failures in
8105//redir_children_should_not_see_saved_fd_2.tests
8106//redir_children_should_not_see_saved_fd_3.tests
8107//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008108 /* Without this, "rm -i FILE" can't be ^C'ed: */
8109 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008110 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008111 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008112 }
8113# endif
8114 /* Re-exec ourselves */
8115 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008116 /* Don't propagate SIG_IGN to the child */
8117 if (SPECIAL_JOBSTOP_SIGS != 0)
8118 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008119 execv(bb_busybox_exec_path, argv);
8120 /* If they called chroot or otherwise made the binary no longer
8121 * executable, fall through */
8122 }
8123 }
8124#endif
8125
8126#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8127 skip:
8128#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008129 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008130 execvp_or_die(argv);
8131}
8132
8133/* Called after [v]fork() in run_pipe
8134 */
8135static void pseudo_exec(nommu_save_t *nommu_save,
8136 struct command *command,
8137 char **argv_expanded) NORETURN;
8138static void pseudo_exec(nommu_save_t *nommu_save,
8139 struct command *command,
8140 char **argv_expanded)
8141{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008142#if ENABLE_HUSH_FUNCTIONS
8143 if (command->cmd_type == CMD_FUNCDEF) {
8144 /* Ignore funcdefs in pipes:
8145 * true | f() { cmd }
8146 */
8147 _exit(0);
8148 }
8149#endif
8150
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008151 if (command->argv) {
8152 pseudo_exec_argv(nommu_save, command->argv,
8153 command->assignment_cnt, argv_expanded);
8154 }
8155
8156 if (command->group) {
8157 /* Cases when we are here:
8158 * ( list )
8159 * { list } &
8160 * ... | ( list ) | ...
8161 * ... | { list } | ...
8162 */
8163#if BB_MMU
8164 int rcode;
8165 debug_printf_exec("pseudo_exec: run_list\n");
8166 reset_traps_to_defaults();
8167 rcode = run_list(command->group);
8168 /* OK to leak memory by not calling free_pipe_list,
8169 * since this process is about to exit */
8170 _exit(rcode);
8171#else
8172 re_execute_shell(&nommu_save->argv_from_re_execing,
8173 command->group_as_string,
8174 G.global_argv[0],
8175 G.global_argv + 1,
8176 NULL);
8177#endif
8178 }
8179
8180 /* Case when we are here: ... | >file */
8181 debug_printf_exec("pseudo_exec'ed null command\n");
8182 _exit(EXIT_SUCCESS);
8183}
8184
8185#if ENABLE_HUSH_JOB
8186static const char *get_cmdtext(struct pipe *pi)
8187{
8188 char **argv;
8189 char *p;
8190 int len;
8191
8192 /* This is subtle. ->cmdtext is created only on first backgrounding.
8193 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8194 * On subsequent bg argv is trashed, but we won't use it */
8195 if (pi->cmdtext)
8196 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008197
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008198 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008199 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008200 pi->cmdtext = xzalloc(1);
8201 return pi->cmdtext;
8202 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008203 len = 0;
8204 do {
8205 len += strlen(*argv) + 1;
8206 } while (*++argv);
8207 p = xmalloc(len);
8208 pi->cmdtext = p;
8209 argv = pi->cmds[0].argv;
8210 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008211 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008212 *p++ = ' ';
8213 } while (*++argv);
8214 p[-1] = '\0';
8215 return pi->cmdtext;
8216}
8217
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008218static void remove_job_from_table(struct pipe *pi)
8219{
8220 struct pipe *prev_pipe;
8221
8222 if (pi == G.job_list) {
8223 G.job_list = pi->next;
8224 } else {
8225 prev_pipe = G.job_list;
8226 while (prev_pipe->next != pi)
8227 prev_pipe = prev_pipe->next;
8228 prev_pipe->next = pi->next;
8229 }
8230 G.last_jobid = 0;
8231 if (G.job_list)
8232 G.last_jobid = G.job_list->jobid;
8233}
8234
8235static void delete_finished_job(struct pipe *pi)
8236{
8237 remove_job_from_table(pi);
8238 free_pipe(pi);
8239}
8240
8241static void clean_up_last_dead_job(void)
8242{
8243 if (G.job_list && !G.job_list->alive_cmds)
8244 delete_finished_job(G.job_list);
8245}
8246
Denys Vlasenko16096292017-07-10 10:00:28 +02008247static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008248{
8249 struct pipe *job, **jobp;
8250 int i;
8251
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008252 clean_up_last_dead_job();
8253
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008254 /* Find the end of the list, and find next job ID to use */
8255 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008256 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008257 while ((job = *jobp) != NULL) {
8258 if (job->jobid > i)
8259 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008260 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008261 }
8262 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008263
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008264 /* Create a new job struct at the end */
8265 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008266 job->next = NULL;
8267 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8268 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8269 for (i = 0; i < pi->num_cmds; i++) {
8270 job->cmds[i].pid = pi->cmds[i].pid;
8271 /* all other fields are not used and stay zero */
8272 }
8273 job->cmdtext = xstrdup(get_cmdtext(pi));
8274
8275 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008276 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008277 G.last_jobid = job->jobid;
8278}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008279#endif /* JOB */
8280
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008281static int job_exited_or_stopped(struct pipe *pi)
8282{
8283 int rcode, i;
8284
8285 if (pi->alive_cmds != pi->stopped_cmds)
8286 return -1;
8287
8288 /* All processes in fg pipe have exited or stopped */
8289 rcode = 0;
8290 i = pi->num_cmds;
8291 while (--i >= 0) {
8292 rcode = pi->cmds[i].cmd_exitcode;
8293 /* usually last process gives overall exitstatus,
8294 * but with "set -o pipefail", last *failed* process does */
8295 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8296 break;
8297 }
8298 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8299 return rcode;
8300}
8301
Denys Vlasenko7e675362016-10-28 21:57:31 +02008302static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008303{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008304#if ENABLE_HUSH_JOB
8305 struct pipe *pi;
8306#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008307 int i, dead;
8308
8309 dead = WIFEXITED(status) || WIFSIGNALED(status);
8310
8311#if DEBUG_JOBS
8312 if (WIFSTOPPED(status))
8313 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8314 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8315 if (WIFSIGNALED(status))
8316 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8317 childpid, WTERMSIG(status), WEXITSTATUS(status));
8318 if (WIFEXITED(status))
8319 debug_printf_jobs("pid %d exited, exitcode %d\n",
8320 childpid, WEXITSTATUS(status));
8321#endif
8322 /* Were we asked to wait for a fg pipe? */
8323 if (fg_pipe) {
8324 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008325
Denys Vlasenko7e675362016-10-28 21:57:31 +02008326 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008327 int rcode;
8328
Denys Vlasenko7e675362016-10-28 21:57:31 +02008329 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8330 if (fg_pipe->cmds[i].pid != childpid)
8331 continue;
8332 if (dead) {
8333 int ex;
8334 fg_pipe->cmds[i].pid = 0;
8335 fg_pipe->alive_cmds--;
8336 ex = WEXITSTATUS(status);
8337 /* bash prints killer signal's name for *last*
8338 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8339 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8340 */
8341 if (WIFSIGNALED(status)) {
8342 int sig = WTERMSIG(status);
8343 if (i == fg_pipe->num_cmds-1)
8344 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8345 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8346 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8347 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8348 * Maybe we need to use sig | 128? */
8349 ex = sig + 128;
8350 }
8351 fg_pipe->cmds[i].cmd_exitcode = ex;
8352 } else {
8353 fg_pipe->stopped_cmds++;
8354 }
8355 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8356 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008357 rcode = job_exited_or_stopped(fg_pipe);
8358 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008359/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8360 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8361 * and "killall -STOP cat" */
8362 if (G_interactive_fd) {
8363#if ENABLE_HUSH_JOB
8364 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008365 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008366#endif
8367 return rcode;
8368 }
8369 if (fg_pipe->alive_cmds == 0)
8370 return rcode;
8371 }
8372 /* There are still running processes in the fg_pipe */
8373 return -1;
8374 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008375 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008376 }
8377
8378#if ENABLE_HUSH_JOB
8379 /* We were asked to wait for bg or orphaned children */
8380 /* No need to remember exitcode in this case */
8381 for (pi = G.job_list; pi; pi = pi->next) {
8382 for (i = 0; i < pi->num_cmds; i++) {
8383 if (pi->cmds[i].pid == childpid)
8384 goto found_pi_and_prognum;
8385 }
8386 }
8387 /* Happens when shell is used as init process (init=/bin/sh) */
8388 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8389 return -1; /* this wasn't a process from fg_pipe */
8390
8391 found_pi_and_prognum:
8392 if (dead) {
8393 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008394 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008395 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008396 rcode = 128 + WTERMSIG(status);
8397 pi->cmds[i].cmd_exitcode = rcode;
8398 if (G.last_bg_pid == pi->cmds[i].pid)
8399 G.last_bg_pid_exitcode = rcode;
8400 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008401 pi->alive_cmds--;
8402 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008403 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008404 printf(JOB_STATUS_FORMAT, pi->jobid,
8405 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008406 delete_finished_job(pi);
8407 } else {
8408/*
8409 * bash deletes finished jobs from job table only in interactive mode,
8410 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8411 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8412 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8413 * We only retain one "dead" job, if it's the single job on the list.
8414 * This covers most of real-world scenarios where this is useful.
8415 */
8416 if (pi != G.job_list)
8417 delete_finished_job(pi);
8418 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008419 }
8420 } else {
8421 /* child stopped */
8422 pi->stopped_cmds++;
8423 }
8424#endif
8425 return -1; /* this wasn't a process from fg_pipe */
8426}
8427
8428/* Check to see if any processes have exited -- if they have,
8429 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008430 *
8431 * If non-NULL fg_pipe: wait for its completion or stop.
8432 * Return its exitcode or zero if stopped.
8433 *
8434 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8435 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8436 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8437 * or 0 if no children changed status.
8438 *
8439 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8440 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8441 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008442 */
8443static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8444{
8445 int attributes;
8446 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008447 int rcode = 0;
8448
8449 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8450
8451 attributes = WUNTRACED;
8452 if (fg_pipe == NULL)
8453 attributes |= WNOHANG;
8454
8455 errno = 0;
8456#if ENABLE_HUSH_FAST
8457 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8458//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8459//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8460 /* There was neither fork nor SIGCHLD since last waitpid */
8461 /* Avoid doing waitpid syscall if possible */
8462 if (!G.we_have_children) {
8463 errno = ECHILD;
8464 return -1;
8465 }
8466 if (fg_pipe == NULL) { /* is WNOHANG set? */
8467 /* We have children, but they did not exit
8468 * or stop yet (we saw no SIGCHLD) */
8469 return 0;
8470 }
8471 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8472 }
8473#endif
8474
8475/* Do we do this right?
8476 * bash-3.00# sleep 20 | false
8477 * <ctrl-Z pressed>
8478 * [3]+ Stopped sleep 20 | false
8479 * bash-3.00# echo $?
8480 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8481 * [hush 1.14.0: yes we do it right]
8482 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008483 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008484 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008485#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008486 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008487 i = G.count_SIGCHLD;
8488#endif
8489 childpid = waitpid(-1, &status, attributes);
8490 if (childpid <= 0) {
8491 if (childpid && errno != ECHILD)
8492 bb_perror_msg("waitpid");
8493#if ENABLE_HUSH_FAST
8494 else { /* Until next SIGCHLD, waitpid's are useless */
8495 G.we_have_children = (childpid == 0);
8496 G.handled_SIGCHLD = i;
8497//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8498 }
8499#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008500 /* ECHILD (no children), or 0 (no change in children status) */
8501 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008502 break;
8503 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008504 rcode = process_wait_result(fg_pipe, childpid, status);
8505 if (rcode >= 0) {
8506 /* fg_pipe exited or stopped */
8507 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008508 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008509 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008510 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008511 rcode = WEXITSTATUS(status);
8512 if (WIFSIGNALED(status))
8513 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008514 if (WIFSTOPPED(status))
8515 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8516 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008517 rcode++;
8518 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008519 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008520 /* This wasn't one of our processes, or */
8521 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008522 } /* while (waitpid succeeds)... */
8523
8524 return rcode;
8525}
8526
8527#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008528static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008529{
8530 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008531 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008532 if (G_saved_tty_pgrp) {
8533 /* Job finished, move the shell to the foreground */
8534 p = getpgrp(); /* our process group id */
8535 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8536 tcsetpgrp(G_interactive_fd, p);
8537 }
8538 return rcode;
8539}
8540#endif
8541
8542/* Start all the jobs, but don't wait for anything to finish.
8543 * See checkjobs().
8544 *
8545 * Return code is normally -1, when the caller has to wait for children
8546 * to finish to determine the exit status of the pipe. If the pipe
8547 * is a simple builtin command, however, the action is done by the
8548 * time run_pipe returns, and the exit code is provided as the
8549 * return value.
8550 *
8551 * Returns -1 only if started some children. IOW: we have to
8552 * mask out retvals of builtins etc with 0xff!
8553 *
8554 * The only case when we do not need to [v]fork is when the pipe
8555 * is single, non-backgrounded, non-subshell command. Examples:
8556 * cmd ; ... { list } ; ...
8557 * cmd && ... { list } && ...
8558 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008559 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008560 * or (if SH_STANDALONE) an applet, and we can run the { list }
8561 * with run_list. If it isn't one of these, we fork and exec cmd.
8562 *
8563 * Cases when we must fork:
8564 * non-single: cmd | cmd
8565 * backgrounded: cmd & { list } &
8566 * subshell: ( list ) [&]
8567 */
8568#if !ENABLE_HUSH_MODE_X
Denys Vlasenkoc96bb2c2018-06-26 15:43:56 +02008569#define redirect_and_varexp_helper(command, squirrel, argv_expanded) \
8570 redirect_and_varexp_helper(command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008571#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008572static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008573 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008574 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008575 char **argv_expanded)
8576{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008577 /* Assignments occur before redirects. Try:
8578 * a=`sleep 1` sleep 2 3>/qwe/rty
8579 */
8580
8581 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8582 dump_cmd_in_x_mode(new_env);
8583 dump_cmd_in_x_mode(argv_expanded);
8584 /* this takes ownership of new_env[i] elements, and frees new_env: */
8585 set_vars_and_save_old(new_env);
8586
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008587 /* setup_redirects acts on file descriptors, not FILEs.
8588 * This is perfect for work that comes after exec().
8589 * Is it really safe for inline use? Experimentally,
8590 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008591 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008592}
8593static NOINLINE int run_pipe(struct pipe *pi)
8594{
8595 static const char *const null_ptr = NULL;
8596
8597 int cmd_no;
8598 int next_infd;
8599 struct command *command;
8600 char **argv_expanded;
8601 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008602 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008603 int rcode;
8604
8605 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8606 debug_enter();
8607
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008608 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8609 * Result should be 3 lines: q w e, qwe, q w e
8610 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008611 if (G.ifs_whitespace != G.ifs)
8612 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008613 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008614 if (G.ifs) {
8615 char *p;
8616 G.ifs_whitespace = (char*)G.ifs;
8617 p = skip_whitespace(G.ifs);
8618 if (*p) {
8619 /* Not all $IFS is whitespace */
8620 char *d;
8621 int len = p - G.ifs;
8622 p = skip_non_whitespace(p);
8623 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8624 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8625 while (*p) {
8626 if (isspace(*p))
8627 *d++ = *p;
8628 p++;
8629 }
8630 *d = '\0';
8631 }
8632 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008633 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008634 G.ifs_whitespace = (char*)G.ifs;
8635 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008636
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008637 IF_HUSH_JOB(pi->pgrp = -1;)
8638 pi->stopped_cmds = 0;
8639 command = &pi->cmds[0];
8640 argv_expanded = NULL;
8641
8642 if (pi->num_cmds != 1
8643 || pi->followup == PIPE_BG
8644 || command->cmd_type == CMD_SUBSHELL
8645 ) {
8646 goto must_fork;
8647 }
8648
8649 pi->alive_cmds = 1;
8650
8651 debug_printf_exec(": group:%p argv:'%s'\n",
8652 command->group, command->argv ? command->argv[0] : "NONE");
8653
8654 if (command->group) {
8655#if ENABLE_HUSH_FUNCTIONS
8656 if (command->cmd_type == CMD_FUNCDEF) {
8657 /* "executing" func () { list } */
8658 struct function *funcp;
8659
8660 funcp = new_function(command->argv[0]);
8661 /* funcp->name is already set to argv[0] */
8662 funcp->body = command->group;
8663# if !BB_MMU
8664 funcp->body_as_string = command->group_as_string;
8665 command->group_as_string = NULL;
8666# endif
8667 command->group = NULL;
8668 command->argv[0] = NULL;
8669 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8670 funcp->parent_cmd = command;
8671 command->child_func = funcp;
8672
8673 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8674 debug_leave();
8675 return EXIT_SUCCESS;
8676 }
8677#endif
8678 /* { list } */
8679 debug_printf("non-subshell group\n");
8680 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008681 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008682 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008683//FIXME: we need to pass squirrel down into run_list()
8684//for SH_STANDALONE case, or else this construct:
8685// { find /proc/self/fd; true; } >FILE; cmd2
8686//has no way of closing saved fd#1 for "find",
8687//and in SH_STANDALONE mode, "find" is not execed,
8688//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008689 rcode = run_list(command->group) & 0xff;
8690 }
8691 restore_redirects(squirrel);
8692 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8693 debug_leave();
8694 debug_printf_exec("run_pipe: return %d\n", rcode);
8695 return rcode;
8696 }
8697
8698 argv = command->argv ? command->argv : (char **) &null_ptr;
8699 {
8700 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008701 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8702 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008703 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008704 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008705
Denys Vlasenko5807e182018-02-08 19:19:04 +01008706#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008707 if (G.lineno_var)
8708 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8709#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008710
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008711 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008712 /* Assignments, but no command.
8713 * Ensure redirects take effect (that is, create files).
8714 * Try "a=t >file"
8715 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008716 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008717 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008718 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008719 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008720 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008721
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008722 /* Set shell variables */
8723 if (G_x_mode)
8724 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008725 i = 0;
8726 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008727 char *p = expand_string_to_string(argv[i],
8728 EXP_FLAG_ESC_GLOB_CHARS,
8729 /*unbackslash:*/ 1
8730 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008731 if (G_x_mode)
8732 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008733 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008734 if (set_local_var(p, /*flag:*/ 0)) {
8735 /* assignment to readonly var / putenv error? */
8736 rcode = 1;
8737 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008738 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008739 }
8740 if (G_x_mode)
8741 bb_putchar_stderr('\n');
8742 /* Redirect error sets $? to 1. Otherwise,
8743 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008744 * Else, clear $?:
8745 * false; q=`exit 2`; echo $? - should print 2
8746 * false; x=1; echo $? - should print 0
8747 * Because of the 2nd case, we can't just use G.last_exitcode.
8748 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008749 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008750 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008751 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8752 debug_leave();
8753 debug_printf_exec("run_pipe: return %d\n", rcode);
8754 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008755 }
8756
8757 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008758#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008759 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008760 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008761 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008762#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008763 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008764
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008765 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008766 if (!argv_expanded[0]) {
8767 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008768 /* `false` still has to set exitcode 1 */
8769 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008770 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008771 }
8772
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008773 old_vars = NULL;
8774 sv_shadowed = G.shadowed_vars_pp;
8775
Denys Vlasenko75481d32017-07-31 05:27:09 +02008776 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008777 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8778 IF_HUSH_FUNCTIONS(x = NULL;)
8779 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008780 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008781 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008782 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8783 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008784 /*
8785 * Variable assignments are executed, but then "forgotten":
8786 * a=`sleep 1;echo A` exec 3>&-; echo $a
8787 * sleeps, but prints nothing.
8788 */
8789 enter_var_nest_level();
8790 G.shadowed_vars_pp = &old_vars;
8791 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8792 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008793 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008794
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008795 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008796 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008797
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008798 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008799 * a=b true; env | grep ^a=
8800 */
8801 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008802 /* Collect all variables "shadowed" by helper
8803 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8804 * into old_vars list:
8805 */
8806 G.shadowed_vars_pp = &old_vars;
8807 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008808 if (rcode == 0) {
8809 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008810 /* Do not collect *to old_vars list* vars shadowed
8811 * by e.g. "local VAR" builtin (collect them
8812 * in the previously nested list instead):
8813 * don't want them to be restored immediately
8814 * after "local" completes.
8815 */
8816 G.shadowed_vars_pp = sv_shadowed;
8817
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008818 debug_printf_exec(": builtin '%s' '%s'...\n",
8819 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008820 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008821 rcode = x->b_function(argv_expanded) & 0xff;
8822 fflush_all();
8823 }
8824#if ENABLE_HUSH_FUNCTIONS
8825 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008826 debug_printf_exec(": function '%s' '%s'...\n",
8827 funcp->name, argv_expanded[1]);
8828 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008829 /*
8830 * But do collect *to old_vars list* vars shadowed
8831 * within function execution. To that end, restore
8832 * this pointer _after_ function run:
8833 */
8834 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008835 }
8836#endif
8837 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008838 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008839 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008840 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008841 if (n < 0 || !APPLET_IS_NOFORK(n))
8842 goto must_fork;
8843
8844 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008845 /* Collect all variables "shadowed" by helper into old_vars list */
8846 G.shadowed_vars_pp = &old_vars;
8847 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8848 G.shadowed_vars_pp = sv_shadowed;
8849
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008850 if (rcode == 0) {
8851 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8852 argv_expanded[0], argv_expanded[1]);
8853 /*
8854 * Note: signals (^C) can't interrupt here.
8855 * We remember them and they will be acted upon
8856 * after applet returns.
8857 * This makes applets which can run for a long time
8858 * and/or wait for user input ineligible for NOFORK:
8859 * for example, "yes" or "rm" (rm -i waits for input).
8860 */
8861 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008862 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008863 } else
8864 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008865
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008866 restore_redirects(squirrel);
8867 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008868 leave_var_nest_level();
8869 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008870
8871 /*
8872 * Try "usleep 99999999" + ^C + "echo $?"
8873 * with FEATURE_SH_NOFORK=y.
8874 */
8875 if (!funcp) {
8876 /* It was builtin or nofork.
8877 * if this would be a real fork/execed program,
8878 * it should have died if a fatal sig was received.
8879 * But OTOH, there was no separate process,
8880 * the sig was sent to _shell_, not to non-existing
8881 * child.
8882 * Let's just handle ^C only, this one is obvious:
8883 * we aren't ok with exitcode 0 when ^C was pressed
8884 * during builtin/nofork.
8885 */
8886 if (sigismember(&G.pending_set, SIGINT))
8887 rcode = 128 + SIGINT;
8888 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008889 free(argv_expanded);
8890 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8891 debug_leave();
8892 debug_printf_exec("run_pipe return %d\n", rcode);
8893 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008894 }
8895
8896 must_fork:
8897 /* NB: argv_expanded may already be created, and that
8898 * might include `cmd` runs! Do not rerun it! We *must*
8899 * use argv_expanded if it's non-NULL */
8900
8901 /* Going to fork a child per each pipe member */
8902 pi->alive_cmds = 0;
8903 next_infd = 0;
8904
8905 cmd_no = 0;
8906 while (cmd_no < pi->num_cmds) {
8907 struct fd_pair pipefds;
8908#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008909 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008910 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008911 nommu_save.old_vars = NULL;
8912 nommu_save.argv = NULL;
8913 nommu_save.argv_from_re_execing = NULL;
8914#endif
8915 command = &pi->cmds[cmd_no];
8916 cmd_no++;
8917 if (command->argv) {
8918 debug_printf_exec(": pipe member '%s' '%s'...\n",
8919 command->argv[0], command->argv[1]);
8920 } else {
8921 debug_printf_exec(": pipe member with no argv\n");
8922 }
8923
8924 /* pipes are inserted between pairs of commands */
8925 pipefds.rd = 0;
8926 pipefds.wr = 1;
8927 if (cmd_no < pi->num_cmds)
8928 xpiped_pair(pipefds);
8929
Denys Vlasenko5807e182018-02-08 19:19:04 +01008930#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008931 if (G.lineno_var)
8932 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8933#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008934
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008935 command->pid = BB_MMU ? fork() : vfork();
8936 if (!command->pid) { /* child */
8937#if ENABLE_HUSH_JOB
8938 disable_restore_tty_pgrp_on_exit();
8939 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8940
8941 /* Every child adds itself to new process group
8942 * with pgid == pid_of_first_child_in_pipe */
8943 if (G.run_list_level == 1 && G_interactive_fd) {
8944 pid_t pgrp;
8945 pgrp = pi->pgrp;
8946 if (pgrp < 0) /* true for 1st process only */
8947 pgrp = getpid();
8948 if (setpgid(0, pgrp) == 0
8949 && pi->followup != PIPE_BG
8950 && G_saved_tty_pgrp /* we have ctty */
8951 ) {
8952 /* We do it in *every* child, not just first,
8953 * to avoid races */
8954 tcsetpgrp(G_interactive_fd, pgrp);
8955 }
8956 }
8957#endif
8958 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8959 /* 1st cmd in backgrounded pipe
8960 * should have its stdin /dev/null'ed */
8961 close(0);
8962 if (open(bb_dev_null, O_RDONLY))
8963 xopen("/", O_RDONLY);
8964 } else {
8965 xmove_fd(next_infd, 0);
8966 }
8967 xmove_fd(pipefds.wr, 1);
8968 if (pipefds.rd > 1)
8969 close(pipefds.rd);
8970 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008971 * and the pipe fd (fd#1) is available for dup'ing:
8972 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8973 * of cmd1 goes into pipe.
8974 */
8975 if (setup_redirects(command, NULL)) {
8976 /* Happens when redir file can't be opened:
8977 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8978 * FOO
8979 * hush: can't open '/qwe/rty': No such file or directory
8980 * BAZ
8981 * (echo BAR is not executed, it hits _exit(1) below)
8982 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008983 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008984 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008985
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008986 /* Stores to nommu_save list of env vars putenv'ed
8987 * (NOMMU, on MMU we don't need that) */
8988 /* cast away volatility... */
8989 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8990 /* pseudo_exec() does not return */
8991 }
8992
8993 /* parent or error */
8994#if ENABLE_HUSH_FAST
8995 G.count_SIGCHLD++;
8996//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8997#endif
8998 enable_restore_tty_pgrp_on_exit();
8999#if !BB_MMU
9000 /* Clean up after vforked child */
9001 free(nommu_save.argv);
9002 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009003 G.var_nest_level = sv_var_nest_level;
9004 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009005 add_vars(nommu_save.old_vars);
9006#endif
9007 free(argv_expanded);
9008 argv_expanded = NULL;
9009 if (command->pid < 0) { /* [v]fork failed */
9010 /* Clearly indicate, was it fork or vfork */
9011 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9012 } else {
9013 pi->alive_cmds++;
9014#if ENABLE_HUSH_JOB
9015 /* Second and next children need to know pid of first one */
9016 if (pi->pgrp < 0)
9017 pi->pgrp = command->pid;
9018#endif
9019 }
9020
9021 if (cmd_no > 1)
9022 close(next_infd);
9023 if (cmd_no < pi->num_cmds)
9024 close(pipefds.wr);
9025 /* Pass read (output) pipe end to next iteration */
9026 next_infd = pipefds.rd;
9027 }
9028
9029 if (!pi->alive_cmds) {
9030 debug_leave();
9031 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9032 return 1;
9033 }
9034
9035 debug_leave();
9036 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9037 return -1;
9038}
9039
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009040/* NB: called by pseudo_exec, and therefore must not modify any
9041 * global data until exec/_exit (we can be a child after vfork!) */
9042static int run_list(struct pipe *pi)
9043{
9044#if ENABLE_HUSH_CASE
9045 char *case_word = NULL;
9046#endif
9047#if ENABLE_HUSH_LOOPS
9048 struct pipe *loop_top = NULL;
9049 char **for_lcur = NULL;
9050 char **for_list = NULL;
9051#endif
9052 smallint last_followup;
9053 smalluint rcode;
9054#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9055 smalluint cond_code = 0;
9056#else
9057 enum { cond_code = 0 };
9058#endif
9059#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009060 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009061 smallint last_rword; /* ditto */
9062#endif
9063
9064 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9065 debug_enter();
9066
9067#if ENABLE_HUSH_LOOPS
9068 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009069 {
9070 struct pipe *cpipe;
9071 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9072 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9073 continue;
9074 /* current word is FOR or IN (BOLD in comments below) */
9075 if (cpipe->next == NULL) {
9076 syntax_error("malformed for");
9077 debug_leave();
9078 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9079 return 1;
9080 }
9081 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9082 if (cpipe->next->res_word == RES_DO)
9083 continue;
9084 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9085 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9086 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9087 ) {
9088 syntax_error("malformed for");
9089 debug_leave();
9090 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9091 return 1;
9092 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009093 }
9094 }
9095#endif
9096
9097 /* Past this point, all code paths should jump to ret: label
9098 * in order to return, no direct "return" statements please.
9099 * This helps to ensure that no memory is leaked. */
9100
9101#if ENABLE_HUSH_JOB
9102 G.run_list_level++;
9103#endif
9104
9105#if HAS_KEYWORDS
9106 rword = RES_NONE;
9107 last_rword = RES_XXXX;
9108#endif
9109 last_followup = PIPE_SEQ;
9110 rcode = G.last_exitcode;
9111
9112 /* Go through list of pipes, (maybe) executing them. */
9113 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009114 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009115 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009116
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009117 if (G.flag_SIGINT)
9118 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009119 if (G_flag_return_in_progress == 1)
9120 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009121
9122 IF_HAS_KEYWORDS(rword = pi->res_word;)
9123 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9124 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009125
9126 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009127 if (
9128#if ENABLE_HUSH_IF
9129 rword == RES_IF || rword == RES_ELIF ||
9130#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009131 pi->followup != PIPE_SEQ
9132 ) {
9133 G.errexit_depth++;
9134 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009135#if ENABLE_HUSH_LOOPS
9136 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9137 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9138 ) {
9139 /* start of a loop: remember where loop starts */
9140 loop_top = pi;
9141 G.depth_of_loop++;
9142 }
9143#endif
9144 /* Still in the same "if...", "then..." or "do..." branch? */
9145 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9146 if ((rcode == 0 && last_followup == PIPE_OR)
9147 || (rcode != 0 && last_followup == PIPE_AND)
9148 ) {
9149 /* It is "<true> || CMD" or "<false> && CMD"
9150 * and we should not execute CMD */
9151 debug_printf_exec("skipped cmd because of || or &&\n");
9152 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009153 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009154 }
9155 }
9156 last_followup = pi->followup;
9157 IF_HAS_KEYWORDS(last_rword = rword;)
9158#if ENABLE_HUSH_IF
9159 if (cond_code) {
9160 if (rword == RES_THEN) {
9161 /* if false; then ... fi has exitcode 0! */
9162 G.last_exitcode = rcode = EXIT_SUCCESS;
9163 /* "if <false> THEN cmd": skip cmd */
9164 continue;
9165 }
9166 } else {
9167 if (rword == RES_ELSE || rword == RES_ELIF) {
9168 /* "if <true> then ... ELSE/ELIF cmd":
9169 * skip cmd and all following ones */
9170 break;
9171 }
9172 }
9173#endif
9174#if ENABLE_HUSH_LOOPS
9175 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9176 if (!for_lcur) {
9177 /* first loop through for */
9178
9179 static const char encoded_dollar_at[] ALIGN1 = {
9180 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9181 }; /* encoded representation of "$@" */
9182 static const char *const encoded_dollar_at_argv[] = {
9183 encoded_dollar_at, NULL
9184 }; /* argv list with one element: "$@" */
9185 char **vals;
9186
9187 vals = (char**)encoded_dollar_at_argv;
9188 if (pi->next->res_word == RES_IN) {
9189 /* if no variable values after "in" we skip "for" */
9190 if (!pi->next->cmds[0].argv) {
9191 G.last_exitcode = rcode = EXIT_SUCCESS;
9192 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9193 break;
9194 }
9195 vals = pi->next->cmds[0].argv;
9196 } /* else: "for var; do..." -> assume "$@" list */
9197 /* create list of variable values */
9198 debug_print_strings("for_list made from", vals);
9199 for_list = expand_strvec_to_strvec(vals);
9200 for_lcur = for_list;
9201 debug_print_strings("for_list", for_list);
9202 }
9203 if (!*for_lcur) {
9204 /* "for" loop is over, clean up */
9205 free(for_list);
9206 for_list = NULL;
9207 for_lcur = NULL;
9208 break;
9209 }
9210 /* Insert next value from for_lcur */
9211 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009212 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009213 continue;
9214 }
9215 if (rword == RES_IN) {
9216 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9217 }
9218 if (rword == RES_DONE) {
9219 continue; /* "done" has no cmds too */
9220 }
9221#endif
9222#if ENABLE_HUSH_CASE
9223 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009224 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009225 case_word = expand_string_to_string(pi->cmds->argv[0],
9226 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009227 debug_printf_exec("CASE word1:'%s'\n", case_word);
9228 //unbackslash(case_word);
9229 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009230 continue;
9231 }
9232 if (rword == RES_MATCH) {
9233 char **argv;
9234
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009235 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009236 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9237 break;
9238 /* all prev words didn't match, does this one match? */
9239 argv = pi->cmds->argv;
9240 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009241 char *pattern;
9242 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9243 pattern = expand_string_to_string(*argv,
9244 EXP_FLAG_ESC_GLOB_CHARS,
9245 /*unbackslash:*/ 0
9246 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009247 /* TODO: which FNM_xxx flags to use? */
9248 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009249 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9250 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009251 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009252 if (cond_code == 0) {
9253 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009254 free(case_word);
9255 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009256 break;
9257 }
9258 argv++;
9259 }
9260 continue;
9261 }
9262 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009263 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009264 if (cond_code != 0)
9265 continue; /* not matched yet, skip this pipe */
9266 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009267 if (rword == RES_ESAC) {
9268 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9269 if (case_word) {
9270 /* "case" did not match anything: still set $? (to 0) */
9271 G.last_exitcode = rcode = EXIT_SUCCESS;
9272 }
9273 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009274#endif
9275 /* Just pressing <enter> in shell should check for jobs.
9276 * OTOH, in non-interactive shell this is useless
9277 * and only leads to extra job checks */
9278 if (pi->num_cmds == 0) {
9279 if (G_interactive_fd)
9280 goto check_jobs_and_continue;
9281 continue;
9282 }
9283
9284 /* After analyzing all keywords and conditions, we decided
9285 * to execute this pipe. NB: have to do checkjobs(NULL)
9286 * after run_pipe to collect any background children,
9287 * even if list execution is to be stopped. */
9288 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009289#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009290 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009291#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009292 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9293 if (r != -1) {
9294 /* We ran a builtin, function, or group.
9295 * rcode is already known
9296 * and we don't need to wait for anything. */
9297 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9298 G.last_exitcode = rcode;
9299 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009300#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009301 /* Was it "break" or "continue"? */
9302 if (G.flag_break_continue) {
9303 smallint fbc = G.flag_break_continue;
9304 /* We might fall into outer *loop*,
9305 * don't want to break it too */
9306 if (loop_top) {
9307 G.depth_break_continue--;
9308 if (G.depth_break_continue == 0)
9309 G.flag_break_continue = 0;
9310 /* else: e.g. "continue 2" should *break* once, *then* continue */
9311 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9312 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009313 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009314 break;
9315 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009316 /* "continue": simulate end of loop */
9317 rword = RES_DONE;
9318 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009319 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009320#endif
9321 if (G_flag_return_in_progress == 1) {
9322 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9323 break;
9324 }
9325 } else if (pi->followup == PIPE_BG) {
9326 /* What does bash do with attempts to background builtins? */
9327 /* even bash 3.2 doesn't do that well with nested bg:
9328 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9329 * I'm NOT treating inner &'s as jobs */
9330#if ENABLE_HUSH_JOB
9331 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009332 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009333#endif
9334 /* Last command's pid goes to $! */
9335 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009336 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009337 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009338/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009339 rcode = EXIT_SUCCESS;
9340 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009341 } else {
9342#if ENABLE_HUSH_JOB
9343 if (G.run_list_level == 1 && G_interactive_fd) {
9344 /* Waits for completion, then fg's main shell */
9345 rcode = checkjobs_and_fg_shell(pi);
9346 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009347 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009348 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009349#endif
9350 /* This one just waits for completion */
9351 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9352 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9353 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009354 G.last_exitcode = rcode;
9355 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009356 }
9357
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009358 /* Handle "set -e" */
9359 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9360 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9361 if (G.errexit_depth == 0)
9362 hush_exit(rcode);
9363 }
9364 G.errexit_depth = sv_errexit_depth;
9365
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009366 /* Analyze how result affects subsequent commands */
9367#if ENABLE_HUSH_IF
9368 if (rword == RES_IF || rword == RES_ELIF)
9369 cond_code = rcode;
9370#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009371 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009372 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009373 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009374#if ENABLE_HUSH_LOOPS
9375 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009376 if (pi->next
9377 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009378 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009379 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009380 if (rword == RES_WHILE) {
9381 if (rcode) {
9382 /* "while false; do...done" - exitcode 0 */
9383 G.last_exitcode = rcode = EXIT_SUCCESS;
9384 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009385 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009386 }
9387 }
9388 if (rword == RES_UNTIL) {
9389 if (!rcode) {
9390 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009391 break;
9392 }
9393 }
9394 }
9395#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009396 } /* for (pi) */
9397
9398#if ENABLE_HUSH_JOB
9399 G.run_list_level--;
9400#endif
9401#if ENABLE_HUSH_LOOPS
9402 if (loop_top)
9403 G.depth_of_loop--;
9404 free(for_list);
9405#endif
9406#if ENABLE_HUSH_CASE
9407 free(case_word);
9408#endif
9409 debug_leave();
9410 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9411 return rcode;
9412}
9413
9414/* Select which version we will use */
9415static int run_and_free_list(struct pipe *pi)
9416{
9417 int rcode = 0;
9418 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009419 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009420 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9421 rcode = run_list(pi);
9422 }
9423 /* free_pipe_list has the side effect of clearing memory.
9424 * In the long run that function can be merged with run_list,
9425 * but doing that now would hobble the debugging effort. */
9426 free_pipe_list(pi);
9427 debug_printf_exec("run_and_free_list return %d\n", rcode);
9428 return rcode;
9429}
9430
9431
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009432static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009433{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009434 sighandler_t old_handler;
9435 unsigned sig = 0;
9436 while ((mask >>= 1) != 0) {
9437 sig++;
9438 if (!(mask & 1))
9439 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009440 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009441 /* POSIX allows shell to re-enable SIGCHLD
9442 * even if it was SIG_IGN on entry.
9443 * Therefore we skip IGN check for it:
9444 */
9445 if (sig == SIGCHLD)
9446 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009447 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9448 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9449 */
9450 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009451 if (old_handler == SIG_IGN) {
9452 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009453 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009454#if ENABLE_HUSH_TRAP
9455 if (!G_traps)
9456 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9457 free(G_traps[sig]);
9458 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9459#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009460 }
9461 }
9462}
9463
9464/* Called a few times only (or even once if "sh -c") */
9465static void install_special_sighandlers(void)
9466{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009467 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009468
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009469 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009470 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009471 if (G_interactive_fd) {
9472 mask |= SPECIAL_INTERACTIVE_SIGS;
9473 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009474 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009475 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009476 /* Careful, do not re-install handlers we already installed */
9477 if (G.special_sig_mask != mask) {
9478 unsigned diff = mask & ~G.special_sig_mask;
9479 G.special_sig_mask = mask;
9480 install_sighandlers(diff);
9481 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009482}
9483
9484#if ENABLE_HUSH_JOB
9485/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009486/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009487static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009488{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009489 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009490
9491 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009492 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009493 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9494 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009495 + (1 << SIGBUS ) * HUSH_DEBUG
9496 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009497 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009498 + (1 << SIGABRT)
9499 /* bash 3.2 seems to handle these just like 'fatal' ones */
9500 + (1 << SIGPIPE)
9501 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009502 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009503 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009504 * we never want to restore pgrp on exit, and this fn is not called
9505 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009506 /*+ (1 << SIGHUP )*/
9507 /*+ (1 << SIGTERM)*/
9508 /*+ (1 << SIGINT )*/
9509 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009510 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009511
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009512 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009513}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009514#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009515
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009516static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009517{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009518 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009519 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009520 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009521 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009522 break;
9523 case 'x':
9524 IF_HUSH_MODE_X(G_x_mode = state;)
9525 break;
9526 case 'o':
9527 if (!o_opt) {
9528 /* "set -+o" without parameter.
9529 * in bash, set -o produces this output:
9530 * pipefail off
9531 * and set +o:
9532 * set +o pipefail
9533 * We always use the second form.
9534 */
9535 const char *p = o_opt_strings;
9536 idx = 0;
9537 while (*p) {
9538 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9539 idx++;
9540 p += strlen(p) + 1;
9541 }
9542 break;
9543 }
9544 idx = index_in_strings(o_opt_strings, o_opt);
9545 if (idx >= 0) {
9546 G.o_opt[idx] = state;
9547 break;
9548 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009549 case 'e':
9550 G.o_opt[OPT_O_ERREXIT] = state;
9551 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009552 default:
9553 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009554 }
9555 return EXIT_SUCCESS;
9556}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009557
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009558int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009559int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009560{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009561 enum {
9562 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009563 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009564 };
9565 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009566 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009567 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009568 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009569 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009570
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009571 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009572 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009573 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009574
Denys Vlasenko10c01312011-05-11 11:49:21 +02009575#if ENABLE_HUSH_FAST
9576 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9577#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009578#if !BB_MMU
9579 G.argv0_for_re_execing = argv[0];
9580#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009581
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009582 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009583 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9584 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009585 shell_ver = xzalloc(sizeof(*shell_ver));
9586 shell_ver->flg_export = 1;
9587 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009588 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009589 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009590 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009591
Denys Vlasenko605067b2010-09-06 12:10:51 +02009592 /* Create shell local variables from the values
9593 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009594 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009595 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009596 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009597 if (e) while (*e) {
9598 char *value = strchr(*e, '=');
9599 if (value) { /* paranoia */
9600 cur_var->next = xzalloc(sizeof(*cur_var));
9601 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009602 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009603 cur_var->max_len = strlen(*e);
9604 cur_var->flg_export = 1;
9605 }
9606 e++;
9607 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009608 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009609 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9610 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009611
9612 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009613 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009614
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009615#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9616 /* Set (but not export) PS1/2 unless already set */
9617 if (!get_local_var_value("PS1"))
9618 set_local_var_from_halves("PS1", "\\w \\$ ");
9619 if (!get_local_var_value("PS2"))
9620 set_local_var_from_halves("PS2", "> ");
9621#endif
9622
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009623#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009624 /* Set (but not export) HOSTNAME unless already set */
9625 if (!get_local_var_value("HOSTNAME")) {
9626 struct utsname uts;
9627 uname(&uts);
9628 set_local_var_from_halves("HOSTNAME", uts.nodename);
9629 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009630 /* bash also exports SHLVL and _,
9631 * and sets (but doesn't export) the following variables:
9632 * BASH=/bin/bash
9633 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9634 * BASH_VERSION='3.2.0(1)-release'
9635 * HOSTTYPE=i386
9636 * MACHTYPE=i386-pc-linux-gnu
9637 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009638 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009639 * EUID=<NNNNN>
9640 * UID=<NNNNN>
9641 * GROUPS=()
9642 * LINES=<NNN>
9643 * COLUMNS=<NNN>
9644 * BASH_ARGC=()
9645 * BASH_ARGV=()
9646 * BASH_LINENO=()
9647 * BASH_SOURCE=()
9648 * DIRSTACK=()
9649 * PIPESTATUS=([0]="0")
9650 * HISTFILE=/<xxx>/.bash_history
9651 * HISTFILESIZE=500
9652 * HISTSIZE=500
9653 * MAILCHECK=60
9654 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9655 * SHELL=/bin/bash
9656 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9657 * TERM=dumb
9658 * OPTERR=1
9659 * OPTIND=1
9660 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009661 * PS4='+ '
9662 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009663#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009664
Denys Vlasenko5807e182018-02-08 19:19:04 +01009665#if ENABLE_HUSH_LINENO_VAR
9666 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009667 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9668 set_local_var(p, /*flags*/ 0);
9669 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9670 }
9671#endif
9672
Denis Vlasenko38f63192007-01-22 09:03:07 +00009673#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009674 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009675#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009676
Eric Andersen94ac2442001-05-22 19:05:18 +00009677 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009678 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009679
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009680 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009681
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009682 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009683 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009684 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009685 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009686 * in order to intercept (more) signals.
9687 */
9688
9689 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009690 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009691 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009692 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009693 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009694 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009695#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009696 "<:$:R:V:"
9697# if ENABLE_HUSH_FUNCTIONS
9698 "F:"
9699# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009700#endif
9701 );
9702 if (opt <= 0)
9703 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009704 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009705 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009706 /* Possibilities:
9707 * sh ... -c 'script'
9708 * sh ... -c 'script' ARG0 [ARG1...]
9709 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009710 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009711 * "" needs to be replaced with NULL
9712 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009713 * Note: the form without ARG0 never happens:
9714 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009715 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009716 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009717 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009718 G.root_ppid = getppid();
9719 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009720 G.global_argv = argv + optind;
9721 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009722 if (builtin_argc) {
9723 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9724 const struct built_in_command *x;
9725
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009726 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009727 x = find_builtin(optarg);
9728 if (x) { /* paranoia */
9729 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9730 G.global_argv += builtin_argc;
9731 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009732 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009733 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009734 }
9735 goto final_return;
9736 }
9737 if (!G.global_argv[0]) {
9738 /* -c 'script' (no params): prevent empty $0 */
9739 G.global_argv--; /* points to argv[i] of 'script' */
9740 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009741 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009742 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009743 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009744 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009745 goto final_return;
9746 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009747 /* Well, we cannot just declare interactiveness,
9748 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009749 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009750 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009751 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009752 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009753 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009754 case 'l':
9755 flags |= OPT_login;
9756 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009757#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009758 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009759 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009760 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009761 case '$': {
9762 unsigned long long empty_trap_mask;
9763
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009764 G.root_pid = bb_strtou(optarg, &optarg, 16);
9765 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009766 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9767 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009768 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9769 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009770 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009771 optarg++;
9772 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009773 optarg++;
9774 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9775 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009776 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009777 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009778# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009779 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009780 for (sig = 1; sig < NSIG; sig++) {
9781 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009782 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009783 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009784 }
9785 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009786# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009787 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009788# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009789 optarg++;
9790 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009791# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009792# if ENABLE_HUSH_FUNCTIONS
9793 /* nommu uses re-exec trick for "... | func | ...",
9794 * should allow "return".
9795 * This accidentally allows returns in subshells.
9796 */
9797 G_flag_return_in_progress = -1;
9798# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009799 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009800 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009801 case 'R':
9802 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009803 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009804 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009805# if ENABLE_HUSH_FUNCTIONS
9806 case 'F': {
9807 struct function *funcp = new_function(optarg);
9808 /* funcp->name is already set to optarg */
9809 /* funcp->body is set to NULL. It's a special case. */
9810 funcp->body_as_string = argv[optind];
9811 optind++;
9812 break;
9813 }
9814# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009815#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009816 case 'n':
9817 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009818 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009819 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009820 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009821 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009822#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009823 fprintf(stderr, "Usage: sh [FILE]...\n"
9824 " or: sh -c command [args]...\n\n");
9825 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009826#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009827 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009828#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009829 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009830 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009831
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009832 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9833 G.global_argc = argc - (optind - 1);
9834 G.global_argv = argv + (optind - 1);
9835 G.global_argv[0] = argv[0];
9836
Denys Vlasenkodea47882009-10-09 15:40:49 +02009837 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009838 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009839 G.root_ppid = getppid();
9840 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009841
9842 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009843 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009844 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009845 debug_printf("sourcing /etc/profile\n");
9846 input = fopen_for_read("/etc/profile");
9847 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009848 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009849 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009850 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009851 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009852 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009853 /* bash: after sourcing /etc/profile,
9854 * tries to source (in the given order):
9855 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009856 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009857 * bash also sources ~/.bash_logout on exit.
9858 * If called as sh, skips .bash_XXX files.
9859 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009860 }
9861
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009862 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9863 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009864 FILE *input;
9865 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009866 * "bash <script>" (which is never interactive (unless -i?))
9867 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009868 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009869 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009870 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009871 G.global_argc--;
9872 G.global_argv++;
9873 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009874 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009875 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009876 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009877 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009878 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009879 parse_and_run_file(input);
9880#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009881 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009882#endif
9883 goto final_return;
9884 }
9885
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009886 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009887 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009888 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009889
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009890 /* A shell is interactive if the '-i' flag was given,
9891 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009892 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009893 * no arguments remaining or the -s flag given
9894 * standard input is a terminal
9895 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009896 * Refer to Posix.2, the description of the 'sh' utility.
9897 */
9898#if ENABLE_HUSH_JOB
9899 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009900 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9901 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9902 if (G_saved_tty_pgrp < 0)
9903 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009904
9905 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009906 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009907 if (G_interactive_fd < 0) {
9908 /* try to dup to any fd */
9909 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009910 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009911 /* give up */
9912 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009913 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009914 }
9915 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009916// TODO: track & disallow any attempts of user
9917// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009918 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009919 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009920 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009921 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009922
Mike Frysinger38478a62009-05-20 04:48:06 -04009923 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009924 /* If we were run as 'hush &', sleep until we are
9925 * in the foreground (tty pgrp == our pgrp).
9926 * If we get started under a job aware app (like bash),
9927 * make sure we are now in charge so we don't fight over
9928 * who gets the foreground */
9929 while (1) {
9930 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009931 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9932 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009933 break;
9934 /* send TTIN to ourself (should stop us) */
9935 kill(- shell_pgrp, SIGTTIN);
9936 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009937 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009938
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009939 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009940 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009941
Mike Frysinger38478a62009-05-20 04:48:06 -04009942 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009943 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009944 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009945 /* Put ourselves in our own process group
9946 * (bash, too, does this only if ctty is available) */
9947 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9948 /* Grab control of the terminal */
9949 tcsetpgrp(G_interactive_fd, getpid());
9950 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009951 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009952
9953# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9954 {
9955 const char *hp = get_local_var_value("HISTFILE");
9956 if (!hp) {
9957 hp = get_local_var_value("HOME");
9958 if (hp)
9959 hp = concat_path_file(hp, ".hush_history");
9960 } else {
9961 hp = xstrdup(hp);
9962 }
9963 if (hp) {
9964 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009965 //set_local_var(xasprintf("HISTFILE=%s", ...));
9966 }
9967# if ENABLE_FEATURE_SH_HISTFILESIZE
9968 hp = get_local_var_value("HISTFILESIZE");
9969 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9970# endif
9971 }
9972# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009973 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009974 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009975 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009976#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009977 /* No job control compiled in, only prompt/line editing */
9978 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009979 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009980 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009981 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +02009982 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009983 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009984 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009985 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009986 }
9987 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009988 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009989 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009990 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009991 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009992#else
9993 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009994 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009995#endif
9996 /* bash:
9997 * if interactive but not a login shell, sources ~/.bashrc
9998 * (--norc turns this off, --rcfile <file> overrides)
9999 */
10000
10001 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +020010002 /* note: ash and hush share this string */
10003 printf("\n\n%s %s\n"
10004 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10005 "\n",
10006 bb_banner,
10007 "hush - the humble shell"
10008 );
Mike Frysingerb2705e12009-03-23 08:44:02 +000010009 }
10010
Denis Vlasenkof9375282009-04-05 19:13:39 +000010011 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +000010012
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010013 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010014 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010015}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010016
10017
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010018/*
10019 * Built-ins
10020 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010021static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010022{
10023 return 0;
10024}
10025
Denys Vlasenko265062d2017-01-10 15:13:30 +010010026#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010027static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010028{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010029 int argc = string_array_len(argv);
10030 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010031}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010032#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010033#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010034static int FAST_FUNC builtin_test(char **argv)
10035{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010036 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010037}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010038#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010039#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010040static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010041{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010042 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010043}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010044#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010045#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010046static int FAST_FUNC builtin_printf(char **argv)
10047{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010048 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010049}
10050#endif
10051
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010052#if ENABLE_HUSH_HELP
10053static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10054{
10055 const struct built_in_command *x;
10056
10057 printf(
10058 "Built-in commands:\n"
10059 "------------------\n");
10060 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10061 if (x->b_descr)
10062 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10063 }
10064 return EXIT_SUCCESS;
10065}
10066#endif
10067
10068#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10069static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10070{
10071 show_history(G.line_input_state);
10072 return EXIT_SUCCESS;
10073}
10074#endif
10075
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010076static char **skip_dash_dash(char **argv)
10077{
10078 argv++;
10079 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10080 argv++;
10081 return argv;
10082}
10083
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010084static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010085{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010086 const char *newdir;
10087
10088 argv = skip_dash_dash(argv);
10089 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010090 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010091 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010092 * bash says "bash: cd: HOME not set" and does nothing
10093 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010094 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010095 const char *home = get_local_var_value("HOME");
10096 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010097 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010098 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010099 /* Mimic bash message exactly */
10100 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010101 return EXIT_FAILURE;
10102 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010103 /* Read current dir (get_cwd(1) is inside) and set PWD.
10104 * Note: do not enforce exporting. If PWD was unset or unexported,
10105 * set it again, but do not export. bash does the same.
10106 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010107 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010108 return EXIT_SUCCESS;
10109}
10110
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010111static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10112{
10113 puts(get_cwd(0));
10114 return EXIT_SUCCESS;
10115}
10116
10117static int FAST_FUNC builtin_eval(char **argv)
10118{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010119 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010120
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010121 if (!argv[0])
10122 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010123
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010124 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010125 /* bash:
10126 * eval "echo Hi; done" ("done" is syntax error):
10127 * "echo Hi" will not execute too.
10128 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010129 parse_and_run_string(argv[0]);
10130 } else {
10131 /* "The eval utility shall construct a command by
10132 * concatenating arguments together, separating
10133 * each with a <space> character."
10134 */
10135 char *str, *p;
10136 unsigned len = 0;
10137 char **pp = argv;
10138 do
10139 len += strlen(*pp) + 1;
10140 while (*++pp);
10141 str = p = xmalloc(len);
10142 pp = argv;
10143 for (;;) {
10144 p = stpcpy(p, *pp);
10145 pp++;
10146 if (!*pp)
10147 break;
10148 *p++ = ' ';
10149 }
10150 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010151 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010152 }
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010153 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010154}
10155
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010156static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010157{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010158 argv = skip_dash_dash(argv);
10159 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010160 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010161
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010162 /* Careful: we can end up here after [v]fork. Do not restore
10163 * tty pgrp then, only top-level shell process does that */
10164 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10165 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10166
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010167 /* Saved-redirect fds, script fds and G_interactive_fd are still
10168 * open here. However, they are all CLOEXEC, and execv below
10169 * closes them. Try interactive "exec ls -l /proc/self/fd",
10170 * it should show no extra open fds in the "ls" process.
10171 * If we'd try to run builtins/NOEXECs, this would need improving.
10172 */
10173 //close_saved_fds_and_FILE_fds();
10174
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010175 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010176 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010177 * and tcsetpgrp, and this is inherently racy.
10178 */
10179 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010180}
10181
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010182static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010183{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010184 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010185
10186 /* interactive bash:
10187 * # trap "echo EEE" EXIT
10188 * # exit
10189 * exit
10190 * There are stopped jobs.
10191 * (if there are _stopped_ jobs, running ones don't count)
10192 * # exit
10193 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010194 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010195 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010196 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010197 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010198
10199 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010200 argv = skip_dash_dash(argv);
10201 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010202 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010203 /* mimic bash: exit 123abc == exit 255 + error msg */
10204 xfunc_error_retval = 255;
10205 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010206 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010207}
10208
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010209#if ENABLE_HUSH_TYPE
10210/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10211static int FAST_FUNC builtin_type(char **argv)
10212{
10213 int ret = EXIT_SUCCESS;
10214
10215 while (*++argv) {
10216 const char *type;
10217 char *path = NULL;
10218
10219 if (0) {} /* make conditional compile easier below */
10220 /*else if (find_alias(*argv))
10221 type = "an alias";*/
10222#if ENABLE_HUSH_FUNCTIONS
10223 else if (find_function(*argv))
10224 type = "a function";
10225#endif
10226 else if (find_builtin(*argv))
10227 type = "a shell builtin";
10228 else if ((path = find_in_path(*argv)) != NULL)
10229 type = path;
10230 else {
10231 bb_error_msg("type: %s: not found", *argv);
10232 ret = EXIT_FAILURE;
10233 continue;
10234 }
10235
10236 printf("%s is %s\n", *argv, type);
10237 free(path);
10238 }
10239
10240 return ret;
10241}
10242#endif
10243
10244#if ENABLE_HUSH_READ
10245/* Interruptibility of read builtin in bash
10246 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10247 *
10248 * Empty trap makes read ignore corresponding signal, for any signal.
10249 *
10250 * SIGINT:
10251 * - terminates non-interactive shell;
10252 * - interrupts read in interactive shell;
10253 * if it has non-empty trap:
10254 * - executes trap and returns to command prompt in interactive shell;
10255 * - executes trap and returns to read in non-interactive shell;
10256 * SIGTERM:
10257 * - is ignored (does not interrupt) read in interactive shell;
10258 * - terminates non-interactive shell;
10259 * if it has non-empty trap:
10260 * - executes trap and returns to read;
10261 * SIGHUP:
10262 * - terminates shell (regardless of interactivity);
10263 * if it has non-empty trap:
10264 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010265 * SIGCHLD from children:
10266 * - does not interrupt read regardless of interactivity:
10267 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010268 */
10269static int FAST_FUNC builtin_read(char **argv)
10270{
10271 const char *r;
10272 char *opt_n = NULL;
10273 char *opt_p = NULL;
10274 char *opt_t = NULL;
10275 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010276 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010277 const char *ifs;
10278 int read_flags;
10279
10280 /* "!": do not abort on errors.
10281 * Option string must start with "sr" to match BUILTIN_READ_xxx
10282 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010283 read_flags = getopt32(argv,
10284#if BASH_READ_D
10285 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10286#else
10287 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10288#endif
10289 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010290 if (read_flags == (uint32_t)-1)
10291 return EXIT_FAILURE;
10292 argv += optind;
10293 ifs = get_local_var_value("IFS"); /* can be NULL */
10294
10295 again:
10296 r = shell_builtin_read(set_local_var_from_halves,
10297 argv,
10298 ifs,
10299 read_flags,
10300 opt_n,
10301 opt_p,
10302 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010303 opt_u,
10304 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010305 );
10306
10307 if ((uintptr_t)r == 1 && errno == EINTR) {
10308 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010309 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010310 goto again;
10311 }
10312
10313 if ((uintptr_t)r > 1) {
10314 bb_error_msg("%s", r);
10315 r = (char*)(uintptr_t)1;
10316 }
10317
10318 return (uintptr_t)r;
10319}
10320#endif
10321
10322#if ENABLE_HUSH_UMASK
10323static int FAST_FUNC builtin_umask(char **argv)
10324{
10325 int rc;
10326 mode_t mask;
10327
10328 rc = 1;
10329 mask = umask(0);
10330 argv = skip_dash_dash(argv);
10331 if (argv[0]) {
10332 mode_t old_mask = mask;
10333
10334 /* numeric umasks are taken as-is */
10335 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10336 if (!isdigit(argv[0][0]))
10337 mask ^= 0777;
10338 mask = bb_parse_mode(argv[0], mask);
10339 if (!isdigit(argv[0][0]))
10340 mask ^= 0777;
10341 if ((unsigned)mask > 0777) {
10342 mask = old_mask;
10343 /* bash messages:
10344 * bash: umask: 'q': invalid symbolic mode operator
10345 * bash: umask: 999: octal number out of range
10346 */
10347 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10348 rc = 0;
10349 }
10350 } else {
10351 /* Mimic bash */
10352 printf("%04o\n", (unsigned) mask);
10353 /* fall through and restore mask which we set to 0 */
10354 }
10355 umask(mask);
10356
10357 return !rc; /* rc != 0 - success */
10358}
10359#endif
10360
Denys Vlasenko41ade052017-01-08 18:56:24 +010010361#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010362static void print_escaped(const char *s)
10363{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010364 if (*s == '\'')
10365 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010366 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010367 const char *p = strchrnul(s, '\'');
10368 /* print 'xxxx', possibly just '' */
10369 printf("'%.*s'", (int)(p - s), s);
10370 if (*p == '\0')
10371 break;
10372 s = p;
10373 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010374 /* s points to '; print "'''...'''" */
10375 putchar('"');
10376 do putchar('\''); while (*++s == '\'');
10377 putchar('"');
10378 } while (*s);
10379}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010380#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010381
Denys Vlasenko1e660422017-07-17 21:10:50 +020010382#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010383static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010384{
10385 do {
10386 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010387 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010388
10389 /* So far we do not check that name is valid (TODO?) */
10390
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010391 if (*name_end == '\0') {
10392 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010393
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010394 vpp = get_ptr_to_local_var(name, name_end - name);
10395 var = vpp ? *vpp : NULL;
10396
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010397 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010398 /* export -n NAME (without =VALUE) */
10399 if (var) {
10400 var->flg_export = 0;
10401 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10402 unsetenv(name);
10403 } /* else: export -n NOT_EXISTING_VAR: no-op */
10404 continue;
10405 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010406 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010407 /* export NAME (without =VALUE) */
10408 if (var) {
10409 var->flg_export = 1;
10410 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10411 putenv(var->varstr);
10412 continue;
10413 }
10414 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010415 if (flags & SETFLAG_MAKE_RO) {
10416 /* readonly NAME (without =VALUE) */
10417 if (var) {
10418 var->flg_read_only = 1;
10419 continue;
10420 }
10421 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010422# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010423 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010424 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010425 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10426 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010427 /* "local x=abc; ...; local x" - ignore second local decl */
10428 continue;
10429 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010430 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010431# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010432 /* Exporting non-existing variable.
10433 * bash does not put it in environment,
10434 * but remembers that it is exported,
10435 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010436 * We just set it to "" and export.
10437 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010438 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010439 * bash sets the value to "".
10440 */
10441 /* Or, it's "readonly NAME" (without =VALUE).
10442 * bash remembers NAME and disallows its creation
10443 * in the future.
10444 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010445 name = xasprintf("%s=", name);
10446 } else {
10447 /* (Un)exporting/making local NAME=VALUE */
10448 name = xstrdup(name);
10449 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010450 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010451 if (set_local_var(name, flags))
10452 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010453 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010454 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010455}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010456#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010457
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010458#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010459static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010460{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010461 unsigned opt_unexport;
10462
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010463#if ENABLE_HUSH_EXPORT_N
10464 /* "!": do not abort on errors */
10465 opt_unexport = getopt32(argv, "!n");
10466 if (opt_unexport == (uint32_t)-1)
10467 return EXIT_FAILURE;
10468 argv += optind;
10469#else
10470 opt_unexport = 0;
10471 argv++;
10472#endif
10473
10474 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010475 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010476 if (e) {
10477 while (*e) {
10478#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010479 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010480#else
10481 /* ash emits: export VAR='VAL'
10482 * bash: declare -x VAR="VAL"
10483 * we follow ash example */
10484 const char *s = *e++;
10485 const char *p = strchr(s, '=');
10486
10487 if (!p) /* wtf? take next variable */
10488 continue;
10489 /* export var= */
10490 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010491 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010492 putchar('\n');
10493#endif
10494 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010495 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010496 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010497 return EXIT_SUCCESS;
10498 }
10499
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010500 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010501}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010502#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010503
Denys Vlasenko295fef82009-06-03 12:47:26 +020010504#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010505static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010506{
10507 if (G.func_nest_level == 0) {
10508 bb_error_msg("%s: not in a function", argv[0]);
10509 return EXIT_FAILURE; /* bash compat */
10510 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010511 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010512 /* Since all builtins run in a nested variable level,
10513 * need to use level - 1 here. Or else the variable will be removed at once
10514 * after builtin returns.
10515 */
10516 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010517}
10518#endif
10519
Denys Vlasenko1e660422017-07-17 21:10:50 +020010520#if ENABLE_HUSH_READONLY
10521static int FAST_FUNC builtin_readonly(char **argv)
10522{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010523 argv++;
10524 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010525 /* bash: readonly [-p]: list all readonly VARs
10526 * (-p has no effect in bash)
10527 */
10528 struct variable *e;
10529 for (e = G.top_var; e; e = e->next) {
10530 if (e->flg_read_only) {
10531//TODO: quote value: readonly VAR='VAL'
10532 printf("readonly %s\n", e->varstr);
10533 }
10534 }
10535 return EXIT_SUCCESS;
10536 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010537 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010538}
10539#endif
10540
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010541#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010542/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10543static int FAST_FUNC builtin_unset(char **argv)
10544{
10545 int ret;
10546 unsigned opts;
10547
10548 /* "!": do not abort on errors */
10549 /* "+": stop at 1st non-option */
10550 opts = getopt32(argv, "!+vf");
10551 if (opts == (unsigned)-1)
10552 return EXIT_FAILURE;
10553 if (opts == 3) {
10554 bb_error_msg("unset: -v and -f are exclusive");
10555 return EXIT_FAILURE;
10556 }
10557 argv += optind;
10558
10559 ret = EXIT_SUCCESS;
10560 while (*argv) {
10561 if (!(opts & 2)) { /* not -f */
10562 if (unset_local_var(*argv)) {
10563 /* unset <nonexistent_var> doesn't fail.
10564 * Error is when one tries to unset RO var.
10565 * Message was printed by unset_local_var. */
10566 ret = EXIT_FAILURE;
10567 }
10568 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010569# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010570 else {
10571 unset_func(*argv);
10572 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010573# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010574 argv++;
10575 }
10576 return ret;
10577}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010578#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010579
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010580#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010581/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10582 * built-in 'set' handler
10583 * SUSv3 says:
10584 * set [-abCefhmnuvx] [-o option] [argument...]
10585 * set [+abCefhmnuvx] [+o option] [argument...]
10586 * set -- [argument...]
10587 * set -o
10588 * set +o
10589 * Implementations shall support the options in both their hyphen and
10590 * plus-sign forms. These options can also be specified as options to sh.
10591 * Examples:
10592 * Write out all variables and their values: set
10593 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10594 * Turn on the -x and -v options: set -xv
10595 * Unset all positional parameters: set --
10596 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10597 * Set the positional parameters to the expansion of x, even if x expands
10598 * with a leading '-' or '+': set -- $x
10599 *
10600 * So far, we only support "set -- [argument...]" and some of the short names.
10601 */
10602static int FAST_FUNC builtin_set(char **argv)
10603{
10604 int n;
10605 char **pp, **g_argv;
10606 char *arg = *++argv;
10607
10608 if (arg == NULL) {
10609 struct variable *e;
10610 for (e = G.top_var; e; e = e->next)
10611 puts(e->varstr);
10612 return EXIT_SUCCESS;
10613 }
10614
10615 do {
10616 if (strcmp(arg, "--") == 0) {
10617 ++argv;
10618 goto set_argv;
10619 }
10620 if (arg[0] != '+' && arg[0] != '-')
10621 break;
10622 for (n = 1; arg[n]; ++n) {
10623 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10624 goto error;
10625 if (arg[n] == 'o' && argv[1])
10626 argv++;
10627 }
10628 } while ((arg = *++argv) != NULL);
10629 /* Now argv[0] is 1st argument */
10630
10631 if (arg == NULL)
10632 return EXIT_SUCCESS;
10633 set_argv:
10634
10635 /* NB: G.global_argv[0] ($0) is never freed/changed */
10636 g_argv = G.global_argv;
10637 if (G.global_args_malloced) {
10638 pp = g_argv;
10639 while (*++pp)
10640 free(*pp);
10641 g_argv[1] = NULL;
10642 } else {
10643 G.global_args_malloced = 1;
10644 pp = xzalloc(sizeof(pp[0]) * 2);
10645 pp[0] = g_argv[0]; /* retain $0 */
10646 g_argv = pp;
10647 }
10648 /* This realloc's G.global_argv */
10649 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10650
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010651 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010652
10653 return EXIT_SUCCESS;
10654
10655 /* Nothing known, so abort */
10656 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010657 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010658 return EXIT_FAILURE;
10659}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010660#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010661
10662static int FAST_FUNC builtin_shift(char **argv)
10663{
10664 int n = 1;
10665 argv = skip_dash_dash(argv);
10666 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010667 n = bb_strtou(argv[0], NULL, 10);
10668 if (errno || n < 0) {
10669 /* shared string with ash.c */
10670 bb_error_msg("Illegal number: %s", argv[0]);
10671 /*
10672 * ash aborts in this case.
10673 * bash prints error message and set $? to 1.
10674 * Interestingly, for "shift 99999" bash does not
10675 * print error message, but does set $? to 1
10676 * (and does no shifting at all).
10677 */
10678 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010679 }
10680 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010681 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010682 int m = 1;
10683 while (m <= n)
10684 free(G.global_argv[m++]);
10685 }
10686 G.global_argc -= n;
10687 memmove(&G.global_argv[1], &G.global_argv[n+1],
10688 G.global_argc * sizeof(G.global_argv[0]));
10689 return EXIT_SUCCESS;
10690 }
10691 return EXIT_FAILURE;
10692}
10693
Denys Vlasenko74d40582017-08-11 01:32:46 +020010694#if ENABLE_HUSH_GETOPTS
10695static int FAST_FUNC builtin_getopts(char **argv)
10696{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010697/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10698
Denys Vlasenko74d40582017-08-11 01:32:46 +020010699TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010700If a required argument is not found, and getopts is not silent,
10701a question mark (?) is placed in VAR, OPTARG is unset, and a
10702diagnostic message is printed. If getopts is silent, then a
10703colon (:) is placed in VAR and OPTARG is set to the option
10704character found.
10705
10706Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010707
10708"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010709*/
10710 char cbuf[2];
10711 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010712 int c, n, exitcode, my_opterr;
10713 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010714
10715 optstring = *++argv;
10716 if (!optstring || !(var = *++argv)) {
10717 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10718 return EXIT_FAILURE;
10719 }
10720
Denys Vlasenko238ff982017-08-29 13:38:30 +020010721 if (argv[1])
10722 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10723 else
10724 argv = G.global_argv;
10725 cbuf[1] = '\0';
10726
10727 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010728 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010729 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010730 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010731 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010732 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010733
10734 /* getopts stops on first non-option. Add "+" to force that */
10735 /*if (optstring[0] != '+')*/ {
10736 char *s = alloca(strlen(optstring) + 2);
10737 sprintf(s, "+%s", optstring);
10738 optstring = s;
10739 }
10740
Denys Vlasenko238ff982017-08-29 13:38:30 +020010741 /* Naively, now we should just
10742 * cp = get_local_var_value("OPTIND");
10743 * optind = cp ? atoi(cp) : 0;
10744 * optarg = NULL;
10745 * opterr = my_opterr;
10746 * c = getopt(string_array_len(argv), argv, optstring);
10747 * and be done? Not so fast...
10748 * Unlike normal getopt() usage in C programs, here
10749 * each successive call will (usually) have the same argv[] CONTENTS,
10750 * but not the ADDRESSES. Worse yet, it's possible that between
10751 * invocations of "getopts", there will be calls to shell builtins
10752 * which use getopt() internally. Example:
10753 * while getopts "abc" RES -a -bc -abc de; do
10754 * unset -ff func
10755 * done
10756 * This would not work correctly: getopt() call inside "unset"
10757 * modifies internal libc state which is tracking position in
10758 * multi-option strings ("-abc"). At best, it can skip options
10759 * or return the same option infinitely. With glibc implementation
10760 * of getopt(), it would use outright invalid pointers and return
10761 * garbage even _without_ "unset" mangling internal state.
10762 *
10763 * We resort to resetting getopt() state and calling it N times,
10764 * until we get Nth result (or failure).
10765 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10766 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010767 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010768 count = 0;
10769 n = string_array_len(argv);
10770 do {
10771 optarg = NULL;
10772 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10773 c = getopt(n, argv, optstring);
10774 if (c < 0)
10775 break;
10776 count++;
10777 } while (count <= G.getopt_count);
10778
10779 /* Set OPTIND. Prevent resetting of the magic counter! */
10780 set_local_var_from_halves("OPTIND", utoa(optind));
10781 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010782 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010783
10784 /* Set OPTARG */
10785 /* Always set or unset, never left as-is, even on exit/error:
10786 * "If no option was found, or if the option that was found
10787 * does not have an option-argument, OPTARG shall be unset."
10788 */
10789 cp = optarg;
10790 if (c == '?') {
10791 /* If ":optstring" and unknown option is seen,
10792 * it is stored to OPTARG.
10793 */
10794 if (optstring[1] == ':') {
10795 cbuf[0] = optopt;
10796 cp = cbuf;
10797 }
10798 }
10799 if (cp)
10800 set_local_var_from_halves("OPTARG", cp);
10801 else
10802 unset_local_var("OPTARG");
10803
10804 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010805 exitcode = EXIT_SUCCESS;
10806 if (c < 0) { /* -1: end of options */
10807 exitcode = EXIT_FAILURE;
10808 c = '?';
10809 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010810
Denys Vlasenko238ff982017-08-29 13:38:30 +020010811 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010812 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010813 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010814
Denys Vlasenko74d40582017-08-11 01:32:46 +020010815 return exitcode;
10816}
10817#endif
10818
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010819static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010820{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010821 char *arg_path, *filename;
10822 FILE *input;
10823 save_arg_t sv;
10824 char *args_need_save;
10825#if ENABLE_HUSH_FUNCTIONS
10826 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010827#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010828
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010829 argv = skip_dash_dash(argv);
10830 filename = argv[0];
10831 if (!filename) {
10832 /* bash says: "bash: .: filename argument required" */
10833 return 2; /* bash compat */
10834 }
10835 arg_path = NULL;
10836 if (!strchr(filename, '/')) {
10837 arg_path = find_in_path(filename);
10838 if (arg_path)
10839 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010840 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010841 errno = ENOENT;
10842 bb_simple_perror_msg(filename);
10843 return EXIT_FAILURE;
10844 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010845 }
10846 input = remember_FILE(fopen_or_warn(filename, "r"));
10847 free(arg_path);
10848 if (!input) {
10849 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10850 /* POSIX: non-interactive shell should abort here,
10851 * not merely fail. So far no one complained :)
10852 */
10853 return EXIT_FAILURE;
10854 }
10855
10856#if ENABLE_HUSH_FUNCTIONS
10857 sv_flg = G_flag_return_in_progress;
10858 /* "we are inside sourced file, ok to use return" */
10859 G_flag_return_in_progress = -1;
10860#endif
10861 args_need_save = argv[1]; /* used as a boolean variable */
10862 if (args_need_save)
10863 save_and_replace_G_args(&sv, argv);
10864
10865 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10866 G.last_exitcode = 0;
10867 parse_and_run_file(input);
10868 fclose_and_forget(input);
10869
10870 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10871 restore_G_args(&sv, argv);
10872#if ENABLE_HUSH_FUNCTIONS
10873 G_flag_return_in_progress = sv_flg;
10874#endif
10875
10876 return G.last_exitcode;
10877}
10878
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010879#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010880static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010881{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010882 int sig;
10883 char *new_cmd;
10884
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010885 if (!G_traps)
10886 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010887
10888 argv++;
10889 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010890 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010891 /* No args: print all trapped */
10892 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010893 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010894 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010895 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010896 /* note: bash adds "SIG", but only if invoked
10897 * as "bash". If called as "sh", or if set -o posix,
10898 * then it prints short signal names.
10899 * We are printing short names: */
10900 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010901 }
10902 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010903 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010904 return EXIT_SUCCESS;
10905 }
10906
10907 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010908 /* If first arg is a number: reset all specified signals */
10909 sig = bb_strtou(*argv, NULL, 10);
10910 if (errno == 0) {
10911 int ret;
10912 process_sig_list:
10913 ret = EXIT_SUCCESS;
10914 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010915 sighandler_t handler;
10916
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010917 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010918 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010919 ret = EXIT_FAILURE;
10920 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010921 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010922 continue;
10923 }
10924
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010925 free(G_traps[sig]);
10926 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010927
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010928 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010929 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010930
10931 /* There is no signal for 0 (EXIT) */
10932 if (sig == 0)
10933 continue;
10934
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010935 if (new_cmd)
10936 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10937 else
10938 /* We are removing trap handler */
10939 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010940 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010941 }
10942 return ret;
10943 }
10944
10945 if (!argv[1]) { /* no second arg */
10946 bb_error_msg("trap: invalid arguments");
10947 return EXIT_FAILURE;
10948 }
10949
10950 /* First arg is "-": reset all specified to default */
10951 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10952 /* Everything else: set arg as signal handler
10953 * (includes "" case, which ignores signal) */
10954 if (argv[0][0] == '-') {
10955 if (argv[0][1] == '\0') { /* "-" */
10956 /* new_cmd remains NULL: "reset these sigs" */
10957 goto reset_traps;
10958 }
10959 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10960 argv++;
10961 }
10962 /* else: "-something", no special meaning */
10963 }
10964 new_cmd = *argv;
10965 reset_traps:
10966 argv++;
10967 goto process_sig_list;
10968}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010969#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010970
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010971#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010972static struct pipe *parse_jobspec(const char *str)
10973{
10974 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010975 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010976
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010977 if (sscanf(str, "%%%u", &jobnum) != 1) {
10978 if (str[0] != '%'
10979 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10980 ) {
10981 bb_error_msg("bad argument '%s'", str);
10982 return NULL;
10983 }
10984 /* It is "%%", "%+" or "%" - current job */
10985 jobnum = G.last_jobid;
10986 if (jobnum == 0) {
10987 bb_error_msg("no current job");
10988 return NULL;
10989 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010990 }
10991 for (pi = G.job_list; pi; pi = pi->next) {
10992 if (pi->jobid == jobnum) {
10993 return pi;
10994 }
10995 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010996 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010997 return NULL;
10998}
10999
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011000static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11001{
11002 struct pipe *job;
11003 const char *status_string;
11004
11005 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11006 for (job = G.job_list; job; job = job->next) {
11007 if (job->alive_cmds == job->stopped_cmds)
11008 status_string = "Stopped";
11009 else
11010 status_string = "Running";
11011
11012 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11013 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011014
11015 clean_up_last_dead_job();
11016
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011017 return EXIT_SUCCESS;
11018}
11019
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011020/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011021static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011022{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011023 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011024 struct pipe *pi;
11025
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011026 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011027 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011028
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011029 /* If they gave us no args, assume they want the last backgrounded task */
11030 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011031 for (pi = G.job_list; pi; pi = pi->next) {
11032 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011033 goto found;
11034 }
11035 }
11036 bb_error_msg("%s: no current job", argv[0]);
11037 return EXIT_FAILURE;
11038 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011039
11040 pi = parse_jobspec(argv[1]);
11041 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011042 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011043 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011044 /* TODO: bash prints a string representation
11045 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011046 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011047 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011048 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011049 }
11050
11051 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011052 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11053 for (i = 0; i < pi->num_cmds; i++) {
11054 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011055 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011056 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011057
11058 i = kill(- pi->pgrp, SIGCONT);
11059 if (i < 0) {
11060 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011061 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011062 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011063 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011064 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011065 }
11066
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011067 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011068 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011069 return checkjobs_and_fg_shell(pi);
11070 }
11071 return EXIT_SUCCESS;
11072}
11073#endif
11074
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011075#if ENABLE_HUSH_KILL
11076static int FAST_FUNC builtin_kill(char **argv)
11077{
11078 int ret = 0;
11079
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011080# if ENABLE_HUSH_JOB
11081 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11082 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011083
11084 do {
11085 struct pipe *pi;
11086 char *dst;
11087 int j, n;
11088
11089 if (argv[i][0] != '%')
11090 continue;
11091 /*
11092 * "kill %N" - job kill
11093 * Converting to pgrp / pid kill
11094 */
11095 pi = parse_jobspec(argv[i]);
11096 if (!pi) {
11097 /* Eat bad jobspec */
11098 j = i;
11099 do {
11100 j++;
11101 argv[j - 1] = argv[j];
11102 } while (argv[j]);
11103 ret = 1;
11104 i--;
11105 continue;
11106 }
11107 /*
11108 * In jobs started under job control, we signal
11109 * entire process group by kill -PGRP_ID.
11110 * This happens, f.e., in interactive shell.
11111 *
11112 * Otherwise, we signal each child via
11113 * kill PID1 PID2 PID3.
11114 * Testcases:
11115 * sh -c 'sleep 1|sleep 1 & kill %1'
11116 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11117 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11118 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011119 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011120 dst = alloca(n * sizeof(int)*4);
11121 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011122 if (G_interactive_fd)
11123 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011124 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011125 struct command *cmd = &pi->cmds[j];
11126 /* Skip exited members of the job */
11127 if (cmd->pid == 0)
11128 continue;
11129 /*
11130 * kill_main has matching code to expect
11131 * leading space. Needed to not confuse
11132 * negative pids with "kill -SIGNAL_NO" syntax
11133 */
11134 dst += sprintf(dst, " %u", (int)cmd->pid);
11135 }
11136 *dst = '\0';
11137 } while (argv[++i]);
11138 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011139# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011140
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011141 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011142 ret = run_applet_main(argv, kill_main);
11143 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011144 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011145 return ret;
11146}
11147#endif
11148
11149#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011150/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011151#if !ENABLE_HUSH_JOB
11152# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11153#endif
11154static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011155{
11156 int ret = 0;
11157 for (;;) {
11158 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011159 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011160
Denys Vlasenko830ea352016-11-08 04:59:11 +010011161 if (!sigisemptyset(&G.pending_set))
11162 goto check_sig;
11163
Denys Vlasenko7e675362016-10-28 21:57:31 +020011164 /* waitpid is not interruptible by SA_RESTARTed
11165 * signals which we use. Thus, this ugly dance:
11166 */
11167
11168 /* Make sure possible SIGCHLD is stored in kernel's
11169 * pending signal mask before we call waitpid.
11170 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011171 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011172 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011173 sigfillset(&oldset); /* block all signals, remember old set */
11174 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011175
11176 if (!sigisemptyset(&G.pending_set)) {
11177 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011178 goto restore;
11179 }
11180
11181 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011182/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011183 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011184 debug_printf_exec("checkjobs:%d\n", ret);
11185#if ENABLE_HUSH_JOB
11186 if (waitfor_pipe) {
11187 int rcode = job_exited_or_stopped(waitfor_pipe);
11188 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11189 if (rcode >= 0) {
11190 ret = rcode;
11191 sigprocmask(SIG_SETMASK, &oldset, NULL);
11192 break;
11193 }
11194 }
11195#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011196 /* if ECHILD, there are no children (ret is -1 or 0) */
11197 /* if ret == 0, no children changed state */
11198 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011199 if (errno == ECHILD || ret) {
11200 ret--;
11201 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011202 ret = 0;
11203 sigprocmask(SIG_SETMASK, &oldset, NULL);
11204 break;
11205 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011206 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011207 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11208 /* Note: sigsuspend invokes signal handler */
11209 sigsuspend(&oldset);
11210 restore:
11211 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011212 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011213 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011214 sig = check_and_run_traps();
11215 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011216 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011217 ret = 128 + sig;
11218 break;
11219 }
11220 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11221 }
11222 return ret;
11223}
11224
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011225static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011226{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011227 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011228 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011229
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011230 argv = skip_dash_dash(argv);
11231 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011232 /* Don't care about wait results */
11233 /* Note 1: must wait until there are no more children */
11234 /* Note 2: must be interruptible */
11235 /* Examples:
11236 * $ sleep 3 & sleep 6 & wait
11237 * [1] 30934 sleep 3
11238 * [2] 30935 sleep 6
11239 * [1] Done sleep 3
11240 * [2] Done sleep 6
11241 * $ sleep 3 & sleep 6 & wait
11242 * [1] 30936 sleep 3
11243 * [2] 30937 sleep 6
11244 * [1] Done sleep 3
11245 * ^C <-- after ~4 sec from keyboard
11246 * $
11247 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011248 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011249 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011250
Denys Vlasenko7e675362016-10-28 21:57:31 +020011251 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011252 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011253 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011254#if ENABLE_HUSH_JOB
11255 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011256 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011257 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011258 wait_pipe = parse_jobspec(*argv);
11259 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011260 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011261 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011262 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011263 } else {
11264 /* waiting on "last dead job" removes it */
11265 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011266 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011267 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011268 /* else: parse_jobspec() already emitted error msg */
11269 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011270 }
11271#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011272 /* mimic bash message */
11273 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011274 ret = EXIT_FAILURE;
11275 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011276 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011277
Denys Vlasenko7e675362016-10-28 21:57:31 +020011278 /* Do we have such child? */
11279 ret = waitpid(pid, &status, WNOHANG);
11280 if (ret < 0) {
11281 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011282 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011283 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011284 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011285 /* "wait $!" but last bg task has already exited. Try:
11286 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11287 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011288 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011289 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011290 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011291 } else {
11292 /* Example: "wait 1". mimic bash message */
11293 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011294 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011295 } else {
11296 /* ??? */
11297 bb_perror_msg("wait %s", *argv);
11298 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011299 continue; /* bash checks all argv[] */
11300 }
11301 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011302 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011303 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011304 } else {
11305 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011306 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011307 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011308 if (WIFSIGNALED(status))
11309 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011310 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011311 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011312
11313 return ret;
11314}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011315#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011316
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011317#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11318static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11319{
11320 if (argv[1]) {
11321 def = bb_strtou(argv[1], NULL, 10);
11322 if (errno || def < def_min || argv[2]) {
11323 bb_error_msg("%s: bad arguments", argv[0]);
11324 def = UINT_MAX;
11325 }
11326 }
11327 return def;
11328}
11329#endif
11330
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011331#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011332static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011333{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011334 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011335 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011336 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011337 /* if we came from builtin_continue(), need to undo "= 1" */
11338 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011339 return EXIT_SUCCESS; /* bash compat */
11340 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011341 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011342
11343 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11344 if (depth == UINT_MAX)
11345 G.flag_break_continue = BC_BREAK;
11346 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011347 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011348
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011349 return EXIT_SUCCESS;
11350}
11351
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011352static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011353{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011354 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11355 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011356}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011357#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011358
11359#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011360static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011361{
11362 int rc;
11363
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011364 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011365 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11366 return EXIT_FAILURE; /* bash compat */
11367 }
11368
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011369 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011370
11371 /* bash:
11372 * out of range: wraps around at 256, does not error out
11373 * non-numeric param:
11374 * f() { false; return qwe; }; f; echo $?
11375 * bash: return: qwe: numeric argument required <== we do this
11376 * 255 <== we also do this
11377 */
11378 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11379 return rc;
11380}
11381#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011382
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011383#if ENABLE_HUSH_TIMES
11384static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11385{
11386 static const uint8_t times_tbl[] ALIGN1 = {
11387 ' ', offsetof(struct tms, tms_utime),
11388 '\n', offsetof(struct tms, tms_stime),
11389 ' ', offsetof(struct tms, tms_cutime),
11390 '\n', offsetof(struct tms, tms_cstime),
11391 0
11392 };
11393 const uint8_t *p;
11394 unsigned clk_tck;
11395 struct tms buf;
11396
11397 clk_tck = bb_clk_tck();
11398
11399 times(&buf);
11400 p = times_tbl;
11401 do {
11402 unsigned sec, frac;
11403 unsigned long t;
11404 t = *(clock_t *)(((char *) &buf) + p[1]);
11405 sec = t / clk_tck;
11406 frac = t % clk_tck;
11407 printf("%um%u.%03us%c",
11408 sec / 60, sec % 60,
11409 (frac * 1000) / clk_tck,
11410 p[0]);
11411 p += 2;
11412 } while (*p);
11413
11414 return EXIT_SUCCESS;
11415}
11416#endif
11417
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011418#if ENABLE_HUSH_MEMLEAK
11419static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11420{
11421 void *p;
11422 unsigned long l;
11423
11424# ifdef M_TRIM_THRESHOLD
11425 /* Optional. Reduces probability of false positives */
11426 malloc_trim(0);
11427# endif
11428 /* Crude attempt to find where "free memory" starts,
11429 * sans fragmentation. */
11430 p = malloc(240);
11431 l = (unsigned long)p;
11432 free(p);
11433 p = malloc(3400);
11434 if (l < (unsigned long)p) l = (unsigned long)p;
11435 free(p);
11436
11437
11438# if 0 /* debug */
11439 {
11440 struct mallinfo mi = mallinfo();
11441 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11442 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11443 }
11444# endif
11445
11446 if (!G.memleak_value)
11447 G.memleak_value = l;
11448
11449 l -= G.memleak_value;
11450 if ((long)l < 0)
11451 l = 0;
11452 l /= 1024;
11453 if (l > 127)
11454 l = 127;
11455
11456 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11457 return l;
11458}
11459#endif