blob: e9212cefca7ec5b8763b159c3d6c4abd8a5019ef [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * TODO:
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//config: hush is a small shell. It handles the normal flow control
100//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101//config: case/esac. Redirections, here documents, $((arithmetic))
102//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//config:config HUSH_BASH_SOURCE_CURDIR
127//config: bool "'source' and '.' builtins search current directory after $PATH"
128//config: default n # do not encourage non-standard behavior
129//config: depends on HUSH_BASH_COMPAT
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//config: Enable interactive mode (prompt and command editing).
139//config: Without this, hush simply reads and executes commands
140//config: from stdin just like a shell script from a file.
141//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154//config: command (not entire shell), fg/bg builtins work. Without this option,
155//config: "cmd &" still works by simply spawning a process and immediately
156//config: prompting for next command (or executing next command in a script),
157//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200360#ifndef O_CLOEXEC
361# define O_CLOEXEC 0
362#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100363#ifndef F_DUPFD_CLOEXEC
364# define F_DUPFD_CLOEXEC F_DUPFD
365#endif
366#ifndef PIPE_BUF
367# define PIPE_BUF 4096 /* amount of buffering in a pipe */
368#endif
369
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000370
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100371/* So far, all bash compat is controlled by one config option */
372/* Separate defines document which part of code implements what */
373#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
374#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100375#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
376#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200377#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200378#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100379
380
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200381/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000382#define LEAK_HUNTING 0
383#define BUILD_AS_NOMMU 0
384/* Enable/disable sanity checks. Ok to enable in production,
385 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
386 * Keeping 1 for now even in released versions.
387 */
388#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200389/* Slightly bigger (+200 bytes), but faster hush.
390 * So far it only enables a trick with counting SIGCHLDs and forks,
391 * which allows us to do fewer waitpid's.
392 * (we can detect a case where neither forks were done nor SIGCHLDs happened
393 * and therefore waitpid will return the same result as last time)
394 */
395#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200396/* TODO: implement simplified code for users which do not need ${var%...} ops
397 * So far ${var%...} ops are always enabled:
398 */
399#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000400
401
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000402#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000403# undef BB_MMU
404# undef USE_FOR_NOMMU
405# undef USE_FOR_MMU
406# define BB_MMU 0
407# define USE_FOR_NOMMU(...) __VA_ARGS__
408# define USE_FOR_MMU(...)
409#endif
410
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200411#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100412#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000413/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000414# undef CONFIG_FEATURE_SH_STANDALONE
415# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100417# undef IF_NOT_FEATURE_SH_STANDALONE
418# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000419# define IF_FEATURE_SH_STANDALONE(...)
420# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000421#endif
422
Denis Vlasenko05743d72008-02-10 12:10:08 +0000423#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000424# undef ENABLE_FEATURE_EDITING
425# define ENABLE_FEATURE_EDITING 0
426# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
427# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200428# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
429# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000430#endif
431
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000432/* Do we support ANY keywords? */
433#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000434# define HAS_KEYWORDS 1
435# define IF_HAS_KEYWORDS(...) __VA_ARGS__
436# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000437#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000438# define HAS_KEYWORDS 0
439# define IF_HAS_KEYWORDS(...)
440# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000441#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000442
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000443/* If you comment out one of these below, it will be #defined later
444 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200445#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000446/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200447#define debug_printf_parse(...) do {} while (0)
448#define debug_printf_heredoc(...) do {} while (0)
449#define debug_print_tree(a, b) do {} while (0)
450#define debug_printf_exec(...) do {} while (0)
451#define debug_printf_env(...) do {} while (0)
452#define debug_printf_jobs(...) do {} while (0)
453#define debug_printf_expand(...) do {} while (0)
454#define debug_printf_varexp(...) do {} while (0)
455#define debug_printf_glob(...) do {} while (0)
456#define debug_printf_redir(...) do {} while (0)
457#define debug_printf_list(...) do {} while (0)
458#define debug_printf_subst(...) do {} while (0)
459#define debug_printf_prompt(...) do {} while (0)
460#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000461
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000462#define ERR_PTR ((void*)(long)1)
463
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100464#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000465
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200466#define _SPECIAL_VARS_STR "_*@$!?#"
467#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
468#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100469#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200470/* Support / and // replace ops */
471/* Note that // is stored as \ in "encoded" string representation */
472# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
473# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
474# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
475#else
476# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
477# define VAR_SUBST_OPS "%#:-=+?"
478# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
479#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200480
Denys Vlasenko932b9972018-01-11 12:39:48 +0100481#define SPECIAL_VAR_SYMBOL_STR "\3"
482#define SPECIAL_VAR_SYMBOL 3
483/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
484#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000485
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200486struct variable;
487
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000488static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
489
490/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000491 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000492 */
493#if !BB_MMU
494typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200495 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000496 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000497 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000498} nommu_save_t;
499#endif
500
Denys Vlasenko9b782552010-09-08 13:33:26 +0200501enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000502 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000503#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000504 RES_IF ,
505 RES_THEN ,
506 RES_ELIF ,
507 RES_ELSE ,
508 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000509#endif
510#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000511 RES_FOR ,
512 RES_WHILE ,
513 RES_UNTIL ,
514 RES_DO ,
515 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000516#endif
517#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000518 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000519#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000520#if ENABLE_HUSH_CASE
521 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200522 /* three pseudo-keywords support contrived "case" syntax: */
523 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
524 RES_MATCH , /* "word)" */
525 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000526 RES_ESAC ,
527#endif
528 RES_XXXX ,
529 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200530};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000531
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000532typedef struct o_string {
533 char *data;
534 int length; /* position where data is appended */
535 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200536 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000537 /* At least some part of the string was inside '' or "",
538 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200539 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000540 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200541 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000542} o_string;
543enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200544 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
545 EXP_FLAG_GLOB = 0x2,
546 /* Protect newly added chars against globbing
547 * by prepending \ to *, ?, [, \ */
548 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
549};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000550/* Used for initialization: o_string foo = NULL_O_STRING; */
551#define NULL_O_STRING { NULL }
552
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200553#ifndef debug_printf_parse
554static const char *const assignment_flag[] = {
555 "MAYBE_ASSIGNMENT",
556 "DEFINITELY_ASSIGNMENT",
557 "NOT_ASSIGNMENT",
558 "WORD_IS_KEYWORD",
559};
560#endif
561
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200562/* We almost can use standard FILE api, but we need an ability to move
563 * its fd when redirects coincide with it. No api exists for that
564 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
565 * HFILE is our internal alternative. Only supports reading.
566 * Since we now can, we incorporate linked list of all opened HFILEs
567 * into the struct (used to be a separate mini-list).
568 */
569typedef struct HFILE {
570 char *cur;
571 char *end;
572 struct HFILE *next_hfile;
573 int is_stdin;
574 int fd;
575 char buf[1024];
576} HFILE;
577
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000578typedef struct in_str {
579 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200580 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200581 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200582 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000583} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000584
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200585/* The descrip member of this structure is only used to make
586 * debugging output pretty */
587static const struct {
588 int mode;
589 signed char default_fd;
590 char descrip[3];
591} redir_table[] = {
592 { O_RDONLY, 0, "<" },
593 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
594 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
595 { O_CREAT|O_RDWR, 1, "<>" },
596 { O_RDONLY, 0, "<<" },
597/* Should not be needed. Bogus default_fd helps in debugging */
598/* { O_RDONLY, 77, "<<" }, */
599};
600
Eric Andersen25f27032001-04-26 23:22:31 +0000601struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000602 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000603 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000604 int rd_fd; /* fd to redirect */
605 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
606 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000607 smallint rd_type; /* (enum redir_type) */
608 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000609 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200610 * bit 0: do we need to trim leading tabs?
611 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000612 */
Eric Andersen25f27032001-04-26 23:22:31 +0000613};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000614typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200615 REDIRECT_INPUT = 0,
616 REDIRECT_OVERWRITE = 1,
617 REDIRECT_APPEND = 2,
618 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000619 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200620 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000621
622 REDIRFD_CLOSE = -3,
623 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000624 REDIRFD_TO_FILE = -1,
625 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000626
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000627 HEREDOC_SKIPTABS = 1,
628 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000629} redir_type;
630
Eric Andersen25f27032001-04-26 23:22:31 +0000631
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000632struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000633 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200634 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100635#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100636 unsigned lineno;
637#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200638 smallint cmd_type; /* CMD_xxx */
639#define CMD_NORMAL 0
640#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200641#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
642/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
643 * "export v=t*"
644 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200645# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000646#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200647#if ENABLE_HUSH_FUNCTIONS
648# define CMD_FUNCDEF 3
649#endif
650
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100651 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200652 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
653 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000654#if !BB_MMU
655 char *group_as_string;
656#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000657#if ENABLE_HUSH_FUNCTIONS
658 struct function *child_func;
659/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200660 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000661 * When we execute "f1() {a;}" cmd, we create new function and clear
662 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200663 * When we execute "f1() {b;}", we notice that f1 exists,
664 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000665 * we put those fields back into cmd->xxx
666 * (struct function has ->parent_cmd ptr to facilitate that).
667 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
668 * Without this trick, loop would execute a;b;b;b;...
669 * instead of correct sequence a;b;a;b;...
670 * When command is freed, it severs the link
671 * (sets ->child_func->parent_cmd to NULL).
672 */
673#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000674 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000675/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
676 * and on execution these are substituted with their values.
677 * Substitution can make _several_ words out of one argv[n]!
678 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000679 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000680 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000681 struct redir_struct *redirects; /* I/O redirections */
682};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000683/* Is there anything in this command at all? */
684#define IS_NULL_CMD(cmd) \
685 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
686
Eric Andersen25f27032001-04-26 23:22:31 +0000687struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000688 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000689 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000690 int alive_cmds; /* number of commands running (not exited) */
691 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000692#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100693 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000694 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000695 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000696#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000697 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000698 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000699 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
700 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000701};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000702typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100703 PIPE_SEQ = 0,
704 PIPE_AND = 1,
705 PIPE_OR = 2,
706 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000707} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000708/* Is there anything in this pipe at all? */
709#define IS_NULL_PIPE(pi) \
710 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000711
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000712/* This holds pointers to the various results of parsing */
713struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000714 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000715 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000716 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000717 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000718 /* last command in pipe (being constructed right now) */
719 struct command *command;
720 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000721 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200722 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000723#if !BB_MMU
724 o_string as_string;
725#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200726 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000727#if HAS_KEYWORDS
728 smallint ctx_res_w;
729 smallint ctx_inverted; /* "! cmd | cmd" */
730#if ENABLE_HUSH_CASE
731 smallint ctx_dsemicolon; /* ";;" seen */
732#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000733 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
734 int old_flag;
735 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000736 * example: "if pipe1; pipe2; then pipe3; fi"
737 * when we see "if" or "then", we malloc and copy current context,
738 * and make ->stack point to it. then we parse pipeN.
739 * when closing "then" / fi" / whatever is found,
740 * we move list_head into ->stack->command->group,
741 * copy ->stack into current context, and delete ->stack.
742 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000743 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000744 struct parse_context *stack;
745#endif
746};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200747enum {
748 MAYBE_ASSIGNMENT = 0,
749 DEFINITELY_ASSIGNMENT = 1,
750 NOT_ASSIGNMENT = 2,
751 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
752 WORD_IS_KEYWORD = 3,
753};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000754
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000755/* On program start, environ points to initial environment.
756 * putenv adds new pointers into it, unsetenv removes them.
757 * Neither of these (de)allocates the strings.
758 * setenv allocates new strings in malloc space and does putenv,
759 * and thus setenv is unusable (leaky) for shell's purposes */
760#define setenv(...) setenv_is_leaky_dont_use()
761struct variable {
762 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000763 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000764 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200765 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000766 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000767 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000768};
769
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000770enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000771 BC_BREAK = 1,
772 BC_CONTINUE = 2,
773};
774
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000775#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000776struct function {
777 struct function *next;
778 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000779 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000780 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200781# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000782 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200783# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000784};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000785#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000786
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000787
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100788/* set -/+o OPT support. (TODO: make it optional)
789 * bash supports the following opts:
790 * allexport off
791 * braceexpand on
792 * emacs on
793 * errexit off
794 * errtrace off
795 * functrace off
796 * hashall on
797 * histexpand off
798 * history on
799 * ignoreeof off
800 * interactive-comments on
801 * keyword off
802 * monitor on
803 * noclobber off
804 * noexec off
805 * noglob off
806 * nolog off
807 * notify off
808 * nounset off
809 * onecmd off
810 * physical off
811 * pipefail off
812 * posix off
813 * privileged off
814 * verbose off
815 * vi off
816 * xtrace off
817 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800818static const char o_opt_strings[] ALIGN1 =
819 "pipefail\0"
820 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200821 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800822#if ENABLE_HUSH_MODE_X
823 "xtrace\0"
824#endif
825 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100826enum {
827 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800828 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200829 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800830#if ENABLE_HUSH_MODE_X
831 OPT_O_XTRACE,
832#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100833 NUM_OPT_O
834};
835
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000836/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000837/* Sorted roughly by size (smaller offsets == smaller code) */
838struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000839 /* interactive_fd != 0 means we are an interactive shell.
840 * If we are, then saved_tty_pgrp can also be != 0, meaning
841 * that controlling tty is available. With saved_tty_pgrp == 0,
842 * job control still works, but terminal signals
843 * (^C, ^Z, ^Y, ^\) won't work at all, and background
844 * process groups can only be created with "cmd &".
845 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
846 * to give tty to the foreground process group,
847 * and will take it back when the group is stopped (^Z)
848 * or killed (^C).
849 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850#if ENABLE_HUSH_INTERACTIVE
851 /* 'interactive_fd' is a fd# open to ctty, if we have one
852 * _AND_ if we decided to act interactively */
853 int interactive_fd;
854 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200855 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000856# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000857#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000858# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000859#endif
860#if ENABLE_FEATURE_EDITING
861 line_input_t *line_input_state;
862#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000863 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200864 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000865 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200866#if ENABLE_HUSH_RANDOM_SUPPORT
867 random_t random_gen;
868#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000869#if ENABLE_HUSH_JOB
870 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100871 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000872 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000873 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400874# define G_saved_tty_pgrp (G.saved_tty_pgrp)
875#else
876# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000877#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200878 /* How deeply are we in context where "set -e" is ignored */
879 int errexit_depth;
880 /* "set -e" rules (do we follow them correctly?):
881 * Exit if pipe, list, or compound command exits with a non-zero status.
882 * Shell does not exit if failed command is part of condition in
883 * if/while, part of && or || list except the last command, any command
884 * in a pipe but the last, or if the command's return value is being
885 * inverted with !. If a compound command other than a subshell returns a
886 * non-zero status because a command failed while -e was being ignored, the
887 * shell does not exit. A trap on ERR, if set, is executed before the shell
888 * exits [ERR is a bashism].
889 *
890 * If a compound command or function executes in a context where -e is
891 * ignored, none of the commands executed within are affected by the -e
892 * setting. If a compound command or function sets -e while executing in a
893 * context where -e is ignored, that setting does not have any effect until
894 * the compound command or the command containing the function call completes.
895 */
896
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100897 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100898#if ENABLE_HUSH_MODE_X
899# define G_x_mode (G.o_opt[OPT_O_XTRACE])
900#else
901# define G_x_mode 0
902#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200903#if ENABLE_HUSH_INTERACTIVE
904 smallint promptmode; /* 0: PS1, 1: PS2 */
905#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000906 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000907#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000908 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000909#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000910#if ENABLE_HUSH_FUNCTIONS
911 /* 0: outside of a function (or sourced file)
912 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000913 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000914 */
915 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200916# define G_flag_return_in_progress (G.flag_return_in_progress)
917#else
918# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000919#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000920 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200921 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000922 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200923 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200924 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100925#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000926 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000927 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100928# define G_global_args_malloced (G.global_args_malloced)
929#else
930# define G_global_args_malloced 0
931#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000932 /* how many non-NULL argv's we have. NB: $# + 1 */
933 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000934 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000935#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000936 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000937#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000938#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000939 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000940 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000941#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200942#if ENABLE_HUSH_GETOPTS
943 unsigned getopt_count;
944#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000945 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200946 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000947 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200948 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200949 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200950 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200951 unsigned var_nest_level;
952#if ENABLE_HUSH_FUNCTIONS
953# if ENABLE_HUSH_LOCAL
954 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200955# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200956 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000957#endif
Denys Vlasenko9dda9272018-07-27 14:12:05 +0200958#if ENABLE_HUSH_MODE_X
959 unsigned x_mode_depth;
960#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000961 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200962#if ENABLE_HUSH_FAST
963 unsigned count_SIGCHLD;
964 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200965 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200966#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100967#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100968 unsigned lineno;
969 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100970#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200971 HFILE *HFILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200972 /* Which signals have non-DFL handler (even with no traps set)?
973 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200974 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200975 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200976 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200977 * Other than these two times, never modified.
978 */
979 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200980#if ENABLE_HUSH_JOB
981 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100982# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200983#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200984# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200985#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100986#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000987 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100988# define G_traps G.traps
989#else
990# define G_traps ((char**)NULL)
991#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200992 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100993#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000994 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100995#endif
996#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000997 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000998#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200999 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +02001000#if ENABLE_FEATURE_EDITING
1001 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1002#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001003};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001004#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001005/* Not #defining name to G.name - this quickly gets unwieldy
1006 * (too many defines). Also, I actually prefer to see when a variable
1007 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001008#define INIT_G() do { \
1009 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001010 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1011 sigfillset(&G.sa.sa_mask); \
1012 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001013} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001014
1015
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001016/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001017static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001018#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001019static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001020#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001021static int builtin_eval(char **argv) FAST_FUNC;
1022static int builtin_exec(char **argv) FAST_FUNC;
1023static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001024#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001025static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001026#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001027#if ENABLE_HUSH_READONLY
1028static int builtin_readonly(char **argv) FAST_FUNC;
1029#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001030#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001031static int builtin_fg_bg(char **argv) FAST_FUNC;
1032static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001033#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001034#if ENABLE_HUSH_GETOPTS
1035static int builtin_getopts(char **argv) FAST_FUNC;
1036#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001037#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001038static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001039#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001040#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001041static int builtin_history(char **argv) FAST_FUNC;
1042#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001043#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001044static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001045#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001046#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001047static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001048#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001049#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001050static int builtin_printf(char **argv) FAST_FUNC;
1051#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001052static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001053#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001055#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001056#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001057static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001058#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_shift(char **argv) FAST_FUNC;
1060static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001061#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001062static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001063#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001064#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001065static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001066#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001067#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001068static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001069#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001070#if ENABLE_HUSH_TIMES
1071static int builtin_times(char **argv) FAST_FUNC;
1072#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001073static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001074#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001075static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001076#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001077#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001078static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001079#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001080#if ENABLE_HUSH_KILL
1081static int builtin_kill(char **argv) FAST_FUNC;
1082#endif
1083#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001084static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001085#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001086#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001087static int builtin_break(char **argv) FAST_FUNC;
1088static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001089#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001090#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001091static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001092#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001093
1094/* Table of built-in functions. They can be forked or not, depending on
1095 * context: within pipes, they fork. As simple commands, they do not.
1096 * When used in non-forking context, they can change global variables
1097 * in the parent shell process. If forked, of course they cannot.
1098 * For example, 'unset foo | whatever' will parse and run, but foo will
1099 * still be set at the end. */
1100struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001101 const char *b_cmd;
1102 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001103#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001104 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001105# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001106#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001107# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001108#endif
1109};
1110
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001111static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001112 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001113 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001114#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001115 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001116#endif
1117#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001118 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001119#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001120 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001122 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001123#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001124 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1125 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001126 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001127#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001128 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001129#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001130#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001131 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001132#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001133#if ENABLE_HUSH_GETOPTS
1134 BLTIN("getopts" , builtin_getopts , NULL),
1135#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001136#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001137 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001138#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001139#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001140 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001141#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001142#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001143 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001144#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001145#if ENABLE_HUSH_KILL
1146 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1147#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001148#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001149 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001150#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001151#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001152 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001153#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001154#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001156#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001157#if ENABLE_HUSH_READONLY
1158 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1159#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001160#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001161 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001162#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001163#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001164 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001165#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001166 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001167#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001168 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001169#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001170#if ENABLE_HUSH_TIMES
1171 BLTIN("times" , builtin_times , NULL),
1172#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001173#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001174 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001175#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001176 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001177#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001178 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001179#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001180#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001181 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001182#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001183#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001184 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001185#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001186#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001187 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001188#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001189#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001190 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001191#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001192};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001193/* These builtins won't be used if we are on NOMMU and need to re-exec
1194 * (it's cheaper to run an external program in this case):
1195 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001196static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001197#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001198 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001199#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001200#if BASH_TEST2
1201 BLTIN("[[" , builtin_test , NULL),
1202#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001203#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001204 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001205#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001206#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001207 BLTIN("printf" , builtin_printf , NULL),
1208#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001209 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001210#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001211 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001212#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001213};
1214
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001215
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001216/* Debug printouts.
1217 */
1218#if HUSH_DEBUG
1219/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001220# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001221# define debug_enter() (G.debug_indent++)
1222# define debug_leave() (G.debug_indent--)
1223#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001224# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001225# define debug_enter() ((void)0)
1226# define debug_leave() ((void)0)
1227#endif
1228
1229#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001230# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001231#endif
1232
1233#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001234# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001235#endif
1236
Denys Vlasenko3675c372018-07-23 16:31:21 +02001237#ifndef debug_printf_heredoc
1238# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1239#endif
1240
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001241#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001242#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001243#endif
1244
1245#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001246# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001247#endif
1248
1249#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001250# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001251# define DEBUG_JOBS 1
1252#else
1253# define DEBUG_JOBS 0
1254#endif
1255
1256#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001257# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258# define DEBUG_EXPAND 1
1259#else
1260# define DEBUG_EXPAND 0
1261#endif
1262
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001263#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001264# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001265#endif
1266
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001267#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001268# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001269# define DEBUG_GLOB 1
1270#else
1271# define DEBUG_GLOB 0
1272#endif
1273
Denys Vlasenko2db74612017-07-07 22:07:28 +02001274#ifndef debug_printf_redir
1275# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1276#endif
1277
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001278#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001279# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001280#endif
1281
1282#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001283# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001284#endif
1285
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001286#ifndef debug_printf_prompt
1287# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1288#endif
1289
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001290#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001291# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001292# define DEBUG_CLEAN 1
1293#else
1294# define DEBUG_CLEAN 0
1295#endif
1296
1297#if DEBUG_EXPAND
1298static void debug_print_strings(const char *prefix, char **vv)
1299{
1300 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001301 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001302 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001303 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001304}
1305#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001306# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001307#endif
1308
1309
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001310/* Leak hunting. Use hush_leaktool.sh for post-processing.
1311 */
1312#if LEAK_HUNTING
1313static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001314{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001315 void *ptr = xmalloc((size + 0xff) & ~0xff);
1316 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1317 return ptr;
1318}
1319static void *xxrealloc(int lineno, void *ptr, size_t size)
1320{
1321 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1322 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1323 return ptr;
1324}
1325static char *xxstrdup(int lineno, const char *str)
1326{
1327 char *ptr = xstrdup(str);
1328 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1329 return ptr;
1330}
1331static void xxfree(void *ptr)
1332{
1333 fdprintf(2, "free %p\n", ptr);
1334 free(ptr);
1335}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001336# define xmalloc(s) xxmalloc(__LINE__, s)
1337# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1338# define xstrdup(s) xxstrdup(__LINE__, s)
1339# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001340#endif
1341
1342
1343/* Syntax and runtime errors. They always abort scripts.
1344 * In interactive use they usually discard unparsed and/or unexecuted commands
1345 * and return to the prompt.
1346 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1347 */
1348#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001349# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001350# define syntax_error(lineno, msg) syntax_error(msg)
1351# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1352# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1353# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1354# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001355#endif
1356
Denys Vlasenko39701202017-08-02 19:44:05 +02001357static void die_if_script(void)
1358{
1359 if (!G_interactive_fd) {
1360 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1361 xfunc_error_retval = G.last_exitcode;
1362 xfunc_die();
1363 }
1364}
1365
1366static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001367{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001368 va_list p;
1369
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001370#if HUSH_DEBUG >= 2
1371 bb_error_msg("hush.c:%u", lineno);
1372#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001373 va_start(p, fmt);
1374 bb_verror_msg(fmt, p, NULL);
1375 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001376 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001377}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001378
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001379static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001380{
1381 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001382 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001383 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001384 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001385 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001386}
1387
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001388static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001389{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001390 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001391 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001392}
1393
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001394static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001395{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001396 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001397//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1398// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001399}
1400
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001401static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001402{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001403 char msg[2] = { ch, '\0' };
1404 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001405}
1406
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001407static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001408{
1409 char msg[2];
1410 msg[0] = ch;
1411 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001412#if HUSH_DEBUG >= 2
1413 bb_error_msg("hush.c:%u", lineno);
1414#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001415 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001416 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001417}
1418
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001419#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001420# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001421# undef syntax_error
1422# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001423# undef syntax_error_unterm_ch
1424# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001425# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001426#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001427# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001428# define syntax_error(msg) syntax_error(__LINE__, msg)
1429# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1430# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1431# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1432# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001433#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001434
Denis Vlasenko552433b2009-04-04 19:29:21 +00001435
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001436#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001437static void cmdedit_update_prompt(void);
1438#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001439# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001440#endif
1441
1442
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001443/* Utility functions
1444 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001445/* Replace each \x with x in place, return ptr past NUL. */
1446static char *unbackslash(char *src)
1447{
Denys Vlasenko71885402009-09-24 01:44:13 +02001448 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001449 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001450 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001451 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001452 if (*src != '\0') {
1453 /* \x -> x */
1454 *dst++ = *src++;
1455 continue;
1456 }
1457 /* else: "\<nul>". Do not delete this backslash.
1458 * Testcase: eval 'echo ok\'
1459 */
1460 *dst++ = '\\';
1461 /* fallthrough */
1462 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001463 if ((*dst++ = *src++) == '\0')
1464 break;
1465 }
1466 return dst;
1467}
1468
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001469static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001470{
1471 int i;
1472 unsigned count1;
1473 unsigned count2;
1474 char **v;
1475
1476 v = strings;
1477 count1 = 0;
1478 if (v) {
1479 while (*v) {
1480 count1++;
1481 v++;
1482 }
1483 }
1484 count2 = 0;
1485 v = add;
1486 while (*v) {
1487 count2++;
1488 v++;
1489 }
1490 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1491 v[count1 + count2] = NULL;
1492 i = count2;
1493 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001494 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001495 return v;
1496}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001497#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001498static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1499{
1500 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1501 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1502 return ptr;
1503}
1504#define add_strings_to_strings(strings, add, need_to_dup) \
1505 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1506#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001507
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001508/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001509static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001510{
1511 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001512 v[0] = add;
1513 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001514 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001515}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001516#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001517static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1518{
1519 char **ptr = add_string_to_strings(strings, add);
1520 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1521 return ptr;
1522}
1523#define add_string_to_strings(strings, add) \
1524 xx_add_string_to_strings(__LINE__, strings, add)
1525#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001526
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001527static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001528{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001529 char **v;
1530
1531 if (!strings)
1532 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001533 v = strings;
1534 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001535 free(*v);
1536 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001537 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001538 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001539}
1540
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001541static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001542{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001543 int newfd;
1544 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001545 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1546 if (newfd >= 0) {
1547 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1548 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1549 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001550 if (errno == EBUSY)
1551 goto repeat;
1552 if (errno == EINTR)
1553 goto repeat;
1554 }
1555 return newfd;
1556}
1557
Denys Vlasenko657e9002017-07-30 23:34:04 +02001558static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001559{
1560 int newfd;
1561 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001562 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001563 if (newfd < 0) {
1564 if (errno == EBUSY)
1565 goto repeat;
1566 if (errno == EINTR)
1567 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001568 /* fd was not open? */
1569 if (errno == EBADF)
1570 return fd;
1571 xfunc_die();
1572 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001573 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1574 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001575 close(fd);
1576 return newfd;
1577}
1578
1579
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001580/* Manipulating HFILEs */
1581static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001582{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001583 HFILE *fp;
1584 int fd;
1585
1586 fd = STDIN_FILENO;
1587 if (name) {
1588 fd = open(name, O_RDONLY | O_CLOEXEC);
1589 if (fd < 0)
1590 return NULL;
1591 if (O_CLOEXEC == 0) /* ancient libc */
1592 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001593 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001594
1595 fp = xmalloc(sizeof(*fp));
1596 fp->is_stdin = (name == NULL);
1597 fp->fd = fd;
1598 fp->cur = fp->end = fp->buf;
1599 fp->next_hfile = G.HFILE_list;
1600 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001601 return fp;
1602}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001603static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001604{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001605 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001606 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001607 HFILE *cur = *pp;
1608 if (cur == fp) {
1609 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001610 break;
1611 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001612 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001613 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001614 if (fp->fd >= 0)
1615 close(fp->fd);
1616 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001617}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001618static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001619{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001620 int n;
1621
1622 if (fp->fd < 0) {
1623 /* Already saw EOF */
1624 return EOF;
1625 }
1626 /* Try to buffer more input */
1627 fp->cur = fp->buf;
1628 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1629 if (n < 0) {
1630 bb_perror_msg("read error");
1631 n = 0;
1632 }
1633 fp->end = fp->buf + n;
1634 if (n == 0) {
1635 /* EOF/error */
1636 close(fp->fd);
1637 fp->fd = -1;
1638 return EOF;
1639 }
1640 return (unsigned char)(*fp->cur++);
1641}
1642/* Inlined for common case of non-empty buffer.
1643 */
1644static ALWAYS_INLINE int hfgetc(HFILE *fp)
1645{
1646 if (fp->cur < fp->end)
1647 return (unsigned char)(*fp->cur++);
1648 /* Buffer empty */
1649 return refill_HFILE_and_getc(fp);
1650}
1651static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1652{
1653 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001654 while (fl) {
1655 if (fd == fl->fd) {
1656 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001657 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001658 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001659 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001660 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001661 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001662 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001663 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001664}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001665#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001666static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001667{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001668 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001669 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001670 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001671 * It is disastrous if we share memory with a vforked parent.
1672 * I'm not sure we never come here after vfork.
1673 * Therefore just close fd, nothing more.
1674 */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001675 /*hfclose(fl); - unsafe */
1676 if (fl->fd >= 0)
1677 close(fl->fd);
1678 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001679 }
1680}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001681#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001682static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001683{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001684 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001685 while (fl) {
1686 if (fl->fd == fd)
1687 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001688 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001689 }
1690 return 0;
1691}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001692
1693
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001694/* Helpers for setting new $n and restoring them back
1695 */
1696typedef struct save_arg_t {
1697 char *sv_argv0;
1698 char **sv_g_argv;
1699 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001700 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001701} save_arg_t;
1702
1703static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1704{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001705 sv->sv_argv0 = argv[0];
1706 sv->sv_g_argv = G.global_argv;
1707 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001708 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001709
1710 argv[0] = G.global_argv[0]; /* retain $0 */
1711 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001712 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001713
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001714 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001715}
1716
1717static void restore_G_args(save_arg_t *sv, char **argv)
1718{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001719#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001720 if (G.global_args_malloced) {
1721 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001722 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001723 while (*++pp) /* note: does not free $0 */
1724 free(*pp);
1725 free(G.global_argv);
1726 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001727#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001728 argv[0] = sv->sv_argv0;
1729 G.global_argv = sv->sv_g_argv;
1730 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001731 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001732}
1733
1734
Denis Vlasenkod5762932009-03-31 11:22:57 +00001735/* Basic theory of signal handling in shell
1736 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001737 * This does not describe what hush does, rather, it is current understanding
1738 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001739 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1740 *
1741 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1742 * is finished or backgrounded. It is the same in interactive and
1743 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001744 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001745 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001746 * backgrounds (i.e. stops) or kills all members of currently running
1747 * pipe.
1748 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001749 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001750 * or by SIGINT in interactive shell.
1751 *
1752 * Trap handlers will execute even within trap handlers. (right?)
1753 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001754 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1755 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001756 *
1757 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001758 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001759 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001760 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001761 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001762 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001763 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001764 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001765 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001766 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001767 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001768 *
1769 * SIGQUIT: ignore
1770 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001771 * SIGHUP (interactive):
1772 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001773 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001774 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1775 * that all pipe members are stopped. Try this in bash:
1776 * while :; do :; done - ^Z does not background it
1777 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001778 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001779 * of the command line, show prompt. NB: ^C does not send SIGINT
1780 * to interactive shell while shell is waiting for a pipe,
1781 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001782 * Example 1: this waits 5 sec, but does not execute ls:
1783 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1784 * Example 2: this does not wait and does not execute ls:
1785 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1786 * Example 3: this does not wait 5 sec, but executes ls:
1787 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001788 * Example 4: this does not wait and does not execute ls:
1789 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001790 *
1791 * (What happens to signals which are IGN on shell start?)
1792 * (What happens with signal mask on shell start?)
1793 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001794 * Old implementation
1795 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001796 * We use in-kernel pending signal mask to determine which signals were sent.
1797 * We block all signals which we don't want to take action immediately,
1798 * i.e. we block all signals which need to have special handling as described
1799 * above, and all signals which have traps set.
1800 * After each pipe execution, we extract any pending signals via sigtimedwait()
1801 * and act on them.
1802 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001803 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001804 * sigset_t blocked_set: current blocked signal set
1805 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001806 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001807 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001808 * "trap 'cmd' SIGxxx":
1809 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001810 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001811 * unblock signals with special interactive handling
1812 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001813 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001814 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001815 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001816 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001817 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001818 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001819 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001820 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001821 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001822 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001823 * Standard says "When a subshell is entered, traps that are not being ignored
1824 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001825 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001826 *
1827 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001828 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001829 * masked signals are not visible!
1830 *
1831 * New implementation
1832 * ==================
1833 * We record each signal we are interested in by installing signal handler
1834 * for them - a bit like emulating kernel pending signal mask in userspace.
1835 * We are interested in: signals which need to have special handling
1836 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001837 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001838 * After each pipe execution, we extract any pending signals
1839 * and act on them.
1840 *
1841 * unsigned special_sig_mask: a mask of shell-special signals.
1842 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1843 * char *traps[sig] if trap for sig is set (even if it's '').
1844 * sigset_t pending_set: set of sigs we received.
1845 *
1846 * "trap - SIGxxx":
1847 * if sig is in special_sig_mask, set handler back to:
1848 * record_pending_signo, or to IGN if it's a tty stop signal
1849 * if sig is in fatal_sig_mask, set handler back to sigexit.
1850 * else: set handler back to SIG_DFL
1851 * "trap 'cmd' SIGxxx":
1852 * set handler to record_pending_signo.
1853 * "trap '' SIGxxx":
1854 * set handler to SIG_IGN.
1855 * after [v]fork, if we plan to be a shell:
1856 * set signals with special interactive handling to SIG_DFL
1857 * (because child shell is not interactive),
1858 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1859 * after [v]fork, if we plan to exec:
1860 * POSIX says fork clears pending signal mask in child - no need to clear it.
1861 *
1862 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1863 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1864 *
1865 * Note (compat):
1866 * Standard says "When a subshell is entered, traps that are not being ignored
1867 * are set to the default actions". bash interprets it so that traps which
1868 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001869 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001870enum {
1871 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001872 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001873 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001874 | (1 << SIGHUP)
1875 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001876 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001877#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001878 | (1 << SIGTTIN)
1879 | (1 << SIGTTOU)
1880 | (1 << SIGTSTP)
1881#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001882 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001883};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001884
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001885static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001886{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001887 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001888#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001889 if (sig == SIGCHLD) {
1890 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001891//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001892 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001893#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001894}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001895
Denys Vlasenko0806e402011-05-12 23:06:20 +02001896static sighandler_t install_sighandler(int sig, sighandler_t handler)
1897{
1898 struct sigaction old_sa;
1899
1900 /* We could use signal() to install handlers... almost:
1901 * except that we need to mask ALL signals while handlers run.
1902 * I saw signal nesting in strace, race window isn't small.
1903 * SA_RESTART is also needed, but in Linux, signal()
1904 * sets SA_RESTART too.
1905 */
1906 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1907 /* sigfillset(&G.sa.sa_mask); - already done */
1908 /* G.sa.sa_flags = SA_RESTART; - already done */
1909 G.sa.sa_handler = handler;
1910 sigaction(sig, &G.sa, &old_sa);
1911 return old_sa.sa_handler;
1912}
1913
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001914static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001915
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001916static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001917static void restore_ttypgrp_and__exit(void)
1918{
1919 /* xfunc has failed! die die die */
1920 /* no EXIT traps, this is an escape hatch! */
1921 G.exiting = 1;
1922 hush_exit(xfunc_error_retval);
1923}
1924
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001925#if ENABLE_HUSH_JOB
1926
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001927/* Needed only on some libc:
1928 * It was observed that on exit(), fgetc'ed buffered data
1929 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1930 * With the net effect that even after fork(), not vfork(),
1931 * exit() in NOEXECed applet in "sh SCRIPT":
1932 * noexec_applet_here
1933 * echo END_OF_SCRIPT
1934 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1935 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001936 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001937 * and in `cmd` handling.
1938 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1939 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001940static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001941static void fflush_and__exit(void)
1942{
1943 fflush_all();
1944 _exit(xfunc_error_retval);
1945}
1946
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001947/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001948# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001949/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001950# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001951
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001952/* Restores tty foreground process group, and exits.
1953 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001954 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001955 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001956 * We also call it if xfunc is exiting.
1957 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001958static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001959static void sigexit(int sig)
1960{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001961 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001962 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001963 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1964 /* Disable all signals: job control, SIGPIPE, etc.
1965 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1966 */
1967 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001968 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001969 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001970
1971 /* Not a signal, just exit */
1972 if (sig <= 0)
1973 _exit(- sig);
1974
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001975 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001976}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001977#else
1978
Denys Vlasenko8391c482010-05-22 17:50:43 +02001979# define disable_restore_tty_pgrp_on_exit() ((void)0)
1980# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001981
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001982#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001983
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001984static sighandler_t pick_sighandler(unsigned sig)
1985{
1986 sighandler_t handler = SIG_DFL;
1987 if (sig < sizeof(unsigned)*8) {
1988 unsigned sigmask = (1 << sig);
1989
1990#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001991 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001992 if (G_fatal_sig_mask & sigmask)
1993 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001994 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001995#endif
1996 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001997 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001998 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001999 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002000 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002001 * in an endless loop when we try to do some
2002 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002003 */
2004 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2005 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002006 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002007 }
2008 return handler;
2009}
2010
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002011/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002012static void hush_exit(int exitcode)
2013{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002014#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2015 save_history(G.line_input_state);
2016#endif
2017
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002018 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002019 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002020 char *argv[3];
2021 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002022 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002023 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002024 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002025 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002026 * "trap" will still show it, if executed
2027 * in the handler */
2028 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002029 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002030
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002031#if ENABLE_FEATURE_CLEAN_UP
2032 {
2033 struct variable *cur_var;
2034 if (G.cwd != bb_msg_unknown)
2035 free((char*)G.cwd);
2036 cur_var = G.top_var;
2037 while (cur_var) {
2038 struct variable *tmp = cur_var;
2039 if (!cur_var->max_len)
2040 free(cur_var->varstr);
2041 cur_var = cur_var->next;
2042 free(tmp);
2043 }
2044 }
2045#endif
2046
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002047 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002048#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002049 sigexit(- (exitcode & 0xff));
2050#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002051 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002052#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002053}
2054
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002055
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002056//TODO: return a mask of ALL handled sigs?
2057static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002058{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002059 int last_sig = 0;
2060
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002061 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002062 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002063
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002064 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002065 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002066 sig = 0;
2067 do {
2068 sig++;
2069 if (sigismember(&G.pending_set, sig)) {
2070 sigdelset(&G.pending_set, sig);
2071 goto got_sig;
2072 }
2073 } while (sig < NSIG);
2074 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002075 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002076 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002077 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002078 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002079 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002080 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002081 char *argv[3];
2082 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002083 argv[1] = xstrdup(G_traps[sig]);
2084 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002085 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002086 save_rcode = G.last_exitcode;
2087 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002088 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002089//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002090 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002091 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002092 } /* else: "" trap, ignoring signal */
2093 continue;
2094 }
2095 /* not a trap: special action */
2096 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002097 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002098 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002099 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002100 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002101 break;
2102#if ENABLE_HUSH_JOB
2103 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002104//TODO: why are we doing this? ash and dash don't do this,
2105//they have no handler for SIGHUP at all,
2106//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002107 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002108 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002109 /* bash is observed to signal whole process groups,
2110 * not individual processes */
2111 for (job = G.job_list; job; job = job->next) {
2112 if (job->pgrp <= 0)
2113 continue;
2114 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2115 if (kill(- job->pgrp, SIGHUP) == 0)
2116 kill(- job->pgrp, SIGCONT);
2117 }
2118 sigexit(SIGHUP);
2119 }
2120#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002121#if ENABLE_HUSH_FAST
2122 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002123 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002124 G.count_SIGCHLD++;
2125//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2126 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002127 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002128 * This simplifies wait builtin a bit.
2129 */
2130 break;
2131#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002132 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002133 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002134 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002135 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002136 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002137 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002138 * in interactive shell, because TERM is ignored.
2139 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002140 break;
2141 }
2142 }
2143 return last_sig;
2144}
2145
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002146
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002147static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002148{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002149 if (force || G.cwd == NULL) {
2150 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2151 * we must not try to free(bb_msg_unknown) */
2152 if (G.cwd == bb_msg_unknown)
2153 G.cwd = NULL;
2154 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2155 if (!G.cwd)
2156 G.cwd = bb_msg_unknown;
2157 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002158 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002159}
2160
Denis Vlasenko83506862007-11-23 13:11:42 +00002161
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002162/*
2163 * Shell and environment variable support
2164 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002165static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002166{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002167 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002168 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002169
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002170 pp = &G.top_var;
2171 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002172 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002173 return pp;
2174 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002175 }
2176 return NULL;
2177}
2178
Denys Vlasenko03dad222010-01-12 23:29:57 +01002179static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002180{
Denys Vlasenko29082232010-07-16 13:52:32 +02002181 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002182 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002183
2184 if (G.expanded_assignments) {
2185 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002186 while (*cpp) {
2187 char *cp = *cpp;
2188 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2189 return cp + len + 1;
2190 cpp++;
2191 }
2192 }
2193
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002194 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002195 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002196 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002197
Denys Vlasenkodea47882009-10-09 15:40:49 +02002198 if (strcmp(name, "PPID") == 0)
2199 return utoa(G.root_ppid);
2200 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002201#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002202 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002203 return utoa(next_random(&G.random_gen));
2204#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002205 return NULL;
2206}
2207
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002208static void handle_changed_special_names(const char *name, unsigned name_len)
2209{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002210 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2211 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2212 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002213 cmdedit_update_prompt();
2214 return;
2215 }
2216
2217 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2218 && name_len == 6
2219 ) {
2220#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002221 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002222 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002223 return;
2224 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002225#endif
2226#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002227 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002228 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002229 return;
2230 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002231#endif
2232 }
2233}
2234
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002235/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002236 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002237 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002238#define SETFLAG_EXPORT (1 << 0)
2239#define SETFLAG_UNEXPORT (1 << 1)
2240#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002241#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002242static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002243{
Denys Vlasenko61407802018-04-04 21:14:28 +02002244 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002245 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002246 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002247 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002248 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002249 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002250
Denis Vlasenko950bd722009-04-21 11:23:56 +00002251 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002252 if (HUSH_DEBUG && !eq_sign)
2253 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002254
Denis Vlasenko950bd722009-04-21 11:23:56 +00002255 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002256 cur_pp = &G.top_var;
2257 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002258 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002259 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002260 continue;
2261 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002262
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002263 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002264 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002265 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002267//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2268//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002269 return -1;
2270 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002271 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002272 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2273 *eq_sign = '\0';
2274 unsetenv(str);
2275 *eq_sign = '=';
2276 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002277 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002278 /* bash 3.2.33(1) and exported vars:
2279 * # export z=z
2280 * # f() { local z=a; env | grep ^z; }
2281 * # f
2282 * z=a
2283 * # env | grep ^z
2284 * z=z
2285 */
2286 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002287 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002288 /* New variable is local ("local VAR=VAL" or
2289 * "VAR=VAL cmd")
2290 * and existing one is global, or local
2291 * on a lower level that new one.
2292 * Remove it from global variable list:
2293 */
2294 *cur_pp = cur->next;
2295 if (G.shadowed_vars_pp) {
2296 /* Save in "shadowed" list */
2297 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2298 cur->flg_export ? "exported " : "",
2299 cur->varstr, cur->var_nest_level, str, local_lvl
2300 );
2301 cur->next = *G.shadowed_vars_pp;
2302 *G.shadowed_vars_pp = cur;
2303 } else {
2304 /* Came from pseudo_exec_argv(), no need to save: delete it */
2305 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2306 cur->flg_export ? "exported " : "",
2307 cur->varstr, cur->var_nest_level, str, local_lvl
2308 );
2309 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2310 free_me = cur->varstr; /* then free it later */
2311 free(cur);
2312 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002313 break;
2314 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002315
Denis Vlasenko950bd722009-04-21 11:23:56 +00002316 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002317 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002318 free_and_exp:
2319 free(str);
2320 goto exp;
2321 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002322
2323 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002324 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002325 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002326 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002327 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002328 strcpy(cur->varstr, str);
2329 goto free_and_exp;
2330 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002331 /* Can't reuse */
2332 cur->max_len = 0;
2333 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002334 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002335 /* max_len == 0 signifies "malloced" var, which we can
2336 * (and have to) free. But we can't free(cur->varstr) here:
2337 * if cur->flg_export is 1, it is in the environment.
2338 * We should either unsetenv+free, or wait until putenv,
2339 * then putenv(new)+free(old).
2340 */
2341 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002342 goto set_str_and_exp;
2343 }
2344
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002345 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002346 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002347 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002348 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002349 cur->next = *cur_pp;
2350 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002351
2352 set_str_and_exp:
2353 cur->varstr = str;
2354 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002355#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002356 if (flags & SETFLAG_MAKE_RO) {
2357 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002358 }
2359#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002360 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002361 cur->flg_export = 1;
2362 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002363 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002364 cur->flg_export = 0;
2365 /* unsetenv was already done */
2366 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002367 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002368 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002369 i = putenv(cur->varstr);
2370 /* only now we can free old exported malloced string */
2371 free(free_me);
2372 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002373 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002374 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002375 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002376
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002377 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002378
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002379 return 0;
2380}
2381
Denys Vlasenko6db47842009-09-05 20:15:17 +02002382/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002383static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002384{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002385 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002386}
2387
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002388#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002389static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002390{
2391 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002392 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002393
Denys Vlasenko61407802018-04-04 21:14:28 +02002394 cur_pp = &G.top_var;
2395 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002396 if (strncmp(cur->varstr, name, name_len) == 0
2397 && cur->varstr[name_len] == '='
2398 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002399 if (cur->flg_read_only) {
2400 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002401 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002402 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002403
Denys Vlasenko61407802018-04-04 21:14:28 +02002404 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002405 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2406 bb_unsetenv(cur->varstr);
2407 if (!cur->max_len)
2408 free(cur->varstr);
2409 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002410
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002411 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002412 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002413 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002414 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002415
2416 /* Handle "unset PS1" et al even if did not find the variable to unset */
2417 handle_changed_special_names(name, name_len);
2418
Mike Frysingerd690f682009-03-30 06:50:54 +00002419 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002420}
2421
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002422static int unset_local_var(const char *name)
2423{
2424 return unset_local_var_len(name, strlen(name));
2425}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002426#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002427
Denys Vlasenkob2b14cb2018-06-26 18:09:22 +02002428#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2429 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002430static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002431{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002432 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002433 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002434}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002435#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002436
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002437
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002438/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002439 * Helpers for "var1=val1 var2=val2 cmd" feature
2440 */
2441static void add_vars(struct variable *var)
2442{
2443 struct variable *next;
2444
2445 while (var) {
2446 next = var->next;
2447 var->next = G.top_var;
2448 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002449 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002450 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002451 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002452 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002453 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002454 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002455 var = next;
2456 }
2457}
2458
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002459/* We put strings[i] into variable table and possibly putenv them.
2460 * If variable is read only, we can free the strings[i]
2461 * which attempts to overwrite it.
2462 * The strings[] vector itself is freed.
2463 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002464static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002465{
2466 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002467
2468 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002469 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002470
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002471 s = strings;
2472 while (*s) {
2473 struct variable *var_p;
2474 struct variable **var_pp;
2475 char *eq;
2476
2477 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002478 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002479 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002480 var_pp = get_ptr_to_local_var(*s, eq - *s);
2481 if (var_pp) {
2482 var_p = *var_pp;
2483 if (var_p->flg_read_only) {
2484 char **p;
2485 bb_error_msg("%s: readonly variable", *s);
2486 /*
2487 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2488 * If VAR is readonly, leaving it in the list
2489 * after asssignment error (msg above)
2490 * causes doubled error message later, on unset.
2491 */
2492 debug_printf_env("removing/freeing '%s' element\n", *s);
2493 free(*s);
2494 p = s;
2495 do { *p = p[1]; p++; } while (*p);
2496 goto next;
2497 }
2498 /* below, set_local_var() with nest level will
2499 * "shadow" (remove) this variable from
2500 * global linked list.
2501 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002502 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002503 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2504 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002505 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002506 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002507 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002508 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002509}
2510
2511
2512/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002513 * Unicode helper
2514 */
2515static void reinit_unicode_for_hush(void)
2516{
2517 /* Unicode support should be activated even if LANG is set
2518 * _during_ shell execution, not only if it was set when
2519 * shell was started. Therefore, re-check LANG every time:
2520 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002521 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2522 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002523 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002524 const char *s = get_local_var_value("LC_ALL");
2525 if (!s) s = get_local_var_value("LC_CTYPE");
2526 if (!s) s = get_local_var_value("LANG");
2527 reinit_unicode(s);
2528 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002529}
2530
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002531/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002532 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002533 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002534
2535#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002536/* To test correct lineedit/interactive behavior, type from command line:
2537 * echo $P\
2538 * \
2539 * AT\
2540 * H\
2541 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002542 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002543 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002544# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002545static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002546{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002547 G.PS1 = get_local_var_value("PS1");
2548 if (G.PS1 == NULL)
2549 G.PS1 = "";
2550 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002551 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002552 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002553}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002554# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002555static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556{
2557 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002558
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002559 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002560
2561 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2562 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002563 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002564 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2565 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002566 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002567 /* bash uses $PWD value, even if it is set by user.
2568 * It uses current dir only if PWD is unset.
2569 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002570 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002571 }
2572 prompt_str = G.PS1;
2573 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002574 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002575 return prompt_str;
2576}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002577static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002578{
2579 int r;
2580 const char *prompt_str;
2581
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002582 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002583# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002584 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002585 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002586 if (G.flag_SIGINT) {
2587 /* There was ^C'ed, make it look prettier: */
2588 bb_putchar('\n');
2589 G.flag_SIGINT = 0;
2590 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002591 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002592 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002593 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002594 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002595 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002596 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002597 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002598 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002599 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002600 if (r != 0 && !G.flag_SIGINT)
2601 break;
2602 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002603 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2604 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002605 G.last_exitcode = 128 + SIGINT;
2606 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002607 if (r < 0) {
2608 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002609 i->p = NULL;
2610 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002611 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002612 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002613 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002614 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002615# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002616 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002617 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002618 if (i->last_char == '\0' || i->last_char == '\n') {
2619 /* Why check_and_run_traps here? Try this interactively:
2620 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2621 * $ <[enter], repeatedly...>
2622 * Without check_and_run_traps, handler never runs.
2623 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002624 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002625 fputs(prompt_str, stdout);
2626 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002627 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002628//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002629 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002630 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2631 * no ^C masking happens during fgetc, no special code for ^C:
2632 * it generates SIGINT as usual.
2633 */
2634 check_and_run_traps();
2635 if (G.flag_SIGINT)
2636 G.last_exitcode = 128 + SIGINT;
2637 if (r != '\0')
2638 break;
2639 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002640 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002641# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002642}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002643/* This is the magic location that prints prompts
2644 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002645static int fgetc_interactive(struct in_str *i)
2646{
2647 int ch;
2648 /* If it's interactive stdin, get new line. */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002649 if (G_interactive_fd && i->file->is_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002650 /* Returns first char (or EOF), the rest is in i->p[] */
2651 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002652 G.promptmode = 1; /* PS2 */
2653 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002654 } else {
2655 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002656 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002657 }
2658 return ch;
2659}
2660#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002661static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002662{
2663 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002664 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002665 return ch;
2666}
2667#endif /* INTERACTIVE */
2668
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002669static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002670{
2671 int ch;
2672
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002673 if (!i->file) {
2674 /* string-based in_str */
2675 ch = (unsigned char)*i->p;
2676 if (ch != '\0') {
2677 i->p++;
2678 i->last_char = ch;
2679 return ch;
2680 }
2681 return EOF;
2682 }
2683
2684 /* FILE-based in_str */
2685
Denys Vlasenko4074d492016-09-30 01:49:53 +02002686#if ENABLE_FEATURE_EDITING
2687 /* This can be stdin, check line editing char[] buffer */
2688 if (i->p && *i->p != '\0') {
2689 ch = (unsigned char)*i->p++;
2690 goto out;
2691 }
2692#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002693 /* peek_buf[] is an int array, not char. Can contain EOF. */
2694 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002695 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002696 int ch2 = i->peek_buf[1];
2697 i->peek_buf[0] = ch2;
2698 if (ch2 == 0) /* very likely, avoid redundant write */
2699 goto out;
2700 i->peek_buf[1] = 0;
2701 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002702 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002703
Denys Vlasenko4074d492016-09-30 01:49:53 +02002704 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002705 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002706 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002707 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002708#if ENABLE_HUSH_LINENO_VAR
2709 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002710 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002711 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2712 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002713#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002714 return ch;
2715}
2716
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002717static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002718{
2719 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002720
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002721 if (!i->file) {
2722 /* string-based in_str */
2723 /* Doesn't report EOF on NUL. None of the callers care. */
2724 return (unsigned char)*i->p;
2725 }
2726
2727 /* FILE-based in_str */
2728
Denys Vlasenko4074d492016-09-30 01:49:53 +02002729#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002730 /* This can be stdin, check line editing char[] buffer */
2731 if (i->p && *i->p != '\0')
2732 return (unsigned char)*i->p;
2733#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002734 /* peek_buf[] is an int array, not char. Can contain EOF. */
2735 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002736 if (ch != 0)
2737 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002738
Denys Vlasenko4074d492016-09-30 01:49:53 +02002739 /* Need to get a new char */
2740 ch = fgetc_interactive(i);
2741 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2742
2743 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2744#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2745 if (i->p) {
2746 i->p -= 1;
2747 return ch;
2748 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002749#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002750 i->peek_buf[0] = ch;
2751 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002752 return ch;
2753}
2754
Denys Vlasenko4074d492016-09-30 01:49:53 +02002755/* Only ever called if i_peek() was called, and did not return EOF.
2756 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2757 * not end-of-line. Therefore we never need to read a new editing line here.
2758 */
2759static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002760{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002761 int ch;
2762
2763 /* There are two cases when i->p[] buffer exists.
2764 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002765 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002766 * In both cases, we know that i->p[0] exists and not NUL, and
2767 * the peek2 result is in i->p[1].
2768 */
2769 if (i->p)
2770 return (unsigned char)i->p[1];
2771
2772 /* Now we know it is a file-based in_str. */
2773
2774 /* peek_buf[] is an int array, not char. Can contain EOF. */
2775 /* Is there 2nd char? */
2776 ch = i->peek_buf[1];
2777 if (ch == 0) {
2778 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002779 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002780 i->peek_buf[1] = ch;
2781 }
2782
2783 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2784 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002785}
2786
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002787static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2788{
2789 for (;;) {
2790 int ch, ch2;
2791
2792 ch = i_getch(input);
2793 if (ch != '\\')
2794 return ch;
2795 ch2 = i_peek(input);
2796 if (ch2 != '\n')
2797 return ch;
2798 /* backslash+newline, skip it */
2799 i_getch(input);
2800 }
2801}
2802
2803/* Note: this function _eats_ \<newline> pairs, safe to use plain
2804 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2805 */
2806static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2807{
2808 for (;;) {
2809 int ch, ch2;
2810
2811 ch = i_peek(input);
2812 if (ch != '\\')
2813 return ch;
2814 ch2 = i_peek2(input);
2815 if (ch2 != '\n')
2816 return ch;
2817 /* backslash+newline, skip it */
2818 i_getch(input);
2819 i_getch(input);
2820 }
2821}
2822
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002823static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002824{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002825 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002826 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002827 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002828}
2829
2830static void setup_string_in_str(struct in_str *i, const char *s)
2831{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002832 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002833 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002834 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002835}
2836
2837
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002838/*
2839 * o_string support
2840 */
2841#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002842
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002843static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002844{
2845 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002846 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002847 if (o->data)
2848 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002849}
2850
Denys Vlasenko18567402018-07-20 17:51:31 +02002851static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002852{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002853 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002854 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002855}
2856
Denys Vlasenko18567402018-07-20 17:51:31 +02002857static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002858{
2859 free(o->data);
2860}
2861
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002862static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002863{
2864 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002865 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002866 o->data = xrealloc(o->data, 1 + o->maxlen);
2867 }
2868}
2869
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002870static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002871{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002872 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002873 if (o->length < o->maxlen) {
2874 /* likely. avoid o_grow_by() call */
2875 add:
2876 o->data[o->length] = ch;
2877 o->length++;
2878 o->data[o->length] = '\0';
2879 return;
2880 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002881 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002882 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002883}
2884
Denys Vlasenko657086a2016-09-29 18:07:42 +02002885#if 0
2886/* Valid only if we know o_string is not empty */
2887static void o_delchr(o_string *o)
2888{
2889 o->length--;
2890 o->data[o->length] = '\0';
2891}
2892#endif
2893
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002894static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002895{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002896 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002897 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002898 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002899}
2900
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002901static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002902{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002903 o_addblock(o, str, strlen(str));
2904}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002905
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002906#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002907static void nommu_addchr(o_string *o, int ch)
2908{
2909 if (o)
2910 o_addchr(o, ch);
2911}
2912#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002913# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002914#endif
2915
2916static void o_addstr_with_NUL(o_string *o, const char *str)
2917{
2918 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002919}
2920
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002921/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002922 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002923 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2924 * Apparently, on unquoted $v bash still does globbing
2925 * ("v='*.txt'; echo $v" prints all .txt files),
2926 * but NOT brace expansion! Thus, there should be TWO independent
2927 * quoting mechanisms on $v expansion side: one protects
2928 * $v from brace expansion, and other additionally protects "$v" against globbing.
2929 * We have only second one.
2930 */
2931
Denys Vlasenko9e800222010-10-03 14:28:04 +02002932#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002933# define MAYBE_BRACES "{}"
2934#else
2935# define MAYBE_BRACES ""
2936#endif
2937
Eric Andersen25f27032001-04-26 23:22:31 +00002938/* My analysis of quoting semantics tells me that state information
2939 * is associated with a destination, not a source.
2940 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002941static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002942{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002943 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002944 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002945 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002946 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002947 o_grow_by(o, sz);
2948 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002949 o->data[o->length] = '\\';
2950 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002951 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002952 o->data[o->length] = ch;
2953 o->length++;
2954 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002955}
2956
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002957static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002958{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002959 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002960 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2961 && strchr("*?[\\" MAYBE_BRACES, ch)
2962 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002963 sz++;
2964 o->data[o->length] = '\\';
2965 o->length++;
2966 }
2967 o_grow_by(o, sz);
2968 o->data[o->length] = ch;
2969 o->length++;
2970 o->data[o->length] = '\0';
2971}
2972
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002973static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002974{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002975 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002976 char ch;
2977 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002978 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002979 if (ordinary_cnt > len) /* paranoia */
2980 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002981 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002982 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002983 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002984 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002985 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002986
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002987 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002988 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002989 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002990 sz++;
2991 o->data[o->length] = '\\';
2992 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002993 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002994 o_grow_by(o, sz);
2995 o->data[o->length] = ch;
2996 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002997 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002998 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002999}
3000
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003001static void o_addQblock(o_string *o, const char *str, int len)
3002{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003003 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003004 o_addblock(o, str, len);
3005 return;
3006 }
3007 o_addqblock(o, str, len);
3008}
3009
Denys Vlasenko38292b62010-09-05 14:49:40 +02003010static void o_addQstr(o_string *o, const char *str)
3011{
3012 o_addQblock(o, str, strlen(str));
3013}
3014
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003015/* A special kind of o_string for $VAR and `cmd` expansion.
3016 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003017 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003018 * list[i] contains an INDEX (int!) into this string data.
3019 * It means that if list[] needs to grow, data needs to be moved higher up
3020 * but list[i]'s need not be modified.
3021 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003022 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003023 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3024 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003025#if DEBUG_EXPAND || DEBUG_GLOB
3026static void debug_print_list(const char *prefix, o_string *o, int n)
3027{
3028 char **list = (char**)o->data;
3029 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3030 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003031
3032 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003033 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003034 prefix, list, n, string_start, o->length, o->maxlen,
3035 !!(o->o_expflags & EXP_FLAG_GLOB),
3036 o->has_quoted_part,
3037 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003038 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003039 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003040 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3041 o->data + (int)(uintptr_t)list[i] + string_start,
3042 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003043 i++;
3044 }
3045 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003046 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003047 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003048 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003049 }
3050}
3051#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003052# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003053#endif
3054
3055/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3056 * in list[n] so that it points past last stored byte so far.
3057 * It returns n+1. */
3058static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003059{
3060 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003061 int string_start;
3062 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003063
3064 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003065 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3066 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003067 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003068 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003069 /* list[n] points to string_start, make space for 16 more pointers */
3070 o->maxlen += 0x10 * sizeof(list[0]);
3071 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003072 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003073 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003074 /*
3075 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3076 * check. (grep for -prev-ifs-check-).
3077 * Ensure that argv[-1][last] is not garbage
3078 * but zero bytes, to save index check there.
3079 */
3080 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003081 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003082 } else {
3083 debug_printf_list("list[%d]=%d string_start=%d\n",
3084 n, string_len, string_start);
3085 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003086 } else {
3087 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003088 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3089 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003090 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3091 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003092 o->has_empty_slot = 0;
3093 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003094 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003095 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003096 return n + 1;
3097}
3098
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003099/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003100static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003101{
3102 char **list = (char**)o->data;
3103 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3104
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003105 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003106}
3107
Denys Vlasenko9e800222010-10-03 14:28:04 +02003108#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003109/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3110 * first, it processes even {a} (no commas), second,
3111 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003112 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003113 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003114
3115/* Helper */
3116static int glob_needed(const char *s)
3117{
3118 while (*s) {
3119 if (*s == '\\') {
3120 if (!s[1])
3121 return 0;
3122 s += 2;
3123 continue;
3124 }
3125 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3126 return 1;
3127 s++;
3128 }
3129 return 0;
3130}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003131/* Return pointer to next closing brace or to comma */
3132static const char *next_brace_sub(const char *cp)
3133{
3134 unsigned depth = 0;
3135 cp++;
3136 while (*cp != '\0') {
3137 if (*cp == '\\') {
3138 if (*++cp == '\0')
3139 break;
3140 cp++;
3141 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003142 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003143 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003144 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003145 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003146 depth++;
3147 }
3148
3149 return *cp != '\0' ? cp : NULL;
3150}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003151/* Recursive brace globber. Note: may garble pattern[]. */
3152static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003153{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003154 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003155 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003156 const char *next;
3157 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003158 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003159 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003160
3161 debug_printf_glob("glob_brace('%s')\n", pattern);
3162
3163 begin = pattern;
3164 while (1) {
3165 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003166 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003167 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003168 /* Find the first sub-pattern and at the same time
3169 * find the rest after the closing brace */
3170 next = next_brace_sub(begin);
3171 if (next == NULL) {
3172 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003173 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003174 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003175 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003176 /* "{abc}" with no commas - illegal
3177 * brace expr, disregard and skip it */
3178 begin = next + 1;
3179 continue;
3180 }
3181 break;
3182 }
3183 if (*begin == '\\' && begin[1] != '\0')
3184 begin++;
3185 begin++;
3186 }
3187 debug_printf_glob("begin:%s\n", begin);
3188 debug_printf_glob("next:%s\n", next);
3189
3190 /* Now find the end of the whole brace expression */
3191 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003192 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003193 rest = next_brace_sub(rest);
3194 if (rest == NULL) {
3195 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003196 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003197 }
3198 debug_printf_glob("rest:%s\n", rest);
3199 }
3200 rest_len = strlen(++rest) + 1;
3201
3202 /* We are sure the brace expression is well-formed */
3203
3204 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003205 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003206
3207 /* We have a brace expression. BEGIN points to the opening {,
3208 * NEXT points past the terminator of the first element, and REST
3209 * points past the final }. We will accumulate result names from
3210 * recursive runs for each brace alternative in the buffer using
3211 * GLOB_APPEND. */
3212
3213 p = begin + 1;
3214 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003215 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003216 memcpy(
3217 mempcpy(
3218 mempcpy(new_pattern_buf,
3219 /* We know the prefix for all sub-patterns */
3220 pattern, begin - pattern),
3221 p, next - p),
3222 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003223
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003224 /* Note: glob_brace() may garble new_pattern_buf[].
3225 * That's why we re-copy prefix every time (1st memcpy above).
3226 */
3227 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003228 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003229 /* We saw the last entry */
3230 break;
3231 }
3232 p = next + 1;
3233 next = next_brace_sub(next);
3234 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003235 free(new_pattern_buf);
3236 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003237
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003238 simple_glob:
3239 {
3240 int gr;
3241 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003242
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003243 memset(&globdata, 0, sizeof(globdata));
3244 gr = glob(pattern, 0, NULL, &globdata);
3245 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3246 if (gr != 0) {
3247 if (gr == GLOB_NOMATCH) {
3248 globfree(&globdata);
3249 /* NB: garbles parameter */
3250 unbackslash(pattern);
3251 o_addstr_with_NUL(o, pattern);
3252 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3253 return o_save_ptr_helper(o, n);
3254 }
3255 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003256 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003257 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3258 * but we didn't specify it. Paranoia again. */
3259 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3260 }
3261 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3262 char **argv = globdata.gl_pathv;
3263 while (1) {
3264 o_addstr_with_NUL(o, *argv);
3265 n = o_save_ptr_helper(o, n);
3266 argv++;
3267 if (!*argv)
3268 break;
3269 }
3270 }
3271 globfree(&globdata);
3272 }
3273 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003274}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003275/* Performs globbing on last list[],
3276 * saving each result as a new list[].
3277 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003278static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003279{
3280 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003281
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003282 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003283 if (!o->data)
3284 return o_save_ptr_helper(o, n);
3285 pattern = o->data + o_get_last_ptr(o, n);
3286 debug_printf_glob("glob pattern '%s'\n", pattern);
3287 if (!glob_needed(pattern)) {
3288 /* unbackslash last string in o in place, fix length */
3289 o->length = unbackslash(pattern) - o->data;
3290 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3291 return o_save_ptr_helper(o, n);
3292 }
3293
3294 copy = xstrdup(pattern);
3295 /* "forget" pattern in o */
3296 o->length = pattern - o->data;
3297 n = glob_brace(copy, o, n);
3298 free(copy);
3299 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003300 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003301 return n;
3302}
3303
Denys Vlasenko238081f2010-10-03 14:26:26 +02003304#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003305
3306/* Helper */
3307static int glob_needed(const char *s)
3308{
3309 while (*s) {
3310 if (*s == '\\') {
3311 if (!s[1])
3312 return 0;
3313 s += 2;
3314 continue;
3315 }
3316 if (*s == '*' || *s == '[' || *s == '?')
3317 return 1;
3318 s++;
3319 }
3320 return 0;
3321}
3322/* Performs globbing on last list[],
3323 * saving each result as a new list[].
3324 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003325static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003326{
3327 glob_t globdata;
3328 int gr;
3329 char *pattern;
3330
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003331 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003332 if (!o->data)
3333 return o_save_ptr_helper(o, n);
3334 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003335 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003336 if (!glob_needed(pattern)) {
3337 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003338 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003339 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003340 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003341 return o_save_ptr_helper(o, n);
3342 }
3343
3344 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003345 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3346 * If we glob "*.\*" and don't find anything, we need
3347 * to fall back to using literal "*.*", but GLOB_NOCHECK
3348 * will return "*.\*"!
3349 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003350 gr = glob(pattern, 0, NULL, &globdata);
3351 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003352 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003353 if (gr == GLOB_NOMATCH) {
3354 globfree(&globdata);
3355 goto literal;
3356 }
3357 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003358 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003359 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3360 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003361 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003362 }
3363 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3364 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003365 /* "forget" pattern in o */
3366 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003367 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003368 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003369 n = o_save_ptr_helper(o, n);
3370 argv++;
3371 if (!*argv)
3372 break;
3373 }
3374 }
3375 globfree(&globdata);
3376 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003377 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003378 return n;
3379}
3380
Denys Vlasenko238081f2010-10-03 14:26:26 +02003381#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003382
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003383/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003384 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003385static int o_save_ptr(o_string *o, int n)
3386{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003387 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003388 /* If o->has_empty_slot, list[n] was already globbed
3389 * (if it was requested back then when it was filled)
3390 * so don't do that again! */
3391 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003392 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003393 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003394 return o_save_ptr_helper(o, n);
3395}
3396
3397/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003398static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003399{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003400 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003401 int string_start;
3402
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003403 if (DEBUG_EXPAND)
3404 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003405 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003406 list = (char**)o->data;
3407 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3408 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003409 while (n) {
3410 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003411 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003412 }
3413 return list;
3414}
3415
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003416static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003417
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003418/* Returns pi->next - next pipe in the list */
3419static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003420{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003421 struct pipe *next;
3422 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003423
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003424 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003425 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003426 struct command *command;
3427 struct redir_struct *r, *rnext;
3428
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003429 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003430 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003431 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003432 if (DEBUG_CLEAN) {
3433 int a;
3434 char **p;
3435 for (a = 0, p = command->argv; *p; a++, p++) {
3436 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3437 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003438 }
3439 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003440 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003441 }
3442 /* not "else if": on syntax error, we may have both! */
3443 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003444 debug_printf_clean(" begin group (cmd_type:%d)\n",
3445 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003446 free_pipe_list(command->group);
3447 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003448 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003449 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003450 /* else is crucial here.
3451 * If group != NULL, child_func is meaningless */
3452#if ENABLE_HUSH_FUNCTIONS
3453 else if (command->child_func) {
3454 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3455 command->child_func->parent_cmd = NULL;
3456 }
3457#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003458#if !BB_MMU
3459 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003460 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003461#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003462 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003463 debug_printf_clean(" redirect %d%s",
3464 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003465 /* guard against the case >$FOO, where foo is unset or blank */
3466 if (r->rd_filename) {
3467 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3468 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003469 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003470 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003471 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003472 rnext = r->next;
3473 free(r);
3474 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003475 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003476 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003477 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003478 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003479#if ENABLE_HUSH_JOB
3480 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003481 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003482#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003483
3484 next = pi->next;
3485 free(pi);
3486 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003487}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003488
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003489static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003490{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003491 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003492#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003493 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003494#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003495 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003496 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003497 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003498}
3499
3500
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003501/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003502
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003503#ifndef debug_print_tree
3504static void debug_print_tree(struct pipe *pi, int lvl)
3505{
3506 static const char *const PIPE[] = {
3507 [PIPE_SEQ] = "SEQ",
3508 [PIPE_AND] = "AND",
3509 [PIPE_OR ] = "OR" ,
3510 [PIPE_BG ] = "BG" ,
3511 };
3512 static const char *RES[] = {
3513 [RES_NONE ] = "NONE" ,
3514# if ENABLE_HUSH_IF
3515 [RES_IF ] = "IF" ,
3516 [RES_THEN ] = "THEN" ,
3517 [RES_ELIF ] = "ELIF" ,
3518 [RES_ELSE ] = "ELSE" ,
3519 [RES_FI ] = "FI" ,
3520# endif
3521# if ENABLE_HUSH_LOOPS
3522 [RES_FOR ] = "FOR" ,
3523 [RES_WHILE] = "WHILE",
3524 [RES_UNTIL] = "UNTIL",
3525 [RES_DO ] = "DO" ,
3526 [RES_DONE ] = "DONE" ,
3527# endif
3528# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3529 [RES_IN ] = "IN" ,
3530# endif
3531# if ENABLE_HUSH_CASE
3532 [RES_CASE ] = "CASE" ,
3533 [RES_CASE_IN ] = "CASE_IN" ,
3534 [RES_MATCH] = "MATCH",
3535 [RES_CASE_BODY] = "CASE_BODY",
3536 [RES_ESAC ] = "ESAC" ,
3537# endif
3538 [RES_XXXX ] = "XXXX" ,
3539 [RES_SNTX ] = "SNTX" ,
3540 };
3541 static const char *const CMDTYPE[] = {
3542 "{}",
3543 "()",
3544 "[noglob]",
3545# if ENABLE_HUSH_FUNCTIONS
3546 "func()",
3547# endif
3548 };
3549
3550 int pin, prn;
3551
3552 pin = 0;
3553 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003554 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3555 lvl*2, "",
3556 pin,
3557 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3558 RES[pi->res_word],
3559 pi->followup, PIPE[pi->followup]
3560 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003561 prn = 0;
3562 while (prn < pi->num_cmds) {
3563 struct command *command = &pi->cmds[prn];
3564 char **argv = command->argv;
3565
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003566 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003567 lvl*2, "", prn,
3568 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003569#if ENABLE_HUSH_LINENO_VAR
3570 fdprintf(2, " LINENO:%u", command->lineno);
3571#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003572 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003573 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003574 CMDTYPE[command->cmd_type],
3575 argv
3576# if !BB_MMU
3577 , " group_as_string:", command->group_as_string
3578# else
3579 , "", ""
3580# endif
3581 );
3582 debug_print_tree(command->group, lvl+1);
3583 prn++;
3584 continue;
3585 }
3586 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003587 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003588 argv++;
3589 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003590 if (command->redirects)
3591 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003592 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003593 prn++;
3594 }
3595 pi = pi->next;
3596 pin++;
3597 }
3598}
3599#endif /* debug_print_tree */
3600
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003601static struct pipe *new_pipe(void)
3602{
Eric Andersen25f27032001-04-26 23:22:31 +00003603 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003604 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003605 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003606 return pi;
3607}
3608
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003609/* Command (member of a pipe) is complete, or we start a new pipe
3610 * if ctx->command is NULL.
3611 * No errors possible here.
3612 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003613static int done_command(struct parse_context *ctx)
3614{
3615 /* The command is really already in the pipe structure, so
3616 * advance the pipe counter and make a new, null command. */
3617 struct pipe *pi = ctx->pipe;
3618 struct command *command = ctx->command;
3619
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003620#if 0 /* Instead we emit error message at run time */
3621 if (ctx->pending_redirect) {
3622 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003623 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003624 ctx->pending_redirect = NULL;
3625 }
3626#endif
3627
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003628 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003629 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003630 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003631 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003632 }
3633 pi->num_cmds++;
3634 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003635 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003636 } else {
3637 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3638 }
3639
3640 /* Only real trickiness here is that the uncommitted
3641 * command structure is not counted in pi->num_cmds. */
3642 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003643 ctx->command = command = &pi->cmds[pi->num_cmds];
3644 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003645 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003646#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003647 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003648 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003649#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003650 return pi->num_cmds; /* used only for 0/nonzero check */
3651}
3652
3653static void done_pipe(struct parse_context *ctx, pipe_style type)
3654{
3655 int not_null;
3656
3657 debug_printf_parse("done_pipe entered, followup %d\n", type);
3658 /* Close previous command */
3659 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003660#if HAS_KEYWORDS
3661 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3662 ctx->ctx_inverted = 0;
3663 ctx->pipe->res_word = ctx->ctx_res_w;
3664#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003665 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3666 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003667 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3668 * in a backgrounded subshell.
3669 */
3670 struct pipe *pi;
3671 struct command *command;
3672
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003673 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003674 pi = ctx->list_head;
3675 while (pi != ctx->pipe) {
3676 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3677 goto no_conv;
3678 pi = pi->next;
3679 }
3680
3681 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3682 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3683 pi = xzalloc(sizeof(*pi));
3684 pi->followup = PIPE_BG;
3685 pi->num_cmds = 1;
3686 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3687 command = &pi->cmds[0];
3688 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3689 command->cmd_type = CMD_NORMAL;
3690 command->group = ctx->list_head;
3691#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003692 command->group_as_string = xstrndup(
3693 ctx->as_string.data,
3694 ctx->as_string.length - 1 /* do not copy last char, "&" */
3695 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003696#endif
3697 /* Replace all pipes in ctx with one newly created */
3698 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003699 } else {
3700 no_conv:
3701 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003702 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003703
3704 /* Without this check, even just <enter> on command line generates
3705 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003706 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003707 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003708#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003709 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003710#endif
3711#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003712 || ctx->ctx_res_w == RES_DONE
3713 || ctx->ctx_res_w == RES_FOR
3714 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003715#endif
3716#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003717 || ctx->ctx_res_w == RES_ESAC
3718#endif
3719 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003720 struct pipe *new_p;
3721 debug_printf_parse("done_pipe: adding new pipe: "
3722 "not_null:%d ctx->ctx_res_w:%d\n",
3723 not_null, ctx->ctx_res_w);
3724 new_p = new_pipe();
3725 ctx->pipe->next = new_p;
3726 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003727 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003728 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003729 * This is used to control execution.
3730 * RES_FOR and RES_IN are NOT sticky (needed to support
3731 * cases where variable or value happens to match a keyword):
3732 */
3733#if ENABLE_HUSH_LOOPS
3734 if (ctx->ctx_res_w == RES_FOR
3735 || ctx->ctx_res_w == RES_IN)
3736 ctx->ctx_res_w = RES_NONE;
3737#endif
3738#if ENABLE_HUSH_CASE
3739 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003740 ctx->ctx_res_w = RES_CASE_BODY;
3741 if (ctx->ctx_res_w == RES_CASE)
3742 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003743#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003744 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003745 /* Create the memory for command, roughly:
3746 * ctx->pipe->cmds = new struct command;
3747 * ctx->command = &ctx->pipe->cmds[0];
3748 */
3749 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003750 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003751 }
3752 debug_printf_parse("done_pipe return\n");
3753}
3754
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003755static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003756{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003757 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003758 if (MAYBE_ASSIGNMENT != 0)
3759 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003760 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003761 /* Create the memory for command, roughly:
3762 * ctx->pipe->cmds = new struct command;
3763 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003764 */
3765 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003766}
3767
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003768/* If a reserved word is found and processed, parse context is modified
3769 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003770 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003771#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003772struct reserved_combo {
3773 char literal[6];
3774 unsigned char res;
3775 unsigned char assignment_flag;
3776 int flag;
3777};
3778enum {
3779 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003780# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003781 FLAG_IF = (1 << RES_IF ),
3782 FLAG_THEN = (1 << RES_THEN ),
3783 FLAG_ELIF = (1 << RES_ELIF ),
3784 FLAG_ELSE = (1 << RES_ELSE ),
3785 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003786# endif
3787# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003788 FLAG_FOR = (1 << RES_FOR ),
3789 FLAG_WHILE = (1 << RES_WHILE),
3790 FLAG_UNTIL = (1 << RES_UNTIL),
3791 FLAG_DO = (1 << RES_DO ),
3792 FLAG_DONE = (1 << RES_DONE ),
3793 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003794# endif
3795# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003796 FLAG_MATCH = (1 << RES_MATCH),
3797 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003798# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003799 FLAG_START = (1 << RES_XXXX ),
3800};
3801
3802static const struct reserved_combo* match_reserved_word(o_string *word)
3803{
Eric Andersen25f27032001-04-26 23:22:31 +00003804 /* Mostly a list of accepted follow-up reserved words.
3805 * FLAG_END means we are done with the sequence, and are ready
3806 * to turn the compound list into a command.
3807 * FLAG_START means the word must start a new compound list.
3808 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003809 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003810# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003811 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3812 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3813 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3814 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3815 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3816 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003817# endif
3818# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003819 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3820 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3821 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3822 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3823 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3824 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003825# endif
3826# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003827 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3828 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003829# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003830 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003831 const struct reserved_combo *r;
3832
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003833 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003834 if (strcmp(word->data, r->literal) == 0)
3835 return r;
3836 }
3837 return NULL;
3838}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003839/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003840 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003841static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003842{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003843# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003844 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003845 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003846 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003847# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003848 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003849
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003850 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003851 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003852 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003853 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003854 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003855
3856 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003857# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003858 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3859 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003860 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003861 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003862# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003863 if (r->flag == 0) { /* '!' */
3864 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003865 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003866 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003867 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003868 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003869 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003870 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003871 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003872 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003873
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003874 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003875 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003876 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003877 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003878 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003879 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003880 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003881 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003882 } else {
3883 /* "{...} fi" is ok. "{...} if" is not
3884 * Example:
3885 * if { echo foo; } then { echo bar; } fi */
3886 if (ctx->command->group)
3887 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003888 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003889
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003890 ctx->ctx_res_w = r->res;
3891 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003892 ctx->is_assignment = r->assignment_flag;
3893 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003894
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003895 if (ctx->old_flag & FLAG_END) {
3896 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003897
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003898 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003899 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003900 old = ctx->stack;
3901 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003902 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003903# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003904 /* At this point, the compound command's string is in
3905 * ctx->as_string... except for the leading keyword!
3906 * Consider this example: "echo a | if true; then echo a; fi"
3907 * ctx->as_string will contain "true; then echo a; fi",
3908 * with "if " remaining in old->as_string!
3909 */
3910 {
3911 char *str;
3912 int len = old->as_string.length;
3913 /* Concatenate halves */
3914 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02003915 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003916 /* Find where leading keyword starts in first half */
3917 str = old->as_string.data + len;
3918 if (str > old->as_string.data)
3919 str--; /* skip whitespace after keyword */
3920 while (str > old->as_string.data && isalpha(str[-1]))
3921 str--;
3922 /* Ugh, we're done with this horrid hack */
3923 old->command->group_as_string = xstrdup(str);
3924 debug_printf_parse("pop, remembering as:'%s'\n",
3925 old->command->group_as_string);
3926 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003927# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003928 *ctx = *old; /* physical copy */
3929 free(old);
3930 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003931 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003932}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003933#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003934
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003935/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003936 * Normal return is 0. Syntax errors return 1.
3937 * Note: on return, word is reset, but not o_free'd!
3938 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003939static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003940{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003941 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003942
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003943 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3944 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003945 debug_printf_parse("done_word return 0: true null, ignored\n");
3946 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003947 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003948
Eric Andersen25f27032001-04-26 23:22:31 +00003949 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003950 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3951 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003952 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003953 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003954 * If the redirection operator is "<<" or "<<-", the word
3955 * that follows the redirection operator shall be
3956 * subjected to quote removal; it is unspecified whether
3957 * any of the other expansions occur. For the other
3958 * redirection operators, the word that follows the
3959 * redirection operator shall be subjected to tilde
3960 * expansion, parameter expansion, command substitution,
3961 * arithmetic expansion, and quote removal.
3962 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003963 * on the word by a non-interactive shell; an interactive
3964 * shell may perform it, but shall do so only when
3965 * the expansion would result in one word."
3966 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003967//bash does not do parameter/command substitution or arithmetic expansion
3968//for _heredoc_ redirection word: these constructs look for exact eof marker
3969// as written:
3970// <<EOF$t
3971// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003972// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3973
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003974 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003975 /* Cater for >\file case:
3976 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3977 * Same with heredocs:
3978 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3979 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003980 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3981 unbackslash(ctx->pending_redirect->rd_filename);
3982 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003983 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003984 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3985 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003986 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003987 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003988 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003989 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003990#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003991# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003992 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003993 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003994 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003995 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003996 /* ctx->ctx_res_w = RES_MATCH; */
3997 ctx->ctx_dsemicolon = 0;
3998 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003999# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004000 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004001# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004002 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4003 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004004# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004005# if ENABLE_HUSH_CASE
4006 && ctx->ctx_res_w != RES_CASE
4007# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004008 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004009 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004010 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004011 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004012 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004013# if ENABLE_HUSH_LINENO_VAR
4014/* Case:
4015 * "while ...; do
4016 * cmd ..."
4017 * If we don't close the pipe _now_, immediately after "do", lineno logic
4018 * sees "cmd" as starting at "do" - i.e., at the previous line.
4019 */
4020 if (0
4021 IF_HUSH_IF(|| reserved->res == RES_THEN)
4022 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4023 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4024 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4025 ) {
4026 done_pipe(ctx, PIPE_SEQ);
4027 }
4028# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004029 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004030 debug_printf_parse("done_word return %d\n",
4031 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004032 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004033 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004034# if defined(CMD_SINGLEWORD_NOGLOB)
4035 if (0
4036# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004037 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004038# endif
4039 /* In bash, local/export/readonly are special, args
4040 * are assignments and therefore expansion of them
4041 * should be "one-word" expansion:
4042 * $ export i=`echo 'a b'` # one arg: "i=a b"
4043 * compare with:
4044 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4045 * ls: cannot access i=a: No such file or directory
4046 * ls: cannot access b: No such file or directory
4047 * Note: bash 3.2.33(1) does this only if export word
4048 * itself is not quoted:
4049 * $ export i=`echo 'aaa bbb'`; echo "$i"
4050 * aaa bbb
4051 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4052 * aaa
4053 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004054 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4055 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4056 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004057 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004058 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4059 }
4060 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004061# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004062 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004063#endif /* HAS_KEYWORDS */
4064
Denis Vlasenkobb929512009-04-16 10:59:40 +00004065 if (command->group) {
4066 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004067 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004068 debug_printf_parse("done_word return 1: syntax error, "
4069 "groups and arglists don't mix\n");
4070 return 1;
4071 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004072
4073 /* If this word wasn't an assignment, next ones definitely
4074 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004075 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4076 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004077 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004078 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004079 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004080 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004081 command->assignment_cnt++;
4082 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4083 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004084 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4085 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004086 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004087 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4088 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004089 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004090 }
Eric Andersen25f27032001-04-26 23:22:31 +00004091
Denis Vlasenko06810332007-05-21 23:30:54 +00004092#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004093 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004094 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004095 || !is_well_formed_var_name(command->argv[0], '\0')
4096 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004097 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004098 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004099 return 1;
4100 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004101 /* Force FOR to have just one word (variable name) */
4102 /* NB: basically, this makes hush see "for v in ..."
4103 * syntax as if it is "for v; in ...". FOR and IN become
4104 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004105 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004106 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004107#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004108#if ENABLE_HUSH_CASE
4109 /* Force CASE to have just one word */
4110 if (ctx->ctx_res_w == RES_CASE) {
4111 done_pipe(ctx, PIPE_SEQ);
4112 }
4113#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004114
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004115 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004116
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004117 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004118 return 0;
4119}
4120
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004121
4122/* Peek ahead in the input to find out if we have a "&n" construct,
4123 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004124 * Return:
4125 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4126 * REDIRFD_SYNTAX_ERR if syntax error,
4127 * REDIRFD_TO_FILE if no & was seen,
4128 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004129 */
4130#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004131#define parse_redir_right_fd(as_string, input) \
4132 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004133#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004134static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004135{
4136 int ch, d, ok;
4137
4138 ch = i_peek(input);
4139 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004140 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004141
4142 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004143 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004144 ch = i_peek(input);
4145 if (ch == '-') {
4146 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004147 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004148 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004149 }
4150 d = 0;
4151 ok = 0;
4152 while (ch != EOF && isdigit(ch)) {
4153 d = d*10 + (ch-'0');
4154 ok = 1;
4155 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004156 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004157 ch = i_peek(input);
4158 }
4159 if (ok) return d;
4160
4161//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4162
4163 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004164 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004165}
4166
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004167/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004168 */
4169static int parse_redirect(struct parse_context *ctx,
4170 int fd,
4171 redir_type style,
4172 struct in_str *input)
4173{
4174 struct command *command = ctx->command;
4175 struct redir_struct *redir;
4176 struct redir_struct **redirp;
4177 int dup_num;
4178
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004179 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004180 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004181 /* Check for a '>&1' type redirect */
4182 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4183 if (dup_num == REDIRFD_SYNTAX_ERR)
4184 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004185 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004186 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004187 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004188 if (dup_num) { /* <<-... */
4189 ch = i_getch(input);
4190 nommu_addchr(&ctx->as_string, ch);
4191 ch = i_peek(input);
4192 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004193 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004194
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004195 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004196 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004197 if (ch == '|') {
4198 /* >|FILE redirect ("clobbering" >).
4199 * Since we do not support "set -o noclobber" yet,
4200 * >| and > are the same for now. Just eat |.
4201 */
4202 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004203 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004204 }
4205 }
4206
4207 /* Create a new redir_struct and append it to the linked list */
4208 redirp = &command->redirects;
4209 while ((redir = *redirp) != NULL) {
4210 redirp = &(redir->next);
4211 }
4212 *redirp = redir = xzalloc(sizeof(*redir));
4213 /* redir->next = NULL; */
4214 /* redir->rd_filename = NULL; */
4215 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004216 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004217
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004218 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4219 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004220
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004221 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004222 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004223 /* Erik had a check here that the file descriptor in question
4224 * is legit; I postpone that to "run time"
4225 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004226 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4227 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004228 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004229#if 0 /* Instead we emit error message at run time */
4230 if (ctx->pending_redirect) {
4231 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004232 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004233 }
4234#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004235 /* Set ctx->pending_redirect, so we know what to do at the
4236 * end of the next parsed word. */
4237 ctx->pending_redirect = redir;
4238 }
4239 return 0;
4240}
4241
Eric Andersen25f27032001-04-26 23:22:31 +00004242/* If a redirect is immediately preceded by a number, that number is
4243 * supposed to tell which file descriptor to redirect. This routine
4244 * looks for such preceding numbers. In an ideal world this routine
4245 * needs to handle all the following classes of redirects...
4246 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4247 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4248 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4249 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004250 *
4251 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4252 * "2.7 Redirection
4253 * ... If n is quoted, the number shall not be recognized as part of
4254 * the redirection expression. For example:
4255 * echo \2>a
4256 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004257 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004258 *
4259 * A -1 return means no valid number was found,
4260 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004261 */
4262static int redirect_opt_num(o_string *o)
4263{
4264 int num;
4265
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004266 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004267 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004268 num = bb_strtou(o->data, NULL, 10);
4269 if (errno || num < 0)
4270 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004271 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004272 return num;
4273}
4274
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004275#if BB_MMU
4276#define fetch_till_str(as_string, input, word, skip_tabs) \
4277 fetch_till_str(input, word, skip_tabs)
4278#endif
4279static char *fetch_till_str(o_string *as_string,
4280 struct in_str *input,
4281 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004282 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004283{
4284 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004285 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004286 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004287 int ch;
4288
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004289 /* Starting with "" is necessary for this case:
4290 * cat <<EOF
4291 *
4292 * xxx
4293 * EOF
4294 */
4295 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4296
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004297 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004298
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004299 while (1) {
4300 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004301 if (ch != EOF)
4302 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004303 if (ch == '\n' || ch == EOF) {
4304 check_heredoc_end:
4305 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004306 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004307 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4308 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004309 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004310 return heredoc.data;
4311 }
4312 if (ch == '\n') {
4313 /* This is a new line.
4314 * Remember position and backslash-escaping status.
4315 */
4316 o_addchr(&heredoc, ch);
4317 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004318 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004319 past_EOL = heredoc.length;
4320 /* Get 1st char of next line, possibly skipping leading tabs */
4321 do {
4322 ch = i_getch(input);
4323 if (ch != EOF)
4324 nommu_addchr(as_string, ch);
4325 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4326 /* If this immediately ended the line,
4327 * go back to end-of-line checks.
4328 */
4329 if (ch == '\n')
4330 goto check_heredoc_end;
4331 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004332 } else {
4333 /* Backslash-line continuation in an unquoted
4334 * heredoc. This does not need special handling
4335 * for heredoc body (unquoted heredocs are
4336 * expanded on "execution" and that would take
4337 * care of this case too), but not the case
4338 * of line continuation *in terminator*:
4339 * cat <<EOF
4340 * Ok1
4341 * EO\
4342 * F
4343 */
4344 heredoc.data[--heredoc.length] = '\0';
4345 prev = 0; /* not '\' */
4346 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004347 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004348 }
4349 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004350 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004351 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004352 }
4353 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004354 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004355 if (prev == '\\' && ch == '\\')
4356 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004357 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004358 else
4359 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004360 }
4361}
4362
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004363/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4364 * and load them all. There should be exactly heredoc_cnt of them.
4365 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004366#if BB_MMU
4367#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4368 fetch_heredocs(pi, heredoc_cnt, input)
4369#endif
4370static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004371{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004372 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004373 int i;
4374 struct command *cmd = pi->cmds;
4375
Denys Vlasenko3675c372018-07-23 16:31:21 +02004376 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004377 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004378 cmd->argv ? cmd->argv[0] : "NONE"
4379 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004380 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004381 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004382
Denys Vlasenko3675c372018-07-23 16:31:21 +02004383 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004384 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004385 while (redir) {
4386 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004387 char *p;
4388
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004389 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004390 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004391 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004392 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004393 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004394 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004395 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004396 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004397 free(redir->rd_filename);
4398 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004399 heredoc_cnt--;
4400 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004401 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004402 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004403 if (cmd->group) {
4404 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4405 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4406 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4407 if (heredoc_cnt < 0)
4408 return heredoc_cnt; /* error */
4409 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004410 cmd++;
4411 }
4412 pi = pi->next;
4413 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004414 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004415}
4416
4417
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004418static int run_list(struct pipe *pi);
4419#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004420#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4421 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004422#endif
4423static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004424 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004425 struct in_str *input,
4426 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004427
Denys Vlasenko474cb202018-07-24 13:03:03 +02004428/* Returns number of heredocs not yet consumed,
4429 * or -1 on error.
4430 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004431static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004432 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004433{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004434 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004435 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004436 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004437#if BB_MMU
4438# define as_string NULL
4439#else
4440 char *as_string = NULL;
4441#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004442 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004443 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004444 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004445 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004446
4447 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004448#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004449 if (ch == '(' && !ctx->word.has_quoted_part) {
4450 if (ctx->word.length)
4451 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004452 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004453 if (!command->argv)
4454 goto skip; /* (... */
4455 if (command->argv[1]) { /* word word ... (... */
4456 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004457 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004458 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004459 /* it is "word(..." or "word (..." */
4460 do
4461 ch = i_getch(input);
4462 while (ch == ' ' || ch == '\t');
4463 if (ch != ')') {
4464 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004465 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004466 }
4467 nommu_addchr(&ctx->as_string, ch);
4468 do
4469 ch = i_getch(input);
4470 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004471 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004472 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004473 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004474 }
4475 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004476 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004477 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004478 }
4479#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004480
4481#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004482 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004483 || ctx->word.length /* word{... */
4484 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004485 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004486 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004487 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004488 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004489 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004490 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004491#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004492
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004493 IF_HUSH_FUNCTIONS(skip:)
4494
Denis Vlasenko240c2552009-04-03 03:45:05 +00004495 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004496 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004497 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004498 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4499 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004500 } else {
4501 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004502 ch = i_peek(input);
4503 if (ch != ' ' && ch != '\t' && ch != '\n'
4504 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4505 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004506 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004507 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004508 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004509 if (ch != '(') {
4510 ch = i_getch(input);
4511 nommu_addchr(&ctx->as_string, ch);
4512 }
Eric Andersen25f27032001-04-26 23:22:31 +00004513 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004514
Denys Vlasenko474cb202018-07-24 13:03:03 +02004515 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4516 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4517 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004518#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004519 if (as_string)
4520 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004521#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004522
4523 /* empty ()/{} or parse error? */
4524 if (!pipe_list || pipe_list == ERR_PTR) {
4525 /* parse_stream already emitted error msg */
4526 if (!BB_MMU)
4527 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004528 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004529 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004530 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004531 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004532#if !BB_MMU
4533 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4534 command->group_as_string = as_string;
4535 debug_printf_parse("end of group, remembering as:'%s'\n",
4536 command->group_as_string);
4537#endif
4538
4539#if ENABLE_HUSH_FUNCTIONS
4540 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4541 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4542 struct command *cmd2;
4543
4544 cmd2 = xzalloc(sizeof(*cmd2));
4545 cmd2->cmd_type = CMD_SUBSHELL;
4546 cmd2->group = pipe_list;
4547# if !BB_MMU
4548//UNTESTED!
4549 cmd2->group_as_string = command->group_as_string;
4550 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4551# endif
4552
4553 pipe_list = new_pipe();
4554 pipe_list->cmds = cmd2;
4555 pipe_list->num_cmds = 1;
4556 }
4557#endif
4558
4559 command->group = pipe_list;
4560
Denys Vlasenko474cb202018-07-24 13:03:03 +02004561 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4562 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004563 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004564#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004565}
4566
Denys Vlasenko0b883582016-12-23 16:49:07 +01004567#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004568/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004569/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004570static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004571{
4572 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004573 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004574 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004575 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004576 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004577 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004578 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004579 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004580 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004581 }
4582}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004583static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4584{
4585 while (1) {
4586 int ch = i_getch(input);
4587 if (ch == EOF) {
4588 syntax_error_unterm_ch('\'');
4589 return 0;
4590 }
4591 if (ch == '\'')
4592 return 1;
4593 o_addqchr(dest, ch);
4594 }
4595}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004596/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004597static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004598static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004599{
4600 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004601 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004602 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004603 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004604 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004605 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004606 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004607 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004608 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004609 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004610 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004611 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004612 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004613 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004614 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4615 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004616 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004617 continue;
4618 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004619 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004620 }
4621}
4622/* Process `cmd` - copy contents until "`" is seen. Complicated by
4623 * \` quoting.
4624 * "Within the backquoted style of command substitution, backslash
4625 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4626 * The search for the matching backquote shall be satisfied by the first
4627 * backquote found without a preceding backslash; during this search,
4628 * if a non-escaped backquote is encountered within a shell comment,
4629 * a here-document, an embedded command substitution of the $(command)
4630 * form, or a quoted string, undefined results occur. A single-quoted
4631 * or double-quoted string that begins, but does not end, within the
4632 * "`...`" sequence produces undefined results."
4633 * Example Output
4634 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4635 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004636static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004637{
4638 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004639 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004640 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004641 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004642 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004643 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4644 ch = i_getch(input);
4645 if (ch != '`'
4646 && ch != '$'
4647 && ch != '\\'
4648 && (!in_dquote || ch != '"')
4649 ) {
4650 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004651 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004652 }
4653 if (ch == EOF) {
4654 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004655 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004656 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004657 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004658 }
4659}
4660/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4661 * quoting and nested ()s.
4662 * "With the $(command) style of command substitution, all characters
4663 * following the open parenthesis to the matching closing parenthesis
4664 * constitute the command. Any valid shell script can be used for command,
4665 * except a script consisting solely of redirections which produces
4666 * unspecified results."
4667 * Example Output
4668 * echo $(echo '(TEST)' BEST) (TEST) BEST
4669 * echo $(echo 'TEST)' BEST) TEST) BEST
4670 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004671 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004672 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004673 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004674 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4675 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004676 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004677#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004678static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004679{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004680 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004681 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004682# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004683 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004684# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004685 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4686
Denys Vlasenko817a2022018-06-26 15:35:17 +02004687#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004688 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004689#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004690 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4691
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004692 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004693 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004694 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004695 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004696 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004697 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004698 if (ch == end_ch
4699# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004700 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004701# endif
4702 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004703 if (!dbl)
4704 break;
4705 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004706 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004707 i_getch(input); /* eat second ')' */
4708 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004709 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004710 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004711 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004712 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004713 if (ch == '(' || ch == '{') {
4714 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004715 if (!add_till_closing_bracket(dest, input, ch))
4716 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004717 o_addchr(dest, ch);
4718 continue;
4719 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004720 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004721 if (!add_till_single_quote(dest, input))
4722 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004723 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004724 continue;
4725 }
4726 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004727 if (!add_till_double_quote(dest, input))
4728 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004729 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004730 continue;
4731 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004732 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004733 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4734 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004735 o_addchr(dest, ch);
4736 continue;
4737 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004738 if (ch == '\\') {
4739 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004740 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004741 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004742 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004743 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004744 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004745#if 0
4746 if (ch == '\n') {
4747 /* "backslash+newline", ignore both */
4748 o_delchr(dest); /* undo insertion of '\' */
4749 continue;
4750 }
4751#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004752 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004753 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004754 continue;
4755 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004756 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004757 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004758 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004759}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004760#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004761
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004762/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004763#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004764#define parse_dollar(as_string, dest, input, quote_mask) \
4765 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004766#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004767#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004768static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004769 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004770 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004771{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004772 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004773
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004774 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004775 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004776 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004777 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004778 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004779 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004780 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004781 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004782 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004783 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004784 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004785 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004786 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004787 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004788 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004789 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004790 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004791 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004792 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004793 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004794 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004795 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004796 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004797 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004798 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004799 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004800 o_addchr(dest, ch | quote_mask);
4801 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004802 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004803 case '$': /* pid */
4804 case '!': /* last bg pid */
4805 case '?': /* last exit code */
4806 case '#': /* number of args */
4807 case '*': /* args */
4808 case '@': /* args */
4809 goto make_one_char_var;
4810 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004811 char len_single_ch;
4812
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004813 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4814
Denys Vlasenko74369502010-05-21 19:52:01 +02004815 ch = i_getch(input); /* eat '{' */
4816 nommu_addchr(as_string, ch);
4817
Denys Vlasenko46e64982016-09-29 19:50:55 +02004818 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004819 /* It should be ${?}, or ${#var},
4820 * or even ${?+subst} - operator acting on a special variable,
4821 * or the beginning of variable name.
4822 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004823 if (ch == EOF
4824 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4825 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004826 bad_dollar_syntax:
4827 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004828 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4829 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004830 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004831 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004832 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004833 ch |= quote_mask;
4834
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004835 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004836 * However, this regresses some of our testsuite cases
4837 * which check invalid constructs like ${%}.
4838 * Oh well... let's check that the var name part is fine... */
4839
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004840 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004841 unsigned pos;
4842
Denys Vlasenko74369502010-05-21 19:52:01 +02004843 o_addchr(dest, ch);
4844 debug_printf_parse(": '%c'\n", ch);
4845
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004846 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004847 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004848 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004849 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004850
Denys Vlasenko74369502010-05-21 19:52:01 +02004851 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004852 unsigned end_ch;
4853 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004854 /* handle parameter expansions
4855 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4856 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004857 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4858 if (len_single_ch != '#'
4859 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4860 || i_peek(input) != '}'
4861 ) {
4862 goto bad_dollar_syntax;
4863 }
4864 /* else: it's "length of C" ${#C} op,
4865 * where C is a single char
4866 * special var name, e.g. ${#!}.
4867 */
4868 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004869 /* Eat everything until closing '}' (or ':') */
4870 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004871 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004872 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004873 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004874 ) {
4875 /* It's ${var:N[:M]} thing */
4876 end_ch = '}' * 0x100 + ':';
4877 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004878 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004879 && ch == '/'
4880 ) {
4881 /* It's ${var/[/]pattern[/repl]} thing */
4882 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4883 i_getch(input);
4884 nommu_addchr(as_string, '/');
4885 ch = '\\';
4886 }
4887 end_ch = '}' * 0x100 + '/';
4888 }
4889 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004890 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004891 if (!BB_MMU)
4892 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004893#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004894 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004895 if (last_ch == 0) /* error? */
4896 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004897#else
4898#error Simple code to only allow ${var} is not implemented
4899#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004900 if (as_string) {
4901 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004902 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004903 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004904
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004905 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4906 && (end_ch & 0xff00)
4907 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004908 /* close the first block: */
4909 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004910 /* while parsing N from ${var:N[:M]}
4911 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004912 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004913 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004914 end_ch = '}';
4915 goto again;
4916 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004917 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004918 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004919 /* it's ${var:N} - emulate :999999999 */
4920 o_addstr(dest, "999999999");
4921 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004922 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004923 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004924 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004925 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004926 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004927 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4928 break;
4929 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004930#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004931 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004932 unsigned pos;
4933
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004934 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004935 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004936# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004937 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004938 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004939 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004940 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4941 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004942 if (!BB_MMU)
4943 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004944 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4945 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004946 if (as_string) {
4947 o_addstr(as_string, dest->data + pos);
4948 o_addchr(as_string, ')');
4949 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004950 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004951 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004952 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004953 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004954# endif
4955# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004956 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4957 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004958 if (!BB_MMU)
4959 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004960 if (!add_till_closing_bracket(dest, input, ')'))
4961 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004962 if (as_string) {
4963 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004964 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004965 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004966 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004967# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004968 break;
4969 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004970#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004971 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004972 goto make_var;
4973#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004974 /* TODO: $_ and $-: */
4975 /* $_ Shell or shell script name; or last argument of last command
4976 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4977 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004978 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004979 ch = i_getch(input);
4980 nommu_addchr(as_string, ch);
4981 ch = i_peek_and_eat_bkslash_nl(input);
4982 if (isalnum(ch)) { /* it's $_name or $_123 */
4983 ch = '_';
4984 goto make_var1;
4985 }
4986 /* else: it's $_ */
4987#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004988 default:
4989 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004990 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004991 debug_printf_parse("parse_dollar return 1 (ok)\n");
4992 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004993#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004994}
4995
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004996#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02004997#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004998 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004999#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005000#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005001static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005002 o_string *dest,
5003 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005004 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005005{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005006 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005007 int next;
5008
5009 again:
5010 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005011 if (ch != EOF)
5012 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005013 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005014 debug_printf_parse("encode_string return 1 (ok)\n");
5015 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005016 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005017 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005018 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005019 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005020 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005021 }
5022 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005023 if (ch != '\n') {
5024 next = i_peek(input);
5025 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005026 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005027 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005028 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005029 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005030 /* Testcase: in interactive shell a file with
5031 * echo "unterminated string\<eof>
5032 * is sourced.
5033 */
5034 syntax_error_unterm_ch('"');
5035 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005036 }
5037 /* bash:
5038 * "The backslash retains its special meaning [in "..."]
5039 * only when followed by one of the following characters:
5040 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005041 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005042 * NB: in (unquoted) heredoc, above does not apply to ",
5043 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005044 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005045 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005046 ch = i_getch(input); /* eat next */
5047 if (ch == '\n')
5048 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005049 } /* else: ch remains == '\\', and we double it below: */
5050 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005051 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005052 goto again;
5053 }
5054 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005055 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5056 debug_printf_parse("encode_string return 0: "
5057 "parse_dollar returned 0 (error)\n");
5058 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005059 }
5060 goto again;
5061 }
5062#if ENABLE_HUSH_TICK
5063 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005064 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005065 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5066 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005067 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5068 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005069 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5070 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005071 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005072 }
5073#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005074 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005075 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005076#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005077}
5078
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005079/*
5080 * Scan input until EOF or end_trigger char.
5081 * Return a list of pipes to execute, or NULL on EOF
5082 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005083 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005084 * reset parsing machinery and start parsing anew,
5085 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005086 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005087static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005088 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005089 struct in_str *input,
5090 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005091{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005092 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005093 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005094
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005095 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005096 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005097 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005098 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005099 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005100 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005101
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005102 initialize_context(&ctx);
5103
5104 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5105 * Preventing this:
5106 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005107 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005108
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005109 /* We used to separate words on $IFS here. This was wrong.
5110 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005111 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005112 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005113
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005114 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005115 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005116 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005117 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005118 int ch;
5119 int next;
5120 int redir_fd;
5121 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005122
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005123 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005124 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005125 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005126 if (ch == EOF) {
5127 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005128
5129 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005130 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005131 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005132 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005133 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005134 syntax_error_unterm_ch('(');
5135 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005136 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005137 if (end_trigger == '}') {
5138 syntax_error_unterm_ch('{');
5139 goto parse_error;
5140 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005141
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005142 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005143 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005144 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005145 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005146 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005147 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005148 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005149 /* (this makes bare "&" cmd a no-op.
5150 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005151 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005152 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005153 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005154 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005155 pi = NULL;
5156 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005157#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005158 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005159 if (pstring)
5160 *pstring = ctx.as_string.data;
5161 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005162 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005163#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005164 // heredoc_cnt must be 0 here anyway
5165 //if (heredoc_cnt_ptr)
5166 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005167 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005168 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005169 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005170 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005171 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005172
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005173 /* Handle "'" and "\" first, as they won't play nice with
5174 * i_peek_and_eat_bkslash_nl() anyway:
5175 * echo z\\
5176 * and
5177 * echo '\
5178 * '
5179 * would break.
5180 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005181 if (ch == '\\') {
5182 ch = i_getch(input);
5183 if (ch == '\n')
5184 continue; /* drop \<newline>, get next char */
5185 nommu_addchr(&ctx.as_string, '\\');
5186 o_addchr(&ctx.word, '\\');
5187 if (ch == EOF) {
5188 /* Testcase: eval 'echo Ok\' */
5189 /* bash-4.3.43 was removing backslash,
5190 * but 4.4.19 retains it, most other shells too
5191 */
5192 continue; /* get next char */
5193 }
5194 /* Example: echo Hello \2>file
5195 * we need to know that word 2 is quoted
5196 */
5197 ctx.word.has_quoted_part = 1;
5198 nommu_addchr(&ctx.as_string, ch);
5199 o_addchr(&ctx.word, ch);
5200 continue; /* get next char */
5201 }
5202 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005203 if (ch == '\'') {
5204 ctx.word.has_quoted_part = 1;
5205 next = i_getch(input);
5206 if (next == '\'' && !ctx.pending_redirect)
5207 goto insert_empty_quoted_str_marker;
5208
5209 ch = next;
5210 while (1) {
5211 if (ch == EOF) {
5212 syntax_error_unterm_ch('\'');
5213 goto parse_error;
5214 }
5215 nommu_addchr(&ctx.as_string, ch);
5216 if (ch == '\'')
5217 break;
5218 if (ch == SPECIAL_VAR_SYMBOL) {
5219 /* Convert raw ^C to corresponding special variable reference */
5220 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5221 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5222 }
5223 o_addqchr(&ctx.word, ch);
5224 ch = i_getch(input);
5225 }
5226 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005227 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005228
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005229 next = '\0';
5230 if (ch != '\n')
5231 next = i_peek_and_eat_bkslash_nl(input);
5232
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005233 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005234 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005235 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005236 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005237 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005238 || ctx.word.length /* word{... - non-special */
5239 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005240 || (next != ';' /* }; - special */
5241 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005242 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005243 && next != '&' /* }& and }&& ... - special */
5244 && next != '|' /* }|| ... - special */
5245 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005246 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005247 ) {
5248 /* They are not special, skip "{}" */
5249 is_special += 2;
5250 }
5251 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005252 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005253
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005254 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005255 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005256 o_addQchr(&ctx.word, ch);
5257 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5258 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005259 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005260 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005261 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005262 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5263 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005264 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005265 continue;
5266 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005267
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005268 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005269#if ENABLE_HUSH_LINENO_VAR
5270/* Case:
5271 * "while ...; do<whitespace><newline>
5272 * cmd ..."
5273 * would think that "cmd" starts in <whitespace> -
5274 * i.e., at the previous line.
5275 * We need to skip all whitespace before newlines.
5276 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005277 while (ch != '\n') {
5278 next = i_peek(input);
5279 if (next != ' ' && next != '\t' && next != '\n')
5280 break; /* next char is not ws */
5281 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005282 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005283 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005284#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005285 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005286 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005287 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005288 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005289 /* Is this a case when newline is simply ignored?
5290 * Some examples:
5291 * "cmd | <newline> cmd ..."
5292 * "case ... in <newline> word) ..."
5293 */
5294 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005295 && ctx.word.length == 0
5296 && !ctx.word.has_quoted_part
5297 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005298 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005299 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005300 * Without check #1, interactive shell
5301 * ignores even bare <newline>,
5302 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005303 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005304 * ps2> _ <=== wrong, should be ps1
5305 * Without check #2, "cmd & <newline>"
5306 * is similarly mistreated.
5307 * (BTW, this makes "cmd & cmd"
5308 * and "cmd && cmd" non-orthogonal.
5309 * Really, ask yourself, why
5310 * "cmd && <newline>" doesn't start
5311 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005312 * The only reason is that it might be
5313 * a "cmd1 && <nl> cmd2 &" construct,
5314 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005315 */
5316 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005317 if (pi->num_cmds != 0 /* check #1 */
5318 && pi->followup != PIPE_BG /* check #2 */
5319 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005320 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005321 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005322 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005323 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005324 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005325 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005326 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005327 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5328 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005329 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005330 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005331 ctx.is_assignment = MAYBE_ASSIGNMENT;
5332 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005333 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005334 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005335 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005336 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005337 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005338
5339 /* "cmd}" or "cmd }..." without semicolon or &:
5340 * } is an ordinary char in this case, even inside { cmd; }
5341 * Pathological example: { ""}; } should exec "}" cmd
5342 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005343 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005344 if (ctx.word.length != 0 /* word} */
5345 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005346 ) {
5347 goto ordinary_char;
5348 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005349 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5350 /* Generally, there should be semicolon: "cmd; }"
5351 * However, bash allows to omit it if "cmd" is
5352 * a group. Examples:
5353 * { { echo 1; } }
5354 * {(echo 1)}
5355 * { echo 0 >&2 | { echo 1; } }
5356 * { while false; do :; done }
5357 * { case a in b) ;; esac }
5358 */
5359 if (ctx.command->group)
5360 goto term_group;
5361 goto ordinary_char;
5362 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005363 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005364 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005365 goto skip_end_trigger;
5366 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005367 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005368 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005369 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005370 && (ch != ';' || heredoc_cnt == 0)
5371#if ENABLE_HUSH_CASE
5372 && (ch != ')'
5373 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005374 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005375 )
5376#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005377 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005378 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005379 goto parse_error;
5380 }
5381 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005382 ctx.is_assignment = MAYBE_ASSIGNMENT;
5383 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005384 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005385 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005386 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005387 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005388 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005389#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005390 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005391 if (pstring)
5392 *pstring = ctx.as_string.data;
5393 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005394 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005395#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005396 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5397 /* Example: bare "{ }", "()" */
5398 G.last_exitcode = 2; /* bash compat */
5399 syntax_error_unexpected_ch(ch);
5400 goto parse_error2;
5401 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005402 if (heredoc_cnt_ptr)
5403 *heredoc_cnt_ptr = heredoc_cnt;
5404 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005405 debug_printf_parse("parse_stream return %p: "
5406 "end_trigger char found\n",
5407 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005408 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005409 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005410 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005411 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005412
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005413 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005414 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005415
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005416 /* Catch <, > before deciding whether this word is
5417 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5418 switch (ch) {
5419 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005420 redir_fd = redirect_opt_num(&ctx.word);
5421 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005422 goto parse_error;
5423 }
5424 redir_style = REDIRECT_OVERWRITE;
5425 if (next == '>') {
5426 redir_style = REDIRECT_APPEND;
5427 ch = i_getch(input);
5428 nommu_addchr(&ctx.as_string, ch);
5429 }
5430#if 0
5431 else if (next == '(') {
5432 syntax_error(">(process) not supported");
5433 goto parse_error;
5434 }
5435#endif
5436 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5437 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005438 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005439 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005440 redir_fd = redirect_opt_num(&ctx.word);
5441 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005442 goto parse_error;
5443 }
5444 redir_style = REDIRECT_INPUT;
5445 if (next == '<') {
5446 redir_style = REDIRECT_HEREDOC;
5447 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005448 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005449 ch = i_getch(input);
5450 nommu_addchr(&ctx.as_string, ch);
5451 } else if (next == '>') {
5452 redir_style = REDIRECT_IO;
5453 ch = i_getch(input);
5454 nommu_addchr(&ctx.as_string, ch);
5455 }
5456#if 0
5457 else if (next == '(') {
5458 syntax_error("<(process) not supported");
5459 goto parse_error;
5460 }
5461#endif
5462 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5463 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005464 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005465 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005466 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005467 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005468 /* note: we do not add it to &ctx.as_string */
5469/* TODO: in bash:
5470 * comment inside $() goes to the next \n, even inside quoted string (!):
5471 * cmd "$(cmd2 #comment)" - syntax error
5472 * cmd "`cmd2 #comment`" - ok
5473 * We accept both (comment ends where command subst ends, in both cases).
5474 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005475 while (1) {
5476 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005477 if (ch == '\n') {
5478 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005479 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005480 }
5481 ch = i_getch(input);
5482 if (ch == EOF)
5483 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005484 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005485 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005486 }
5487 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005488 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005489 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005490
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005491 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005492 /* check that we are not in word in "a=1 2>word b=1": */
5493 && !ctx.pending_redirect
5494 ) {
5495 /* ch is a special char and thus this word
5496 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005497 ctx.is_assignment = NOT_ASSIGNMENT;
5498 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005499 }
5500
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005501 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5502
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005503 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005504 case SPECIAL_VAR_SYMBOL:
5505 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005506 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5507 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005508 /* fall through */
5509 case '#':
5510 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005511 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005512 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005513 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005514 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005515 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005516 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005517 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005518 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005519 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005520 case '"':
5521 ctx.word.has_quoted_part = 1;
5522 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005523 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005524 insert_empty_quoted_str_marker:
5525 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005526 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5527 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005528 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005529 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005530 if (ctx.is_assignment == NOT_ASSIGNMENT)
5531 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005532 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005533 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005534 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005535 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005536#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005537 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005538 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005539
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005540 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5541 o_addchr(&ctx.word, '`');
5542 USE_FOR_NOMMU(pos = ctx.word.length;)
5543 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005544 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005545# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005546 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005547 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005548# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005549 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5550 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005551 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005552 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005553#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005554 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005555#if ENABLE_HUSH_CASE
5556 case_semi:
5557#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005558 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005559 goto parse_error;
5560 }
5561 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005562#if ENABLE_HUSH_CASE
5563 /* Eat multiple semicolons, detect
5564 * whether it means something special */
5565 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005566 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005567 if (ch != ';')
5568 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005569 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005570 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005571 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005572 ctx.ctx_dsemicolon = 1;
5573 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005574 break;
5575 }
5576 }
5577#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005578 new_cmd:
5579 /* We just finished a cmd. New one may start
5580 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005581 ctx.is_assignment = MAYBE_ASSIGNMENT;
5582 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005583 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005584 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005585 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005586 goto parse_error;
5587 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005588 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005589 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005590 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005591 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005592 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005593 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005594 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005595 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005596 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005597 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005598 goto parse_error;
5599 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005600#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005601 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005602 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005603#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005604 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005605 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005606 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005607 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005608 } else {
5609 /* we could pick up a file descriptor choice here
5610 * with redirect_opt_num(), but bash doesn't do it.
5611 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005612 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005613 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005614 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005615 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005616#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005617 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005618 if (ctx.ctx_res_w == RES_MATCH
5619 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005620 && ctx.word.length == 0 /* not word(... */
5621 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005622 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005623 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005624 }
5625#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005626 /* fall through */
5627 case '{': {
5628 int n = parse_group(&ctx, input, ch);
5629 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005630 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005631 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005632 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5633 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005634 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005635 }
Eric Andersen25f27032001-04-26 23:22:31 +00005636 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005637#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005638 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005639 goto case_semi;
5640#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005641
Eric Andersen25f27032001-04-26 23:22:31 +00005642 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005643 /* proper use of this character is caught by end_trigger:
5644 * if we see {, we call parse_group(..., end_trigger='}')
5645 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005646 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005647 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005648 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005649 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005650 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005651 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005652 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005653 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005654
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005655 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005656 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005657 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005658 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005659 struct parse_context *pctx;
5660 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005661
5662 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005663 * Sample for finding leaks on syntax error recovery path.
5664 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005665 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005666 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005667 * while if (true | { true;}); then echo ok; fi; do break; done
5668 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005669 */
5670 pctx = &ctx;
5671 do {
5672 /* Update pipe/command counts,
5673 * otherwise freeing may miss some */
5674 done_pipe(pctx, PIPE_SEQ);
5675 debug_printf_clean("freeing list %p from ctx %p\n",
5676 pctx->list_head, pctx);
5677 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005678 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005679 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005680#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005681 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005682#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005683 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005684 if (pctx != &ctx) {
5685 free(pctx);
5686 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005687 IF_HAS_KEYWORDS(pctx = p2;)
5688 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005689
Denys Vlasenko474cb202018-07-24 13:03:03 +02005690 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005691#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005692 if (pstring)
5693 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005694#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005695 debug_leave();
5696 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005697 }
Eric Andersen25f27032001-04-26 23:22:31 +00005698}
5699
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005700
5701/*** Execution routines ***/
5702
5703/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005704#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005705#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005706 expand_string_to_string(str)
5707#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005708static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005709#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005710static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005711#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005712static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005713
5714/* expand_strvec_to_strvec() takes a list of strings, expands
5715 * all variable references within and returns a pointer to
5716 * a list of expanded strings, possibly with larger number
5717 * of strings. (Think VAR="a b"; echo $VAR).
5718 * This new list is allocated as a single malloc block.
5719 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005720 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005721 * Caller can deallocate entire list by single free(list). */
5722
Denys Vlasenko238081f2010-10-03 14:26:26 +02005723/* A horde of its helpers come first: */
5724
5725static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5726{
5727 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005728 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005729
Denys Vlasenko9e800222010-10-03 14:28:04 +02005730#if ENABLE_HUSH_BRACE_EXPANSION
5731 if (c == '{' || c == '}') {
5732 /* { -> \{, } -> \} */
5733 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005734 /* And now we want to add { or } and continue:
5735 * o_addchr(o, c);
5736 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005737 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005738 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005739 }
5740#endif
5741 o_addchr(o, c);
5742 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005743 /* \z -> \\\z; \<eol> -> \\<eol> */
5744 o_addchr(o, '\\');
5745 if (len) {
5746 len--;
5747 o_addchr(o, '\\');
5748 o_addchr(o, *str++);
5749 }
5750 }
5751 }
5752}
5753
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005754/* Store given string, finalizing the word and starting new one whenever
5755 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005756 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005757 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005758 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5759 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005760static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005761{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005762 int last_is_ifs = 0;
5763
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005764 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005765 int word_len;
5766
5767 if (!*str) /* EOL - do not finalize word */
5768 break;
5769 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005770 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005771 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005772 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005773 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005774 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005775 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005776 * Example: "v='\*'; echo b$v" prints "b\*"
5777 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005778 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005779 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005780 /*/ Why can't we do it easier? */
5781 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5782 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5783 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005784 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005785 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005786 if (!*str) /* EOL - do not finalize word */
5787 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005788 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005789
5790 /* We know str here points to at least one IFS char */
5791 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005792 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005793 if (!*str) /* EOL - do not finalize word */
5794 break;
5795
Denys Vlasenko96786362018-04-11 16:02:58 +02005796 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5797 && strchr(G.ifs, *str) /* the second check would fail */
5798 ) {
5799 /* This is a non-whitespace $IFS char */
5800 /* Skip it and IFS whitespace chars, start new word */
5801 str++;
5802 str += strspn(str, G.ifs_whitespace);
5803 goto new_word;
5804 }
5805
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005806 /* Start new word... but not always! */
5807 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005808 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005809 /*
5810 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005811 * here nothing precedes the space in $v expansion,
5812 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005813 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005814 * It's okay if this accesses the byte before first argv[]:
5815 * past call to o_save_ptr() cleared it to zero byte
5816 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005817 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005818 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005819 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005820 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005821 o_addchr(output, '\0');
5822 debug_print_list("expand_on_ifs", output, n);
5823 n = o_save_ptr(output, n);
5824 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005825 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005826
Denys Vlasenko168579a2018-07-19 13:45:54 +02005827 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005828 debug_print_list("expand_on_ifs[1]", output, n);
5829 return n;
5830}
5831
5832/* Helper to expand $((...)) and heredoc body. These act as if
5833 * they are in double quotes, with the exception that they are not :).
5834 * Just the rules are similar: "expand only $var and `cmd`"
5835 *
5836 * Returns malloced string.
5837 * As an optimization, we return NULL if expansion is not needed.
5838 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005839static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005840{
5841 char *exp_str;
5842 struct in_str input;
5843 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005844 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005845
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005846 cp = str;
5847 for (;;) {
5848 if (!*cp) return NULL; /* string has no special chars */
5849 if (*cp == '$') break;
5850 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005851#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005852 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005853#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005854 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005855 }
5856
5857 /* We need to expand. Example:
5858 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5859 */
5860 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005861 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005862//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005863 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005864 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005865 EXP_FLAG_ESC_GLOB_CHARS,
5866 /*unbackslash:*/ 1
5867 );
5868 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005869 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005870 return exp_str;
5871}
5872
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005873/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5874 * These can contain single- and double-quoted strings,
5875 * and treated as if the ARG string is initially unquoted. IOW:
5876 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5877 * a dquoted string: "${var#"zz"}"), the difference only comes later
5878 * (word splitting and globbing of the ${var...} result).
5879 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005880#if !BASH_PATTERN_SUBST
5881#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5882 encode_then_expand_vararg(str, handle_squotes)
5883#endif
5884static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5885{
5886#if !BASH_PATTERN_SUBST
5887 const int do_unbackslash = 0;
5888#endif
5889 char *exp_str;
5890 struct in_str input;
5891 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005892 const char *cp;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005893
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005894 cp = str;
5895 for (;;) {
5896 if (!*cp) return NULL; /* string has no special chars */
5897 if (*cp == '$') break;
5898 if (*cp == '\\') break;
5899 if (*cp == '\'') break;
5900 if (*cp == '"') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005901#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005902 if (*cp == '`') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005903#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005904 cp++;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005905 }
5906
Denys Vlasenkob762c782018-07-17 14:21:38 +02005907 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005908 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005909 exp_str = NULL;
5910
5911 for (;;) {
5912 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005913
5914 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005915 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5916 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005917
5918 if (!dest.o_expflags) {
5919 if (ch == EOF)
5920 break;
5921 if (handle_squotes && ch == '\'') {
5922 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02005923 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005924 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005925 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005926 }
5927 if (ch == EOF) {
5928 syntax_error_unterm_ch('"');
5929 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005930 }
5931 if (ch == '"') {
5932 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5933 continue;
5934 }
5935 if (ch == '\\') {
5936 ch = i_getch(&input);
5937 if (ch == EOF) {
5938//example? error message? syntax_error_unterm_ch('"');
5939 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5940 goto ret;
5941 }
5942 o_addqchr(&dest, ch);
5943 continue;
5944 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02005945 if (ch == '$') {
5946 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5947 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5948 goto ret;
5949 }
5950 continue;
5951 }
5952#if ENABLE_HUSH_TICK
5953 if (ch == '`') {
5954 //unsigned pos = dest->length;
5955 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5956 o_addchr(&dest, 0x80 | '`');
5957 if (!add_till_backquote(&dest, &input,
5958 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5959 )
5960 ) {
5961 goto ret; /* error */
5962 }
5963 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5964 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5965 continue;
5966 }
5967#endif
5968 o_addQchr(&dest, ch);
5969 } /* for (;;) */
5970
5971 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5972 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02005973 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5974 do_unbackslash
5975 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02005976 ret:
5977 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005978 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005979 return exp_str;
5980}
5981
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005982/* Expanding ARG in ${var+ARG}, ${var-ARG}
5983 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02005984static int encode_then_append_var_plusminus(o_string *output, int n,
5985 const char *str, int dquoted)
5986{
5987 struct in_str input;
5988 o_string dest = NULL_O_STRING;
5989
5990#if 0 //todo?
5991 const char *cp;
5992 cp = str;
5993 for (;;) {
5994 if (!*cp) return NULL; /* string has no special chars */
5995 if (*cp == '$') break;
5996 if (*cp == '\\') break;
5997 if (*cp == '\'') break;
5998 if (*cp == '"') break;
5999#if ENABLE_HUSH_TICK
6000 if (*cp == '`') break;
6001#endif
6002 cp++;
6003 }
6004#endif
6005
Denys Vlasenko294eb462018-07-20 16:18:59 +02006006 setup_string_in_str(&input, str);
6007
6008 for (;;) {
6009 int ch;
6010
6011 ch = i_getch(&input);
6012 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6013 __func__, ch, ch, dest.o_expflags);
6014
6015 if (!dest.o_expflags) {
6016 if (ch == EOF)
6017 break;
6018 if (!dquoted && strchr(G.ifs, ch)) {
6019 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6020 * do not assume we are at the start of the word (PREFIX above).
6021 */
6022 if (dest.data) {
6023 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006024 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006025 o_addchr(output, '\0');
6026 n = o_save_ptr(output, n); /* create next word */
6027 } else
6028 if (output->length != o_get_last_ptr(output, n)
6029 || output->has_quoted_part
6030 ) {
6031 /* For these cases:
6032 * f() { for i; do echo "|$i|"; done; }; x=x
6033 * f a${x:+ }b # 1st condition
6034 * |a|
6035 * |b|
6036 * f ""${x:+ }b # 2nd condition
6037 * ||
6038 * |b|
6039 */
6040 o_addchr(output, '\0');
6041 n = o_save_ptr(output, n); /* create next word */
6042 }
6043 continue;
6044 }
6045 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006046 if (!add_till_single_quote_dquoted(&dest, &input))
6047 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006048 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6049 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006050 continue;
6051 }
6052 }
6053 if (ch == EOF) {
6054 syntax_error_unterm_ch('"');
6055 goto ret; /* error */
6056 }
6057 if (ch == '"') {
6058 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006059 if (dest.o_expflags) {
6060 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6061 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6062 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006063 continue;
6064 }
6065 if (ch == '\\') {
6066 ch = i_getch(&input);
6067 if (ch == EOF) {
6068//example? error message? syntax_error_unterm_ch('"');
6069 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6070 goto ret;
6071 }
6072 o_addqchr(&dest, ch);
6073 continue;
6074 }
6075 if (ch == '$') {
6076 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6077 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6078 goto ret;
6079 }
6080 continue;
6081 }
6082#if ENABLE_HUSH_TICK
6083 if (ch == '`') {
6084 //unsigned pos = dest->length;
6085 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6086 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6087 if (!add_till_backquote(&dest, &input,
6088 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6089 )
6090 ) {
6091 goto ret; /* error */
6092 }
6093 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6094 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6095 continue;
6096 }
6097#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006098 if (dquoted) {
6099 /* Always glob-protect if in dquotes:
6100 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6101 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6102 */
6103 o_addqchr(&dest, ch);
6104 } else {
6105 /* Glob-protect only if char is quoted:
6106 * x=x; echo ${x:+/bin/c*} - prints many filenames
6107 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6108 */
6109 o_addQchr(&dest, ch);
6110 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006111 } /* for (;;) */
6112
6113 if (dest.data) {
6114 n = expand_vars_to_list(output, n, dest.data);
6115 }
6116 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006117 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006118 return n;
6119}
6120
Denys Vlasenko0b883582016-12-23 16:49:07 +01006121#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006122static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006123{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006124 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006125 arith_t res;
6126 char *exp_str;
6127
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006128 math_state.lookupvar = get_local_var_value;
6129 math_state.setvar = set_local_var_from_halves;
6130 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006131 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006132 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006133 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006134 if (errmsg_p)
6135 *errmsg_p = math_state.errmsg;
6136 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006137 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006138 return res;
6139}
6140#endif
6141
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006142#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006143/* ${var/[/]pattern[/repl]} helpers */
6144static char *strstr_pattern(char *val, const char *pattern, int *size)
6145{
6146 while (1) {
6147 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6148 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6149 if (end) {
6150 *size = end - val;
6151 return val;
6152 }
6153 if (*val == '\0')
6154 return NULL;
6155 /* Optimization: if "*pat" did not match the start of "string",
6156 * we know that "tring", "ring" etc will not match too:
6157 */
6158 if (pattern[0] == '*')
6159 return NULL;
6160 val++;
6161 }
6162}
6163static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6164{
6165 char *result = NULL;
6166 unsigned res_len = 0;
6167 unsigned repl_len = strlen(repl);
6168
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006169 /* Null pattern never matches, including if "var" is empty */
6170 if (!pattern[0])
6171 return result; /* NULL, no replaces happened */
6172
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006173 while (1) {
6174 int size;
6175 char *s = strstr_pattern(val, pattern, &size);
6176 if (!s)
6177 break;
6178
6179 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006180 strcpy(mempcpy(result + res_len, val, s - val), repl);
6181 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006182 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6183
6184 val = s + size;
6185 if (exp_op == '/')
6186 break;
6187 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006188 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006189 result = xrealloc(result, res_len + strlen(val) + 1);
6190 strcpy(result + res_len, val);
6191 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6192 }
6193 debug_printf_varexp("result:'%s'\n", result);
6194 return result;
6195}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006196#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006197
Denys Vlasenko168579a2018-07-19 13:45:54 +02006198static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006199 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006200{
6201 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6202 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6203 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6204 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006205 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006206 } else { /* quoted "$VAR" */
6207 output->has_quoted_part = 1;
6208 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6209 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6210 if (val && val[0])
6211 o_addQstr(output, val);
6212 }
6213 return n;
6214}
6215
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006216/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006217 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006218static NOINLINE int expand_one_var(o_string *output, int n,
6219 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006220{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006221 const char *val;
6222 char *to_be_freed;
6223 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006224 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006225 char exp_op;
6226 char exp_save = exp_save; /* for compiler */
6227 char *exp_saveptr; /* points to expansion operator */
6228 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006229 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006230
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006231 val = NULL;
6232 to_be_freed = NULL;
6233 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006234 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006235 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006236 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006237 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006238 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006239 exp_op = 0;
6240
Denys Vlasenkob762c782018-07-17 14:21:38 +02006241 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006242 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6243 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6244 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006245 ) {
6246 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006247 var++;
6248 exp_op = 'L';
6249 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006250 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006251 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006252 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006253 ) {
6254 /* ${?:0}, ${#[:]%0} etc */
6255 exp_saveptr = var + 1;
6256 } else {
6257 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6258 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6259 }
6260 exp_op = exp_save = *exp_saveptr;
6261 if (exp_op) {
6262 exp_word = exp_saveptr + 1;
6263 if (exp_op == ':') {
6264 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006265//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006266 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006267 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006268 ) {
6269 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6270 exp_op = ':';
6271 exp_word--;
6272 }
6273 }
6274 *exp_saveptr = '\0';
6275 } /* else: it's not an expansion op, but bare ${var} */
6276 }
6277
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006278 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006279 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006280 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006281 int nn = xatoi_positive(var);
6282 if (nn < G.global_argc)
6283 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006284 /* else val remains NULL: $N with too big N */
6285 } else {
6286 switch (var[0]) {
6287 case '$': /* pid */
6288 val = utoa(G.root_pid);
6289 break;
6290 case '!': /* bg pid */
6291 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6292 break;
6293 case '?': /* exitcode */
6294 val = utoa(G.last_exitcode);
6295 break;
6296 case '#': /* argc */
6297 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6298 break;
6299 default:
6300 val = get_local_var_value(var);
6301 }
6302 }
6303
6304 /* Handle any expansions */
6305 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006306 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006307 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006308 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006309 debug_printf_expand("%s\n", val);
6310 } else if (exp_op) {
6311 if (exp_op == '%' || exp_op == '#') {
6312 /* Standard-mandated substring removal ops:
6313 * ${parameter%word} - remove smallest suffix pattern
6314 * ${parameter%%word} - remove largest suffix pattern
6315 * ${parameter#word} - remove smallest prefix pattern
6316 * ${parameter##word} - remove largest prefix pattern
6317 *
6318 * Word is expanded to produce a glob pattern.
6319 * Then var's value is matched to it and matching part removed.
6320 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006321//FIXME: ${x#...${...}...}
6322//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6323//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006324 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006325 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006326 char *exp_exp_word;
6327 char *loc;
6328 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006329 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006330 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006331 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006332 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006333 if (exp_exp_word)
6334 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006335 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6336 /*
6337 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006338 * G.global_argv and results of utoa and get_local_var_value
6339 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006340 * scan_and_match momentarily stores NULs there.
6341 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006342 t = (char*)val;
6343 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006344 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006345 free(exp_exp_word);
6346 if (loc) { /* match was found */
6347 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006348 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006349 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006350 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006351 }
6352 }
6353 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006354#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006355 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006356 /* It's ${var/[/]pattern[/repl]} thing.
6357 * Note that in encoded form it has TWO parts:
6358 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006359 * and if // is used, it is encoded as \:
6360 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006361 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006362 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006363 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006364 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006365 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006366 * >az >bz
6367 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6368 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6369 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6370 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006371 * (note that a*z _pattern_ is never globbed!)
6372 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006373 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006374 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006375 if (!pattern)
6376 pattern = xstrdup(exp_word);
6377 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6378 *p++ = SPECIAL_VAR_SYMBOL;
6379 exp_word = p;
6380 p = strchr(p, SPECIAL_VAR_SYMBOL);
6381 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006382 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006383 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6384 /* HACK ALERT. We depend here on the fact that
6385 * G.global_argv and results of utoa and get_local_var_value
6386 * are actually in writable memory:
6387 * replace_pattern momentarily stores NULs there. */
6388 t = (char*)val;
6389 to_be_freed = replace_pattern(t,
6390 pattern,
6391 (repl ? repl : exp_word),
6392 exp_op);
6393 if (to_be_freed) /* at least one replace happened */
6394 val = to_be_freed;
6395 free(pattern);
6396 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006397 } else {
6398 /* Empty variable always gives nothing */
6399 // "v=''; echo ${v/*/w}" prints "", not "w"
6400 /* Just skip "replace" part */
6401 *p++ = SPECIAL_VAR_SYMBOL;
6402 p = strchr(p, SPECIAL_VAR_SYMBOL);
6403 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006404 }
6405 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006406#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006407 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006408#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006409 /* It's ${var:N[:M]} bashism.
6410 * Note that in encoded form it has TWO parts:
6411 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6412 */
6413 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006414 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006415
Denys Vlasenko063847d2010-09-15 13:33:02 +02006416 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6417 if (errmsg)
6418 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006419 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6420 *p++ = SPECIAL_VAR_SYMBOL;
6421 exp_word = p;
6422 p = strchr(p, SPECIAL_VAR_SYMBOL);
6423 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006424 len = expand_and_evaluate_arith(exp_word, &errmsg);
6425 if (errmsg)
6426 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006427 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006428 if (beg < 0) {
6429 /* negative beg counts from the end */
6430 beg = (arith_t)strlen(val) + beg;
6431 if (beg < 0) /* ${v: -999999} is "" */
6432 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006433 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006434 debug_printf_varexp("from val:'%s'\n", val);
6435 if (len < 0) {
6436 /* in bash, len=-n means strlen()-n */
6437 len = (arith_t)strlen(val) - beg + len;
6438 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006439 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006440 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006441 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006442 arith_err:
6443 val = NULL;
6444 } else {
6445 /* Paranoia. What if user entered 9999999999999
6446 * which fits in arith_t but not int? */
6447 if (len >= INT_MAX)
6448 len = INT_MAX;
6449 val = to_be_freed = xstrndup(val + beg, len);
6450 }
6451 debug_printf_varexp("val:'%s'\n", val);
6452#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006453 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006454 val = NULL;
6455#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006456 } else { /* one of "-=+?" */
6457 /* Standard-mandated substitution ops:
6458 * ${var?word} - indicate error if unset
6459 * If var is unset, word (or a message indicating it is unset
6460 * if word is null) is written to standard error
6461 * and the shell exits with a non-zero exit status.
6462 * Otherwise, the value of var is substituted.
6463 * ${var-word} - use default value
6464 * If var is unset, word is substituted.
6465 * ${var=word} - assign and use default value
6466 * If var is unset, word is assigned to var.
6467 * In all cases, final value of var is substituted.
6468 * ${var+word} - use alternative value
6469 * If var is unset, null is substituted.
6470 * Otherwise, word is substituted.
6471 *
6472 * Word is subjected to tilde expansion, parameter expansion,
6473 * command substitution, and arithmetic expansion.
6474 * If word is not needed, it is not expanded.
6475 *
6476 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6477 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006478 *
6479 * Word-splitting and single quote behavior:
6480 *
6481 * $ f() { for i; do echo "|$i|"; done; };
6482 *
6483 * $ x=; f ${x:?'x y' z}
6484 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6485 * $ x=; f "${x:?'x y' z}"
6486 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6487 *
6488 * $ x=; f ${x:='x y' z}
6489 * |x|
6490 * |y|
6491 * |z|
6492 * $ x=; f "${x:='x y' z}"
6493 * |'x y' z|
6494 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006495 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006496 * |x y|
6497 * |z|
6498 * $ x=x; f "${x:+'x y' z}"
6499 * |'x y' z|
6500 *
6501 * $ x=; f ${x:-'x y' z}
6502 * |x y|
6503 * |z|
6504 * $ x=; f "${x:-'x y' z}"
6505 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006506 */
6507 int use_word = (!val || ((exp_save == ':') && !val[0]));
6508 if (exp_op == '+')
6509 use_word = !use_word;
6510 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6511 (exp_save == ':') ? "true" : "false", use_word);
6512 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006513 if (exp_op == '+' || exp_op == '-') {
6514 /* ${var+word} - use alternative value */
6515 /* ${var-word} - use default value */
6516 n = encode_then_append_var_plusminus(output, n, exp_word,
6517 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006518 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006519 val = NULL;
6520 } else {
6521 /* ${var?word} - indicate error if unset */
6522 /* ${var=word} - assign and use default value */
6523 to_be_freed = encode_then_expand_vararg(exp_word,
6524 /*handle_squotes:*/ !(arg0 & 0x80),
6525 /*unbackslash:*/ 0
6526 );
6527 if (to_be_freed)
6528 exp_word = to_be_freed;
6529 if (exp_op == '?') {
6530 /* mimic bash message */
6531 msg_and_die_if_script("%s: %s",
6532 var,
6533 exp_word[0]
6534 ? exp_word
6535 : "parameter null or not set"
6536 /* ash has more specific messages, a-la: */
6537 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6538 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006539//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006540//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006541// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6542// bash: x: x y z
6543// $
6544// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006545 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006546 val = exp_word;
6547 }
6548 if (exp_op == '=') {
6549 /* ${var=[word]} or ${var:=[word]} */
6550 if (isdigit(var[0]) || var[0] == '#') {
6551 /* mimic bash message */
6552 msg_and_die_if_script("$%s: cannot assign in this way", var);
6553 val = NULL;
6554 } else {
6555 char *new_var = xasprintf("%s=%s", var, val);
6556 set_local_var(new_var, /*flag:*/ 0);
6557 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006558 }
6559 }
6560 }
6561 } /* one of "-=+?" */
6562
6563 *exp_saveptr = exp_save;
6564 } /* if (exp_op) */
6565
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006566 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006567 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006568
Denys Vlasenko168579a2018-07-19 13:45:54 +02006569 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006570
6571 free(to_be_freed);
6572 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006573}
6574
6575/* Expand all variable references in given string, adding words to list[]
6576 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6577 * to be filled). This routine is extremely tricky: has to deal with
6578 * variables/parameters with whitespace, $* and $@, and constructs like
6579 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006580static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006581{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006582 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006583 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006584 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006585 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006586 char *p;
6587
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006588 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6589 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006590 debug_print_list("expand_vars_to_list[0]", output, n);
6591
6592 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6593 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006594#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006595 char arith_buf[sizeof(arith_t)*3 + 2];
6596#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006597
Denys Vlasenko168579a2018-07-19 13:45:54 +02006598 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006599 o_addchr(output, '\0');
6600 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006601 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006602 }
6603
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006604 o_addblock(output, arg, p - arg);
6605 debug_print_list("expand_vars_to_list[1]", output, n);
6606 arg = ++p;
6607 p = strchr(p, SPECIAL_VAR_SYMBOL);
6608
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006609 /* Fetch special var name (if it is indeed one of them)
6610 * and quote bit, force the bit on if singleword expansion -
6611 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006612 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006613
6614 /* Is this variable quoted and thus expansion can't be null?
6615 * "$@" is special. Even if quoted, it can still
6616 * expand to nothing (not even an empty string),
6617 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006618 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006619 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006620
6621 switch (first_ch & 0x7f) {
6622 /* Highest bit in first_ch indicates that var is double-quoted */
6623 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006624 case '@': {
6625 int i;
6626 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006627 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006628 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006629 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006630 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006631 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006632 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006633 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6634 if (G.global_argv[i++][0] && G.global_argv[i]) {
6635 /* this argv[] is not empty and not last:
6636 * put terminating NUL, start new word */
6637 o_addchr(output, '\0');
6638 debug_print_list("expand_vars_to_list[2]", output, n);
6639 n = o_save_ptr(output, n);
6640 debug_print_list("expand_vars_to_list[3]", output, n);
6641 }
6642 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006643 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006644 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006645 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006646 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006647 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006648 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006649 while (1) {
6650 o_addQstr(output, G.global_argv[i]);
6651 if (++i >= G.global_argc)
6652 break;
6653 o_addchr(output, '\0');
6654 debug_print_list("expand_vars_to_list[4]", output, n);
6655 n = o_save_ptr(output, n);
6656 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006657 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006658 while (1) {
6659 o_addQstr(output, G.global_argv[i]);
6660 if (!G.global_argv[++i])
6661 break;
6662 if (G.ifs[0])
6663 o_addchr(output, G.ifs[0]);
6664 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006665 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006666 }
6667 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006668 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006669 case SPECIAL_VAR_SYMBOL: {
6670 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006671 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006672 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006673 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006674 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006675 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006676 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006677 case SPECIAL_VAR_QUOTED_SVS:
6678 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006679 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006680 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006681 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006682 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006683#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006684 case '`': {
6685 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006686 o_string subst_result = NULL_O_STRING;
6687
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006688 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006689 arg++;
6690 /* Can't just stuff it into output o_string,
6691 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006692 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006693 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6694 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006695 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006696 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006697 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006698 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006699 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006700 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006701#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006702#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006703 case '+': {
6704 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006705 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006706
6707 arg++; /* skip '+' */
6708 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6709 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006710 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006711 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6712 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006713 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006714 break;
6715 }
6716#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006717 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006718 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006719 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006720 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006721 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6722
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006723 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6724 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006725 if (*p != SPECIAL_VAR_SYMBOL)
6726 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006727 arg = ++p;
6728 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6729
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006730 if (*arg) {
6731 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006732 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006733 o_addchr(output, '\0');
6734 n = o_save_ptr(output, n);
6735 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006736 debug_print_list("expand_vars_to_list[a]", output, n);
6737 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006738 * if needed (much earlier), do not use o_addQstr here!
6739 */
6740 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006741 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006742 } else
6743 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006744 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6745 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006746 ) {
6747 n--;
6748 /* allow to reuse list[n] later without re-growth */
6749 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006750 }
6751
6752 return n;
6753}
6754
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006755static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006756{
6757 int n;
6758 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006759 o_string output = NULL_O_STRING;
6760
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006761 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006762
6763 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006764 for (;;) {
6765 /* go to next list[n] */
6766 output.ended_in_ifs = 0;
6767 n = o_save_ptr(&output, n);
6768
6769 if (!*argv)
6770 break;
6771
6772 /* expand argv[i] */
6773 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006774 /* if (!output->has_empty_slot) -- need this?? */
6775 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006776 }
6777 debug_print_list("expand_variables", &output, n);
6778
6779 /* output.data (malloced in one block) gets returned in "list" */
6780 list = o_finalize_list(&output, n);
6781 debug_print_strings("expand_variables[1]", list);
6782 return list;
6783}
6784
6785static char **expand_strvec_to_strvec(char **argv)
6786{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006787 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006788}
6789
Denys Vlasenko11752d42018-04-03 08:20:58 +02006790#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006791static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6792{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006793 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006794}
6795#endif
6796
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006797/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006798 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006799 *
6800 * NB: should NOT do globbing!
6801 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6802 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006803static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006804{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006805#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006806 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006807 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006808#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006809 char *argv[2], **list;
6810
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006811 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006812 /* This is generally an optimization, but it also
6813 * handles "", which otherwise trips over !list[0] check below.
6814 * (is this ever happens that we actually get str="" here?)
6815 */
6816 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6817 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006818 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006819 return xstrdup(str);
6820 }
6821
6822 argv[0] = (char*)str;
6823 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006824 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006825 if (!list[0]) {
6826 /* Example where it happens:
6827 * x=; echo ${x:-"$@"}
6828 */
6829 ((char*)list)[0] = '\0';
6830 } else {
6831 if (HUSH_DEBUG)
6832 if (list[1])
6833 bb_error_msg_and_die("BUG in varexp2");
6834 /* actually, just move string 2*sizeof(char*) bytes back */
6835 overlapping_strcpy((char*)list, list[0]);
6836 if (do_unbackslash)
6837 unbackslash((char*)list);
6838 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006839 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006840 return (char*)list;
6841}
6842
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006843#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006844static char* expand_strvec_to_string(char **argv)
6845{
6846 char **list;
6847
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006848 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006849 /* Convert all NULs to spaces */
6850 if (list[0]) {
6851 int n = 1;
6852 while (list[n]) {
6853 if (HUSH_DEBUG)
6854 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6855 bb_error_msg_and_die("BUG in varexp3");
6856 /* bash uses ' ' regardless of $IFS contents */
6857 list[n][-1] = ' ';
6858 n++;
6859 }
6860 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006861 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006862 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6863 return (char*)list;
6864}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006865#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006866
6867static char **expand_assignments(char **argv, int count)
6868{
6869 int i;
6870 char **p;
6871
6872 G.expanded_assignments = p = NULL;
6873 /* Expand assignments into one string each */
6874 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006875 p = add_string_to_strings(p,
6876 expand_string_to_string(argv[i],
6877 EXP_FLAG_ESC_GLOB_CHARS,
6878 /*unbackslash:*/ 1
6879 )
6880 );
6881 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006882 }
6883 G.expanded_assignments = NULL;
6884 return p;
6885}
6886
6887
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006888static void switch_off_special_sigs(unsigned mask)
6889{
6890 unsigned sig = 0;
6891 while ((mask >>= 1) != 0) {
6892 sig++;
6893 if (!(mask & 1))
6894 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006895#if ENABLE_HUSH_TRAP
6896 if (G_traps) {
6897 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006898 /* trap is '', has to remain SIG_IGN */
6899 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006900 free(G_traps[sig]);
6901 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006902 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006903#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006904 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006905 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006906 }
6907}
6908
Denys Vlasenkob347df92011-08-09 22:49:15 +02006909#if BB_MMU
6910/* never called */
6911void re_execute_shell(char ***to_free, const char *s,
6912 char *g_argv0, char **g_argv,
6913 char **builtin_argv) NORETURN;
6914
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006915static void reset_traps_to_defaults(void)
6916{
6917 /* This function is always called in a child shell
6918 * after fork (not vfork, NOMMU doesn't use this function).
6919 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006920 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006921 unsigned mask;
6922
6923 /* Child shells are not interactive.
6924 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6925 * Testcase: (while :; do :; done) + ^Z should background.
6926 * Same goes for SIGTERM, SIGHUP, SIGINT.
6927 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006928 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006929 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006930 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006931
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006932 /* Switch off special sigs */
6933 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006934# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006935 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006936# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006937 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006938 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6939 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006940
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006941# if ENABLE_HUSH_TRAP
6942 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006943 return;
6944
6945 /* Reset all sigs to default except ones with empty traps */
6946 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006947 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006948 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006949 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006950 continue; /* empty trap: has to remain SIG_IGN */
6951 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006952 free(G_traps[sig]);
6953 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006954 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006955 if (sig == 0)
6956 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006957 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006958 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006959# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006960}
6961
6962#else /* !BB_MMU */
6963
6964static void re_execute_shell(char ***to_free, const char *s,
6965 char *g_argv0, char **g_argv,
6966 char **builtin_argv) NORETURN;
6967static void re_execute_shell(char ***to_free, const char *s,
6968 char *g_argv0, char **g_argv,
6969 char **builtin_argv)
6970{
6971# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6972 /* delims + 2 * (number of bytes in printed hex numbers) */
6973 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6974 char *heredoc_argv[4];
6975 struct variable *cur;
6976# if ENABLE_HUSH_FUNCTIONS
6977 struct function *funcp;
6978# endif
6979 char **argv, **pp;
6980 unsigned cnt;
6981 unsigned long long empty_trap_mask;
6982
6983 if (!g_argv0) { /* heredoc */
6984 argv = heredoc_argv;
6985 argv[0] = (char *) G.argv0_for_re_execing;
6986 argv[1] = (char *) "-<";
6987 argv[2] = (char *) s;
6988 argv[3] = NULL;
6989 pp = &argv[3]; /* used as pointer to empty environment */
6990 goto do_exec;
6991 }
6992
6993 cnt = 0;
6994 pp = builtin_argv;
6995 if (pp) while (*pp++)
6996 cnt++;
6997
6998 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006999 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007000 int sig;
7001 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007002 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007003 empty_trap_mask |= 1LL << sig;
7004 }
7005 }
7006
7007 sprintf(param_buf, NOMMU_HACK_FMT
7008 , (unsigned) G.root_pid
7009 , (unsigned) G.root_ppid
7010 , (unsigned) G.last_bg_pid
7011 , (unsigned) G.last_exitcode
7012 , cnt
7013 , empty_trap_mask
7014 IF_HUSH_LOOPS(, G.depth_of_loop)
7015 );
7016# undef NOMMU_HACK_FMT
7017 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7018 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7019 */
7020 cnt += 6;
7021 for (cur = G.top_var; cur; cur = cur->next) {
7022 if (!cur->flg_export || cur->flg_read_only)
7023 cnt += 2;
7024 }
7025# if ENABLE_HUSH_FUNCTIONS
7026 for (funcp = G.top_func; funcp; funcp = funcp->next)
7027 cnt += 3;
7028# endif
7029 pp = g_argv;
7030 while (*pp++)
7031 cnt++;
7032 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7033 *pp++ = (char *) G.argv0_for_re_execing;
7034 *pp++ = param_buf;
7035 for (cur = G.top_var; cur; cur = cur->next) {
7036 if (strcmp(cur->varstr, hush_version_str) == 0)
7037 continue;
7038 if (cur->flg_read_only) {
7039 *pp++ = (char *) "-R";
7040 *pp++ = cur->varstr;
7041 } else if (!cur->flg_export) {
7042 *pp++ = (char *) "-V";
7043 *pp++ = cur->varstr;
7044 }
7045 }
7046# if ENABLE_HUSH_FUNCTIONS
7047 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7048 *pp++ = (char *) "-F";
7049 *pp++ = funcp->name;
7050 *pp++ = funcp->body_as_string;
7051 }
7052# endif
7053 /* We can pass activated traps here. Say, -Tnn:trap_string
7054 *
7055 * However, POSIX says that subshells reset signals with traps
7056 * to SIG_DFL.
7057 * I tested bash-3.2 and it not only does that with true subshells
7058 * of the form ( list ), but with any forked children shells.
7059 * I set trap "echo W" WINCH; and then tried:
7060 *
7061 * { echo 1; sleep 20; echo 2; } &
7062 * while true; do echo 1; sleep 20; echo 2; break; done &
7063 * true | { echo 1; sleep 20; echo 2; } | cat
7064 *
7065 * In all these cases sending SIGWINCH to the child shell
7066 * did not run the trap. If I add trap "echo V" WINCH;
7067 * _inside_ group (just before echo 1), it works.
7068 *
7069 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007070 */
7071 *pp++ = (char *) "-c";
7072 *pp++ = (char *) s;
7073 if (builtin_argv) {
7074 while (*++builtin_argv)
7075 *pp++ = *builtin_argv;
7076 *pp++ = (char *) "";
7077 }
7078 *pp++ = g_argv0;
7079 while (*g_argv)
7080 *pp++ = *g_argv++;
7081 /* *pp = NULL; - is already there */
7082 pp = environ;
7083
7084 do_exec:
7085 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007086 /* Don't propagate SIG_IGN to the child */
7087 if (SPECIAL_JOBSTOP_SIGS != 0)
7088 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007089 execve(bb_busybox_exec_path, argv, pp);
7090 /* Fallback. Useful for init=/bin/hush usage etc */
7091 if (argv[0][0] == '/')
7092 execve(argv[0], argv, pp);
7093 xfunc_error_retval = 127;
7094 bb_error_msg_and_die("can't re-execute the shell");
7095}
7096#endif /* !BB_MMU */
7097
7098
7099static int run_and_free_list(struct pipe *pi);
7100
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007101/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007102 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7103 * end_trigger controls how often we stop parsing
7104 * NUL: parse all, execute, return
7105 * ';': parse till ';' or newline, execute, repeat till EOF
7106 */
7107static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007108{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007109 /* Why we need empty flag?
7110 * An obscure corner case "false; ``; echo $?":
7111 * empty command in `` should still set $? to 0.
7112 * But we can't just set $? to 0 at the start,
7113 * this breaks "false; echo `echo $?`" case.
7114 */
7115 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007116 while (1) {
7117 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007118
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007119#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007120 if (end_trigger == ';') {
7121 G.promptmode = 0; /* PS1 */
7122 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7123 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007124#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007125 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007126 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7127 /* If we are in "big" script
7128 * (not in `cmd` or something similar)...
7129 */
7130 if (pipe_list == ERR_PTR && end_trigger == ';') {
7131 /* Discard cached input (rest of line) */
7132 int ch = inp->last_char;
7133 while (ch != EOF && ch != '\n') {
7134 //bb_error_msg("Discarded:'%c'", ch);
7135 ch = i_getch(inp);
7136 }
7137 /* Force prompt */
7138 inp->p = NULL;
7139 /* This stream isn't empty */
7140 empty = 0;
7141 continue;
7142 }
7143 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007144 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007145 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007146 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007147 debug_print_tree(pipe_list, 0);
7148 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7149 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007150 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007151 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007152 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007153 }
Eric Andersen25f27032001-04-26 23:22:31 +00007154}
7155
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007156static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007157{
7158 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007159 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7160
Eric Andersen25f27032001-04-26 23:22:31 +00007161 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007162 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007163 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007164}
7165
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007166static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007167{
Eric Andersen25f27032001-04-26 23:22:31 +00007168 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007169 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007170
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007171 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007172 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007173 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007174 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007175}
7176
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007177#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007178static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007179{
7180 pid_t pid;
7181 int channel[2];
7182# if !BB_MMU
7183 char **to_free = NULL;
7184# endif
7185
7186 xpipe(channel);
7187 pid = BB_MMU ? xfork() : xvfork();
7188 if (pid == 0) { /* child */
7189 disable_restore_tty_pgrp_on_exit();
7190 /* Process substitution is not considered to be usual
7191 * 'command execution'.
7192 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7193 */
7194 bb_signals(0
7195 + (1 << SIGTSTP)
7196 + (1 << SIGTTIN)
7197 + (1 << SIGTTOU)
7198 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007199 close(channel[0]); /* NB: close _first_, then move fd! */
7200 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007201# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007202 /* Awful hack for `trap` or $(trap).
7203 *
7204 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7205 * contains an example where "trap" is executed in a subshell:
7206 *
7207 * save_traps=$(trap)
7208 * ...
7209 * eval "$save_traps"
7210 *
7211 * Standard does not say that "trap" in subshell shall print
7212 * parent shell's traps. It only says that its output
7213 * must have suitable form, but then, in the above example
7214 * (which is not supposed to be normative), it implies that.
7215 *
7216 * bash (and probably other shell) does implement it
7217 * (traps are reset to defaults, but "trap" still shows them),
7218 * but as a result, "trap" logic is hopelessly messed up:
7219 *
7220 * # trap
7221 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7222 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7223 * # true | trap <--- trap is in subshell - no output (ditto)
7224 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7225 * trap -- 'echo Ho' SIGWINCH
7226 * # echo `(trap)` <--- in subshell in subshell - output
7227 * trap -- 'echo Ho' SIGWINCH
7228 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7229 * trap -- 'echo Ho' SIGWINCH
7230 *
7231 * The rules when to forget and when to not forget traps
7232 * get really complex and nonsensical.
7233 *
7234 * Our solution: ONLY bare $(trap) or `trap` is special.
7235 */
7236 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007237 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007238 && skip_whitespace(s + 4)[0] == '\0'
7239 ) {
7240 static const char *const argv[] = { NULL, NULL };
7241 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007242 fflush_all(); /* important */
7243 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007244 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007245# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007246# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007247 /* Prevent it from trying to handle ctrl-z etc */
7248 IF_HUSH_JOB(G.run_list_level = 1;)
7249 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007250 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007251 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007252 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007253 parse_and_run_string(s);
7254 _exit(G.last_exitcode);
7255# else
7256 /* We re-execute after vfork on NOMMU. This makes this script safe:
7257 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7258 * huge=`cat BIG` # was blocking here forever
7259 * echo OK
7260 */
7261 re_execute_shell(&to_free,
7262 s,
7263 G.global_argv[0],
7264 G.global_argv + 1,
7265 NULL);
7266# endif
7267 }
7268
7269 /* parent */
7270 *pid_p = pid;
7271# if ENABLE_HUSH_FAST
7272 G.count_SIGCHLD++;
7273//bb_error_msg("[%d] fork in generate_stream_from_string:"
7274// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7275// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7276# endif
7277 enable_restore_tty_pgrp_on_exit();
7278# if !BB_MMU
7279 free(to_free);
7280# endif
7281 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007282 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007283}
7284
7285/* Return code is exit status of the process that is run. */
7286static int process_command_subs(o_string *dest, const char *s)
7287{
7288 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007289 pid_t pid;
7290 int status, ch, eol_cnt;
7291
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007292 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007293
7294 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007295 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007296 while ((ch = getc(fp)) != EOF) {
7297 if (ch == '\0')
7298 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007299 if (ch == '\n') {
7300 eol_cnt++;
7301 continue;
7302 }
7303 while (eol_cnt) {
7304 o_addchr(dest, '\n');
7305 eol_cnt--;
7306 }
7307 o_addQchr(dest, ch);
7308 }
7309
7310 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007311 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007312 /* We need to extract exitcode. Test case
7313 * "true; echo `sleep 1; false` $?"
7314 * should print 1 */
7315 safe_waitpid(pid, &status, 0);
7316 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7317 return WEXITSTATUS(status);
7318}
7319#endif /* ENABLE_HUSH_TICK */
7320
7321
7322static void setup_heredoc(struct redir_struct *redir)
7323{
7324 struct fd_pair pair;
7325 pid_t pid;
7326 int len, written;
7327 /* the _body_ of heredoc (misleading field name) */
7328 const char *heredoc = redir->rd_filename;
7329 char *expanded;
7330#if !BB_MMU
7331 char **to_free;
7332#endif
7333
7334 expanded = NULL;
7335 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007336 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007337 if (expanded)
7338 heredoc = expanded;
7339 }
7340 len = strlen(heredoc);
7341
7342 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7343 xpiped_pair(pair);
7344 xmove_fd(pair.rd, redir->rd_fd);
7345
7346 /* Try writing without forking. Newer kernels have
7347 * dynamically growing pipes. Must use non-blocking write! */
7348 ndelay_on(pair.wr);
7349 while (1) {
7350 written = write(pair.wr, heredoc, len);
7351 if (written <= 0)
7352 break;
7353 len -= written;
7354 if (len == 0) {
7355 close(pair.wr);
7356 free(expanded);
7357 return;
7358 }
7359 heredoc += written;
7360 }
7361 ndelay_off(pair.wr);
7362
7363 /* Okay, pipe buffer was not big enough */
7364 /* Note: we must not create a stray child (bastard? :)
7365 * for the unsuspecting parent process. Child creates a grandchild
7366 * and exits before parent execs the process which consumes heredoc
7367 * (that exec happens after we return from this function) */
7368#if !BB_MMU
7369 to_free = NULL;
7370#endif
7371 pid = xvfork();
7372 if (pid == 0) {
7373 /* child */
7374 disable_restore_tty_pgrp_on_exit();
7375 pid = BB_MMU ? xfork() : xvfork();
7376 if (pid != 0)
7377 _exit(0);
7378 /* grandchild */
7379 close(redir->rd_fd); /* read side of the pipe */
7380#if BB_MMU
7381 full_write(pair.wr, heredoc, len); /* may loop or block */
7382 _exit(0);
7383#else
7384 /* Delegate blocking writes to another process */
7385 xmove_fd(pair.wr, STDOUT_FILENO);
7386 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7387#endif
7388 }
7389 /* parent */
7390#if ENABLE_HUSH_FAST
7391 G.count_SIGCHLD++;
7392//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7393#endif
7394 enable_restore_tty_pgrp_on_exit();
7395#if !BB_MMU
7396 free(to_free);
7397#endif
7398 close(pair.wr);
7399 free(expanded);
7400 wait(NULL); /* wait till child has died */
7401}
7402
Denys Vlasenko2db74612017-07-07 22:07:28 +02007403struct squirrel {
7404 int orig_fd;
7405 int moved_to;
7406 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7407 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7408};
7409
Denys Vlasenko621fc502017-07-24 12:42:17 +02007410static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7411{
7412 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7413 sq[i].orig_fd = orig;
7414 sq[i].moved_to = moved;
7415 sq[i+1].orig_fd = -1; /* end marker */
7416 return sq;
7417}
7418
Denys Vlasenko2db74612017-07-07 22:07:28 +02007419static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7420{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007421 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007422 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007423
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007424 i = 0;
7425 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007426 /* If we collide with an already moved fd... */
7427 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007428 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007429 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7430 if (sq[i].moved_to < 0) /* what? */
7431 xfunc_die();
7432 return sq;
7433 }
7434 if (fd == sq[i].orig_fd) {
7435 /* Example: echo Hello >/dev/null 1>&2 */
7436 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7437 return sq;
7438 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007439 }
7440
Denys Vlasenko2db74612017-07-07 22:07:28 +02007441 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007442 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007443 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7444 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007445 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007446 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007447}
7448
Denys Vlasenko657e9002017-07-30 23:34:04 +02007449static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7450{
7451 int i;
7452
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007453 i = 0;
7454 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007455 /* If we collide with an already moved fd... */
7456 if (fd == sq[i].orig_fd) {
7457 /* Examples:
7458 * "echo 3>FILE 3>&- 3>FILE"
7459 * "echo 3>&- 3>FILE"
7460 * No need for last redirect to insert
7461 * another "need to close 3" indicator.
7462 */
7463 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7464 return sq;
7465 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007466 }
7467
7468 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7469 return append_squirrel(sq, i, fd, -1);
7470}
7471
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007472/* fd: redirect wants this fd to be used (e.g. 3>file).
7473 * Move all conflicting internally used fds,
7474 * and remember them so that we can restore them later.
7475 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007476static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007477{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007478 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7479 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007480
7481#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007482 if (fd == G.interactive_fd) {
7483 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007484 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007485 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7486 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007487 }
7488#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007489 /* Are we called from setup_redirects(squirrel==NULL)
7490 * in redirect in a [v]forked child?
7491 */
7492 if (sqp == NULL) {
7493 /* No need to move script fds.
7494 * For NOMMU case, it's actively wrong: we'd change ->fd
7495 * fields in memory for the parent, but parent's fds
7496 * aren't be moved, it would use wrong fd!
7497 * Reproducer: "cmd 3>FILE" in script.
7498 * If we would call move_HFILEs_on_redirect(), child would:
7499 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7500 * close(3) = 0
7501 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7502 */
7503 //bb_error_msg("sqp == NULL: [v]forked child");
7504 return 0;
7505 }
7506
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007507 /* If this one of script's fds? */
7508 if (move_HFILEs_on_redirect(fd, avoid_fd))
7509 return 1; /* yes. "we closed fd" (actually moved it) */
7510
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007511 /* Are we called for "exec 3>FILE"? Came through
7512 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7513 * This case used to fail for this script:
7514 * exec 3>FILE
7515 * echo Ok
7516 * ...100000 more lines...
7517 * echo Ok
7518 * as follows:
7519 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7520 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7521 * dup2(4, 3) = 3
7522 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7523 * close(4) = 0
7524 * write(1, "Ok\n", 3) = 3
7525 * ... = 3
7526 * write(1, "Ok\n", 3) = 3
7527 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7528 * ^^^^^^^^ oops, wrong fd!!!
7529 * With this case separate from sqp == NULL and *after* move_HFILEs,
7530 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007531 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007532 if (sqp == ERR_PTR) {
7533 /* Don't preserve redirected fds: exec is _meant_ to change these */
7534 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007535 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007536 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007537
Denys Vlasenko2db74612017-07-07 22:07:28 +02007538 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7539 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7540 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007541}
7542
Denys Vlasenko2db74612017-07-07 22:07:28 +02007543static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007544{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007545 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007546 int i;
7547 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007548 if (sq[i].moved_to >= 0) {
7549 /* We simply die on error */
7550 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7551 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7552 } else {
7553 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7554 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7555 close(sq[i].orig_fd);
7556 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007557 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007558 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007559 }
7560
Denys Vlasenko2db74612017-07-07 22:07:28 +02007561 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007562}
7563
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007564#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007565static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007566{
7567 if (G_interactive_fd)
7568 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007569 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007570}
7571#endif
7572
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007573static int internally_opened_fd(int fd, struct squirrel *sq)
7574{
7575 int i;
7576
7577#if ENABLE_HUSH_INTERACTIVE
7578 if (fd == G.interactive_fd)
7579 return 1;
7580#endif
7581 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007582 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007583 return 1;
7584
7585 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7586 if (fd == sq[i].moved_to)
7587 return 1;
7588 }
7589 return 0;
7590}
7591
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007592/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7593 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007594static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007595{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007596 struct redir_struct *redir;
7597
7598 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007599 int newfd;
7600 int closed;
7601
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007602 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007603 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007604 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007605 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7606 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007607 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007608 redir->rd_filename);
7609 setup_heredoc(redir);
7610 continue;
7611 }
7612
7613 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007614 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007615 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007616 int mode;
7617
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007618 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007619 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007620 * "cmd >" (no filename)
7621 * "cmd > <file" (2nd redirect starts too early)
7622 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007623 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007624 continue;
7625 }
7626 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007627 p = expand_string_to_string(redir->rd_filename,
7628 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007629 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007630 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007631 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007632 /* Error message from open_or_warn can be lost
7633 * if stderr has been redirected, but bash
7634 * and ash both lose it as well
7635 * (though zsh doesn't!)
7636 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007637 return 1;
7638 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007639 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007640 /* open() gave us precisely the fd we wanted.
7641 * This means that this fd was not busy
7642 * (not opened to anywhere).
7643 * Remember to close it on restore:
7644 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007645 *sqp = add_squirrel_closed(*sqp, newfd);
7646 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007647 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007648 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007649 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7650 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007651 }
7652
Denys Vlasenko657e9002017-07-30 23:34:04 +02007653 if (newfd == redir->rd_fd)
7654 continue;
7655
7656 /* if "N>FILE": move newfd to redir->rd_fd */
7657 /* if "N>&M": dup newfd to redir->rd_fd */
7658 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7659
7660 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7661 if (newfd == REDIRFD_CLOSE) {
7662 /* "N>&-" means "close me" */
7663 if (!closed) {
7664 /* ^^^ optimization: saving may already
7665 * have closed it. If not... */
7666 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007667 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007668 /* Sometimes we do another close on restore, getting EBADF.
7669 * Consider "echo 3>FILE 3>&-"
7670 * first redirect remembers "need to close 3",
7671 * and second redirect closes 3! Restore code then closes 3 again.
7672 */
7673 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007674 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007675 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007676 //errno = EBADF;
7677 //bb_perror_msg_and_die("can't duplicate file descriptor");
7678 newfd = -1; /* same effect as code above */
7679 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007680 xdup2(newfd, redir->rd_fd);
7681 if (redir->rd_dup == REDIRFD_TO_FILE)
7682 /* "rd_fd > FILE" */
7683 close(newfd);
7684 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007685 }
7686 }
7687 return 0;
7688}
7689
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007690static char *find_in_path(const char *arg)
7691{
7692 char *ret = NULL;
7693 const char *PATH = get_local_var_value("PATH");
7694
7695 if (!PATH)
7696 return NULL;
7697
7698 while (1) {
7699 const char *end = strchrnul(PATH, ':');
7700 int sz = end - PATH; /* must be int! */
7701
7702 free(ret);
7703 if (sz != 0) {
7704 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7705 } else {
7706 /* We have xxx::yyyy in $PATH,
7707 * it means "use current dir" */
7708 ret = xstrdup(arg);
7709 }
7710 if (access(ret, F_OK) == 0)
7711 break;
7712
7713 if (*end == '\0') {
7714 free(ret);
7715 return NULL;
7716 }
7717 PATH = end + 1;
7718 }
7719
7720 return ret;
7721}
7722
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007723static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007724 const struct built_in_command *x,
7725 const struct built_in_command *end)
7726{
7727 while (x != end) {
7728 if (strcmp(name, x->b_cmd) != 0) {
7729 x++;
7730 continue;
7731 }
7732 debug_printf_exec("found builtin '%s'\n", name);
7733 return x;
7734 }
7735 return NULL;
7736}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007737static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007738{
7739 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7740}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007741static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007742{
7743 const struct built_in_command *x = find_builtin1(name);
7744 if (x)
7745 return x;
7746 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7747}
7748
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007749static void remove_nested_vars(void)
7750{
7751 struct variable *cur;
7752 struct variable **cur_pp;
7753
7754 cur_pp = &G.top_var;
7755 while ((cur = *cur_pp) != NULL) {
7756 if (cur->var_nest_level <= G.var_nest_level) {
7757 cur_pp = &cur->next;
7758 continue;
7759 }
7760 /* Unexport */
7761 if (cur->flg_export) {
7762 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7763 bb_unsetenv(cur->varstr);
7764 }
7765 /* Remove from global list */
7766 *cur_pp = cur->next;
7767 /* Free */
7768 if (!cur->max_len) {
7769 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7770 free(cur->varstr);
7771 }
7772 free(cur);
7773 }
7774}
7775
7776static void enter_var_nest_level(void)
7777{
7778 G.var_nest_level++;
7779 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7780
7781 /* Try: f() { echo -n .; f; }; f
7782 * struct variable::var_nest_level is uint16_t,
7783 * thus limiting recursion to < 2^16.
7784 * In any case, with 8 Mbyte stack SEGV happens
7785 * not too long after 2^16 recursions anyway.
7786 */
7787 if (G.var_nest_level > 0xff00)
7788 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7789}
7790
7791static void leave_var_nest_level(void)
7792{
7793 G.var_nest_level--;
7794 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7795 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7796 bb_error_msg_and_die("BUG: nesting underflow");
7797
7798 remove_nested_vars();
7799}
7800
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007801#if ENABLE_HUSH_FUNCTIONS
7802static struct function **find_function_slot(const char *name)
7803{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007804 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007805 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007806
7807 while ((funcp = *funcpp) != NULL) {
7808 if (strcmp(name, funcp->name) == 0) {
7809 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007810 break;
7811 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007812 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007813 }
7814 return funcpp;
7815}
7816
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007817static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007818{
7819 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007820 return funcp;
7821}
7822
7823/* Note: takes ownership on name ptr */
7824static struct function *new_function(char *name)
7825{
7826 struct function **funcpp = find_function_slot(name);
7827 struct function *funcp = *funcpp;
7828
7829 if (funcp != NULL) {
7830 struct command *cmd = funcp->parent_cmd;
7831 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7832 if (!cmd) {
7833 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7834 free(funcp->name);
7835 /* Note: if !funcp->body, do not free body_as_string!
7836 * This is a special case of "-F name body" function:
7837 * body_as_string was not malloced! */
7838 if (funcp->body) {
7839 free_pipe_list(funcp->body);
7840# if !BB_MMU
7841 free(funcp->body_as_string);
7842# endif
7843 }
7844 } else {
7845 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7846 cmd->argv[0] = funcp->name;
7847 cmd->group = funcp->body;
7848# if !BB_MMU
7849 cmd->group_as_string = funcp->body_as_string;
7850# endif
7851 }
7852 } else {
7853 debug_printf_exec("remembering new function '%s'\n", name);
7854 funcp = *funcpp = xzalloc(sizeof(*funcp));
7855 /*funcp->next = NULL;*/
7856 }
7857
7858 funcp->name = name;
7859 return funcp;
7860}
7861
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007862# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007863static void unset_func(const char *name)
7864{
7865 struct function **funcpp = find_function_slot(name);
7866 struct function *funcp = *funcpp;
7867
7868 if (funcp != NULL) {
7869 debug_printf_exec("freeing function '%s'\n", funcp->name);
7870 *funcpp = funcp->next;
7871 /* funcp is unlinked now, deleting it.
7872 * Note: if !funcp->body, the function was created by
7873 * "-F name body", do not free ->body_as_string
7874 * and ->name as they were not malloced. */
7875 if (funcp->body) {
7876 free_pipe_list(funcp->body);
7877 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007878# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007879 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007880# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007881 }
7882 free(funcp);
7883 }
7884}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007885# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007886
7887# if BB_MMU
7888#define exec_function(to_free, funcp, argv) \
7889 exec_function(funcp, argv)
7890# endif
7891static void exec_function(char ***to_free,
7892 const struct function *funcp,
7893 char **argv) NORETURN;
7894static void exec_function(char ***to_free,
7895 const struct function *funcp,
7896 char **argv)
7897{
7898# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007899 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007900
7901 argv[0] = G.global_argv[0];
7902 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007903 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007904
7905// Example when we are here: "cmd | func"
7906// func will run with saved-redirect fds open.
7907// $ f() { echo /proc/self/fd/*; }
7908// $ true | f
7909// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7910// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7911// Same in script:
7912// $ . ./SCRIPT
7913// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7914// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7915// They are CLOEXEC so external programs won't see them, but
7916// for "more correctness" we might want to close those extra fds here:
7917//? close_saved_fds_and_FILE_fds();
7918
Denys Vlasenko332e4112018-04-04 22:32:59 +02007919 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007920 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007921 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007922 IF_HUSH_LOCAL(G.func_nest_level++;)
7923
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007924 /* On MMU, funcp->body is always non-NULL */
7925 n = run_list(funcp->body);
7926 fflush_all();
7927 _exit(n);
7928# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007929//? close_saved_fds_and_FILE_fds();
7930
7931//TODO: check whether "true | func_with_return" works
7932
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007933 re_execute_shell(to_free,
7934 funcp->body_as_string,
7935 G.global_argv[0],
7936 argv + 1,
7937 NULL);
7938# endif
7939}
7940
7941static int run_function(const struct function *funcp, char **argv)
7942{
7943 int rc;
7944 save_arg_t sv;
7945 smallint sv_flg;
7946
7947 save_and_replace_G_args(&sv, argv);
7948
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007949 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007950 sv_flg = G_flag_return_in_progress;
7951 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007952
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007953 /* Make "local" variables properly shadow previous ones */
7954 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007955 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007956
7957 /* On MMU, funcp->body is always non-NULL */
7958# if !BB_MMU
7959 if (!funcp->body) {
7960 /* Function defined by -F */
7961 parse_and_run_string(funcp->body_as_string);
7962 rc = G.last_exitcode;
7963 } else
7964# endif
7965 {
7966 rc = run_list(funcp->body);
7967 }
7968
Denys Vlasenko332e4112018-04-04 22:32:59 +02007969 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007970 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007971
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007972 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007973
7974 restore_G_args(&sv, argv);
7975
7976 return rc;
7977}
7978#endif /* ENABLE_HUSH_FUNCTIONS */
7979
7980
7981#if BB_MMU
7982#define exec_builtin(to_free, x, argv) \
7983 exec_builtin(x, argv)
7984#else
7985#define exec_builtin(to_free, x, argv) \
7986 exec_builtin(to_free, argv)
7987#endif
7988static void exec_builtin(char ***to_free,
7989 const struct built_in_command *x,
7990 char **argv) NORETURN;
7991static void exec_builtin(char ***to_free,
7992 const struct built_in_command *x,
7993 char **argv)
7994{
7995#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007996 int rcode;
7997 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007998//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007999 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008000 fflush_all();
8001 _exit(rcode);
8002#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008003 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008004 /* On NOMMU, we must never block!
8005 * Example: { sleep 99 | read line; } & echo Ok
8006 */
8007 re_execute_shell(to_free,
8008 argv[0],
8009 G.global_argv[0],
8010 G.global_argv + 1,
8011 argv);
8012#endif
8013}
8014
8015
8016static void execvp_or_die(char **argv) NORETURN;
8017static void execvp_or_die(char **argv)
8018{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008019 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008020 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008021 /* Don't propagate SIG_IGN to the child */
8022 if (SPECIAL_JOBSTOP_SIGS != 0)
8023 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008024 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008025 e = 2;
8026 if (errno == EACCES) e = 126;
8027 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008028 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008029 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008030}
8031
8032#if ENABLE_HUSH_MODE_X
8033static void dump_cmd_in_x_mode(char **argv)
8034{
8035 if (G_x_mode && argv) {
8036 /* We want to output the line in one write op */
8037 char *buf, *p;
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008038 unsigned len;
8039 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008040
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008041 len = G.x_mode_depth + 3; /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008042 n = 0;
8043 while (argv[n])
8044 len += strlen(argv[n++]) + 1;
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02008045 p = buf = xmalloc(len);
8046 n = G.x_mode_depth;
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008047 do *p++ = '+'; while ((int)(--n) >= 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008048 n = 0;
8049 while (argv[n])
8050 p += sprintf(p, " %s", argv[n++]);
8051 *p++ = '\n';
8052 *p = '\0';
8053 fputs(buf, stderr);
8054 free(buf);
8055 }
8056}
8057#else
8058# define dump_cmd_in_x_mode(argv) ((void)0)
8059#endif
8060
Denys Vlasenko57000292018-01-12 14:41:45 +01008061#if ENABLE_HUSH_COMMAND
8062static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8063{
8064 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008065
Denys Vlasenko57000292018-01-12 14:41:45 +01008066 if (!opt_vV)
8067 return;
8068
8069 to_free = NULL;
8070 if (!explanation) {
8071 char *path = getenv("PATH");
8072 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008073 if (!explanation)
8074 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008075 if (opt_vV != 'V')
8076 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8077 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008078 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008079 free(to_free);
8080 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008081 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008082}
8083#else
8084# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8085#endif
8086
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008087#if BB_MMU
8088#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8089 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8090#define pseudo_exec(nommu_save, command, argv_expanded) \
8091 pseudo_exec(command, argv_expanded)
8092#endif
8093
8094/* Called after [v]fork() in run_pipe, or from builtin_exec.
8095 * Never returns.
8096 * Don't exit() here. If you don't exec, use _exit instead.
8097 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008098 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008099 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008100static void pseudo_exec_argv(nommu_save_t *nommu_save,
8101 char **argv, int assignment_cnt,
8102 char **argv_expanded) NORETURN;
8103static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8104 char **argv, int assignment_cnt,
8105 char **argv_expanded)
8106{
Denys Vlasenko57000292018-01-12 14:41:45 +01008107 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008108 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008109 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008110 IF_HUSH_COMMAND(char opt_vV = 0;)
8111 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008112
8113 new_env = expand_assignments(argv, assignment_cnt);
8114 dump_cmd_in_x_mode(new_env);
8115
8116 if (!argv[assignment_cnt]) {
8117 /* Case when we are here: ... | var=val | ...
8118 * (note that we do not exit early, i.e., do not optimize out
8119 * expand_assignments(): think about ... | var=`sleep 1` | ...
8120 */
8121 free_strings(new_env);
8122 _exit(EXIT_SUCCESS);
8123 }
8124
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008125 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008126#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008127 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008128#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008129 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008130 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008131#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008132 set_vars_and_save_old(new_env);
8133 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008134
8135 if (argv_expanded) {
8136 argv = argv_expanded;
8137 } else {
8138 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8139#if !BB_MMU
8140 nommu_save->argv = argv;
8141#endif
8142 }
8143 dump_cmd_in_x_mode(argv);
8144
8145#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8146 if (strchr(argv[0], '/') != NULL)
8147 goto skip;
8148#endif
8149
Denys Vlasenko75481d32017-07-31 05:27:09 +02008150#if ENABLE_HUSH_FUNCTIONS
8151 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008152 funcp = find_function(argv[0]);
8153 if (funcp)
8154 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008155#endif
8156
Denys Vlasenko57000292018-01-12 14:41:45 +01008157#if ENABLE_HUSH_COMMAND
8158 /* "command BAR": run BAR without looking it up among functions
8159 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8160 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8161 */
8162 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8163 char *p;
8164
8165 argv++;
8166 p = *argv;
8167 if (p[0] != '-' || !p[1])
8168 continue; /* bash allows "command command command [-OPT] BAR" */
8169
8170 for (;;) {
8171 p++;
8172 switch (*p) {
8173 case '\0':
8174 argv++;
8175 p = *argv;
8176 if (p[0] != '-' || !p[1])
8177 goto after_opts;
8178 continue; /* next arg is also -opts, process it too */
8179 case 'v':
8180 case 'V':
8181 opt_vV = *p;
8182 continue;
8183 default:
8184 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8185 }
8186 }
8187 }
8188 after_opts:
8189# if ENABLE_HUSH_FUNCTIONS
8190 if (opt_vV && find_function(argv[0]))
8191 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8192# endif
8193#endif
8194
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008195 /* Check if the command matches any of the builtins.
8196 * Depending on context, this might be redundant. But it's
8197 * easier to waste a few CPU cycles than it is to figure out
8198 * if this is one of those cases.
8199 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008200 /* Why "BB_MMU ? :" difference in logic? -
8201 * On NOMMU, it is more expensive to re-execute shell
8202 * just in order to run echo or test builtin.
8203 * It's better to skip it here and run corresponding
8204 * non-builtin later. */
8205 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8206 if (x) {
8207 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8208 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008209 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008210
8211#if ENABLE_FEATURE_SH_STANDALONE
8212 /* Check if the command matches any busybox applets */
8213 {
8214 int a = find_applet_by_name(argv[0]);
8215 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008216 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008217# if BB_MMU /* see above why on NOMMU it is not allowed */
8218 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008219 /* Do not leak open fds from opened script files etc.
8220 * Testcase: interactive "ls -l /proc/self/fd"
8221 * should not show tty fd open.
8222 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008223 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008224//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008225//This casuses test failures in
8226//redir_children_should_not_see_saved_fd_2.tests
8227//redir_children_should_not_see_saved_fd_3.tests
8228//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008229 /* Without this, "rm -i FILE" can't be ^C'ed: */
8230 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008231 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008232 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008233 }
8234# endif
8235 /* Re-exec ourselves */
8236 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008237 /* Don't propagate SIG_IGN to the child */
8238 if (SPECIAL_JOBSTOP_SIGS != 0)
8239 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008240 execv(bb_busybox_exec_path, argv);
8241 /* If they called chroot or otherwise made the binary no longer
8242 * executable, fall through */
8243 }
8244 }
8245#endif
8246
8247#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8248 skip:
8249#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008250 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008251 execvp_or_die(argv);
8252}
8253
8254/* Called after [v]fork() in run_pipe
8255 */
8256static void pseudo_exec(nommu_save_t *nommu_save,
8257 struct command *command,
8258 char **argv_expanded) NORETURN;
8259static void pseudo_exec(nommu_save_t *nommu_save,
8260 struct command *command,
8261 char **argv_expanded)
8262{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008263#if ENABLE_HUSH_FUNCTIONS
8264 if (command->cmd_type == CMD_FUNCDEF) {
8265 /* Ignore funcdefs in pipes:
8266 * true | f() { cmd }
8267 */
8268 _exit(0);
8269 }
8270#endif
8271
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008272 if (command->argv) {
8273 pseudo_exec_argv(nommu_save, command->argv,
8274 command->assignment_cnt, argv_expanded);
8275 }
8276
8277 if (command->group) {
8278 /* Cases when we are here:
8279 * ( list )
8280 * { list } &
8281 * ... | ( list ) | ...
8282 * ... | { list } | ...
8283 */
8284#if BB_MMU
8285 int rcode;
8286 debug_printf_exec("pseudo_exec: run_list\n");
8287 reset_traps_to_defaults();
8288 rcode = run_list(command->group);
8289 /* OK to leak memory by not calling free_pipe_list,
8290 * since this process is about to exit */
8291 _exit(rcode);
8292#else
8293 re_execute_shell(&nommu_save->argv_from_re_execing,
8294 command->group_as_string,
8295 G.global_argv[0],
8296 G.global_argv + 1,
8297 NULL);
8298#endif
8299 }
8300
8301 /* Case when we are here: ... | >file */
8302 debug_printf_exec("pseudo_exec'ed null command\n");
8303 _exit(EXIT_SUCCESS);
8304}
8305
8306#if ENABLE_HUSH_JOB
8307static const char *get_cmdtext(struct pipe *pi)
8308{
8309 char **argv;
8310 char *p;
8311 int len;
8312
8313 /* This is subtle. ->cmdtext is created only on first backgrounding.
8314 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8315 * On subsequent bg argv is trashed, but we won't use it */
8316 if (pi->cmdtext)
8317 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008318
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008319 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008320 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008321 pi->cmdtext = xzalloc(1);
8322 return pi->cmdtext;
8323 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008324 len = 0;
8325 do {
8326 len += strlen(*argv) + 1;
8327 } while (*++argv);
8328 p = xmalloc(len);
8329 pi->cmdtext = p;
8330 argv = pi->cmds[0].argv;
8331 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008332 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008333 *p++ = ' ';
8334 } while (*++argv);
8335 p[-1] = '\0';
8336 return pi->cmdtext;
8337}
8338
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008339static void remove_job_from_table(struct pipe *pi)
8340{
8341 struct pipe *prev_pipe;
8342
8343 if (pi == G.job_list) {
8344 G.job_list = pi->next;
8345 } else {
8346 prev_pipe = G.job_list;
8347 while (prev_pipe->next != pi)
8348 prev_pipe = prev_pipe->next;
8349 prev_pipe->next = pi->next;
8350 }
8351 G.last_jobid = 0;
8352 if (G.job_list)
8353 G.last_jobid = G.job_list->jobid;
8354}
8355
8356static void delete_finished_job(struct pipe *pi)
8357{
8358 remove_job_from_table(pi);
8359 free_pipe(pi);
8360}
8361
8362static void clean_up_last_dead_job(void)
8363{
8364 if (G.job_list && !G.job_list->alive_cmds)
8365 delete_finished_job(G.job_list);
8366}
8367
Denys Vlasenko16096292017-07-10 10:00:28 +02008368static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008369{
8370 struct pipe *job, **jobp;
8371 int i;
8372
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008373 clean_up_last_dead_job();
8374
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008375 /* Find the end of the list, and find next job ID to use */
8376 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008377 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008378 while ((job = *jobp) != NULL) {
8379 if (job->jobid > i)
8380 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008381 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008382 }
8383 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008384
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008385 /* Create a new job struct at the end */
8386 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008387 job->next = NULL;
8388 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8389 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8390 for (i = 0; i < pi->num_cmds; i++) {
8391 job->cmds[i].pid = pi->cmds[i].pid;
8392 /* all other fields are not used and stay zero */
8393 }
8394 job->cmdtext = xstrdup(get_cmdtext(pi));
8395
8396 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008397 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008398 G.last_jobid = job->jobid;
8399}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008400#endif /* JOB */
8401
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008402static int job_exited_or_stopped(struct pipe *pi)
8403{
8404 int rcode, i;
8405
8406 if (pi->alive_cmds != pi->stopped_cmds)
8407 return -1;
8408
8409 /* All processes in fg pipe have exited or stopped */
8410 rcode = 0;
8411 i = pi->num_cmds;
8412 while (--i >= 0) {
8413 rcode = pi->cmds[i].cmd_exitcode;
8414 /* usually last process gives overall exitstatus,
8415 * but with "set -o pipefail", last *failed* process does */
8416 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8417 break;
8418 }
8419 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8420 return rcode;
8421}
8422
Denys Vlasenko7e675362016-10-28 21:57:31 +02008423static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008424{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008425#if ENABLE_HUSH_JOB
8426 struct pipe *pi;
8427#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008428 int i, dead;
8429
8430 dead = WIFEXITED(status) || WIFSIGNALED(status);
8431
8432#if DEBUG_JOBS
8433 if (WIFSTOPPED(status))
8434 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8435 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8436 if (WIFSIGNALED(status))
8437 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8438 childpid, WTERMSIG(status), WEXITSTATUS(status));
8439 if (WIFEXITED(status))
8440 debug_printf_jobs("pid %d exited, exitcode %d\n",
8441 childpid, WEXITSTATUS(status));
8442#endif
8443 /* Were we asked to wait for a fg pipe? */
8444 if (fg_pipe) {
8445 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008446
Denys Vlasenko7e675362016-10-28 21:57:31 +02008447 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008448 int rcode;
8449
Denys Vlasenko7e675362016-10-28 21:57:31 +02008450 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8451 if (fg_pipe->cmds[i].pid != childpid)
8452 continue;
8453 if (dead) {
8454 int ex;
8455 fg_pipe->cmds[i].pid = 0;
8456 fg_pipe->alive_cmds--;
8457 ex = WEXITSTATUS(status);
8458 /* bash prints killer signal's name for *last*
8459 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8460 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8461 */
8462 if (WIFSIGNALED(status)) {
8463 int sig = WTERMSIG(status);
8464 if (i == fg_pipe->num_cmds-1)
8465 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8466 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8467 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8468 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8469 * Maybe we need to use sig | 128? */
8470 ex = sig + 128;
8471 }
8472 fg_pipe->cmds[i].cmd_exitcode = ex;
8473 } else {
8474 fg_pipe->stopped_cmds++;
8475 }
8476 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8477 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008478 rcode = job_exited_or_stopped(fg_pipe);
8479 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008480/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8481 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8482 * and "killall -STOP cat" */
8483 if (G_interactive_fd) {
8484#if ENABLE_HUSH_JOB
8485 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008486 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008487#endif
8488 return rcode;
8489 }
8490 if (fg_pipe->alive_cmds == 0)
8491 return rcode;
8492 }
8493 /* There are still running processes in the fg_pipe */
8494 return -1;
8495 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008496 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008497 }
8498
8499#if ENABLE_HUSH_JOB
8500 /* We were asked to wait for bg or orphaned children */
8501 /* No need to remember exitcode in this case */
8502 for (pi = G.job_list; pi; pi = pi->next) {
8503 for (i = 0; i < pi->num_cmds; i++) {
8504 if (pi->cmds[i].pid == childpid)
8505 goto found_pi_and_prognum;
8506 }
8507 }
8508 /* Happens when shell is used as init process (init=/bin/sh) */
8509 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8510 return -1; /* this wasn't a process from fg_pipe */
8511
8512 found_pi_and_prognum:
8513 if (dead) {
8514 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008515 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008516 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008517 rcode = 128 + WTERMSIG(status);
8518 pi->cmds[i].cmd_exitcode = rcode;
8519 if (G.last_bg_pid == pi->cmds[i].pid)
8520 G.last_bg_pid_exitcode = rcode;
8521 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008522 pi->alive_cmds--;
8523 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008524 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008525 printf(JOB_STATUS_FORMAT, pi->jobid,
8526 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008527 delete_finished_job(pi);
8528 } else {
8529/*
8530 * bash deletes finished jobs from job table only in interactive mode,
8531 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8532 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8533 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8534 * We only retain one "dead" job, if it's the single job on the list.
8535 * This covers most of real-world scenarios where this is useful.
8536 */
8537 if (pi != G.job_list)
8538 delete_finished_job(pi);
8539 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008540 }
8541 } else {
8542 /* child stopped */
8543 pi->stopped_cmds++;
8544 }
8545#endif
8546 return -1; /* this wasn't a process from fg_pipe */
8547}
8548
8549/* Check to see if any processes have exited -- if they have,
8550 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008551 *
8552 * If non-NULL fg_pipe: wait for its completion or stop.
8553 * Return its exitcode or zero if stopped.
8554 *
8555 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8556 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8557 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8558 * or 0 if no children changed status.
8559 *
8560 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8561 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8562 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008563 */
8564static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8565{
8566 int attributes;
8567 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008568 int rcode = 0;
8569
8570 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8571
8572 attributes = WUNTRACED;
8573 if (fg_pipe == NULL)
8574 attributes |= WNOHANG;
8575
8576 errno = 0;
8577#if ENABLE_HUSH_FAST
8578 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8579//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8580//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8581 /* There was neither fork nor SIGCHLD since last waitpid */
8582 /* Avoid doing waitpid syscall if possible */
8583 if (!G.we_have_children) {
8584 errno = ECHILD;
8585 return -1;
8586 }
8587 if (fg_pipe == NULL) { /* is WNOHANG set? */
8588 /* We have children, but they did not exit
8589 * or stop yet (we saw no SIGCHLD) */
8590 return 0;
8591 }
8592 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8593 }
8594#endif
8595
8596/* Do we do this right?
8597 * bash-3.00# sleep 20 | false
8598 * <ctrl-Z pressed>
8599 * [3]+ Stopped sleep 20 | false
8600 * bash-3.00# echo $?
8601 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8602 * [hush 1.14.0: yes we do it right]
8603 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008604 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008605 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008606#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008607 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008608 i = G.count_SIGCHLD;
8609#endif
8610 childpid = waitpid(-1, &status, attributes);
8611 if (childpid <= 0) {
8612 if (childpid && errno != ECHILD)
8613 bb_perror_msg("waitpid");
8614#if ENABLE_HUSH_FAST
8615 else { /* Until next SIGCHLD, waitpid's are useless */
8616 G.we_have_children = (childpid == 0);
8617 G.handled_SIGCHLD = i;
8618//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8619 }
8620#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008621 /* ECHILD (no children), or 0 (no change in children status) */
8622 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008623 break;
8624 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008625 rcode = process_wait_result(fg_pipe, childpid, status);
8626 if (rcode >= 0) {
8627 /* fg_pipe exited or stopped */
8628 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008629 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008630 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008631 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008632 rcode = WEXITSTATUS(status);
8633 if (WIFSIGNALED(status))
8634 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008635 if (WIFSTOPPED(status))
8636 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8637 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008638 rcode++;
8639 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008640 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008641 /* This wasn't one of our processes, or */
8642 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008643 } /* while (waitpid succeeds)... */
8644
8645 return rcode;
8646}
8647
8648#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008649static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008650{
8651 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008652 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008653 if (G_saved_tty_pgrp) {
8654 /* Job finished, move the shell to the foreground */
8655 p = getpgrp(); /* our process group id */
8656 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8657 tcsetpgrp(G_interactive_fd, p);
8658 }
8659 return rcode;
8660}
8661#endif
8662
8663/* Start all the jobs, but don't wait for anything to finish.
8664 * See checkjobs().
8665 *
8666 * Return code is normally -1, when the caller has to wait for children
8667 * to finish to determine the exit status of the pipe. If the pipe
8668 * is a simple builtin command, however, the action is done by the
8669 * time run_pipe returns, and the exit code is provided as the
8670 * return value.
8671 *
8672 * Returns -1 only if started some children. IOW: we have to
8673 * mask out retvals of builtins etc with 0xff!
8674 *
8675 * The only case when we do not need to [v]fork is when the pipe
8676 * is single, non-backgrounded, non-subshell command. Examples:
8677 * cmd ; ... { list } ; ...
8678 * cmd && ... { list } && ...
8679 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008680 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008681 * or (if SH_STANDALONE) an applet, and we can run the { list }
8682 * with run_list. If it isn't one of these, we fork and exec cmd.
8683 *
8684 * Cases when we must fork:
8685 * non-single: cmd | cmd
8686 * backgrounded: cmd & { list } &
8687 * subshell: ( list ) [&]
8688 */
8689#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008690#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8691 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008692#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008693static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008694 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008695 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008696 char **argv_expanded)
8697{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008698 /* Assignments occur before redirects. Try:
8699 * a=`sleep 1` sleep 2 3>/qwe/rty
8700 */
8701
8702 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8703 dump_cmd_in_x_mode(new_env);
8704 dump_cmd_in_x_mode(argv_expanded);
8705 /* this takes ownership of new_env[i] elements, and frees new_env: */
8706 set_vars_and_save_old(new_env);
8707
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008708 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008709}
8710static NOINLINE int run_pipe(struct pipe *pi)
8711{
8712 static const char *const null_ptr = NULL;
8713
8714 int cmd_no;
8715 int next_infd;
8716 struct command *command;
8717 char **argv_expanded;
8718 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008719 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008720 int rcode;
8721
8722 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8723 debug_enter();
8724
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008725 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8726 * Result should be 3 lines: q w e, qwe, q w e
8727 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008728 if (G.ifs_whitespace != G.ifs)
8729 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008730 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008731 if (G.ifs) {
8732 char *p;
8733 G.ifs_whitespace = (char*)G.ifs;
8734 p = skip_whitespace(G.ifs);
8735 if (*p) {
8736 /* Not all $IFS is whitespace */
8737 char *d;
8738 int len = p - G.ifs;
8739 p = skip_non_whitespace(p);
8740 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8741 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8742 while (*p) {
8743 if (isspace(*p))
8744 *d++ = *p;
8745 p++;
8746 }
8747 *d = '\0';
8748 }
8749 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008750 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008751 G.ifs_whitespace = (char*)G.ifs;
8752 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008753
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008754 IF_HUSH_JOB(pi->pgrp = -1;)
8755 pi->stopped_cmds = 0;
8756 command = &pi->cmds[0];
8757 argv_expanded = NULL;
8758
8759 if (pi->num_cmds != 1
8760 || pi->followup == PIPE_BG
8761 || command->cmd_type == CMD_SUBSHELL
8762 ) {
8763 goto must_fork;
8764 }
8765
8766 pi->alive_cmds = 1;
8767
8768 debug_printf_exec(": group:%p argv:'%s'\n",
8769 command->group, command->argv ? command->argv[0] : "NONE");
8770
8771 if (command->group) {
8772#if ENABLE_HUSH_FUNCTIONS
8773 if (command->cmd_type == CMD_FUNCDEF) {
8774 /* "executing" func () { list } */
8775 struct function *funcp;
8776
8777 funcp = new_function(command->argv[0]);
8778 /* funcp->name is already set to argv[0] */
8779 funcp->body = command->group;
8780# if !BB_MMU
8781 funcp->body_as_string = command->group_as_string;
8782 command->group_as_string = NULL;
8783# endif
8784 command->group = NULL;
8785 command->argv[0] = NULL;
8786 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8787 funcp->parent_cmd = command;
8788 command->child_func = funcp;
8789
8790 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8791 debug_leave();
8792 return EXIT_SUCCESS;
8793 }
8794#endif
8795 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008796 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008797 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008798 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008799 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008800//FIXME: we need to pass squirrel down into run_list()
8801//for SH_STANDALONE case, or else this construct:
8802// { find /proc/self/fd; true; } >FILE; cmd2
8803//has no way of closing saved fd#1 for "find",
8804//and in SH_STANDALONE mode, "find" is not execed,
8805//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008806 rcode = run_list(command->group) & 0xff;
8807 }
8808 restore_redirects(squirrel);
8809 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8810 debug_leave();
8811 debug_printf_exec("run_pipe: return %d\n", rcode);
8812 return rcode;
8813 }
8814
8815 argv = command->argv ? command->argv : (char **) &null_ptr;
8816 {
8817 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008818 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8819 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008820 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008821 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008822
Denys Vlasenko5807e182018-02-08 19:19:04 +01008823#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008824 if (G.lineno_var)
8825 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8826#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008827
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008828 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008829 /* Assignments, but no command.
8830 * Ensure redirects take effect (that is, create files).
8831 * Try "a=t >file"
8832 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008833 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008834 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008835 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008836 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008837 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008838
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008839 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008840 i = 0;
8841 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008842 char *p = expand_string_to_string(argv[i],
8843 EXP_FLAG_ESC_GLOB_CHARS,
8844 /*unbackslash:*/ 1
8845 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008846#if ENABLE_HUSH_MODE_X
8847 if (G_x_mode) {
8848 if (i == 0) {
8849 unsigned n = G.x_mode_depth;
8850 do
8851 bb_putchar_stderr('+');
8852 while ((int)(--n) >= 0);
8853 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008854 fprintf(stderr, " %s", p);
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008855 }
8856#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008857 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008858 if (set_local_var(p, /*flag:*/ 0)) {
8859 /* assignment to readonly var / putenv error? */
8860 rcode = 1;
8861 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008862 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008863 }
8864 if (G_x_mode)
8865 bb_putchar_stderr('\n');
8866 /* Redirect error sets $? to 1. Otherwise,
8867 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008868 * Else, clear $?:
8869 * false; q=`exit 2`; echo $? - should print 2
8870 * false; x=1; echo $? - should print 0
8871 * Because of the 2nd case, we can't just use G.last_exitcode.
8872 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008873 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008874 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008875 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8876 debug_leave();
8877 debug_printf_exec("run_pipe: return %d\n", rcode);
8878 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008879 }
8880
8881 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008882#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008883 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008884 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008885 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008886#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008887 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008888
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008889 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008890 if (!argv_expanded[0]) {
8891 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008892 /* `false` still has to set exitcode 1 */
8893 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008894 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008895 }
8896
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008897 old_vars = NULL;
8898 sv_shadowed = G.shadowed_vars_pp;
8899
Denys Vlasenko75481d32017-07-31 05:27:09 +02008900 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008901 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8902 IF_HUSH_FUNCTIONS(x = NULL;)
8903 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008904 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008905 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008906 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8907 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008908 /*
8909 * Variable assignments are executed, but then "forgotten":
8910 * a=`sleep 1;echo A` exec 3>&-; echo $a
8911 * sleeps, but prints nothing.
8912 */
8913 enter_var_nest_level();
8914 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008915 rcode = redirect_and_varexp_helper(command,
8916 /*squirrel:*/ ERR_PTR,
8917 argv_expanded
8918 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008919 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008920 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008921
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008922 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008923 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008924
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008925 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008926 * a=b true; env | grep ^a=
8927 */
8928 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008929 /* Collect all variables "shadowed" by helper
8930 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8931 * into old_vars list:
8932 */
8933 G.shadowed_vars_pp = &old_vars;
8934 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008935 if (rcode == 0) {
8936 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008937 /* Do not collect *to old_vars list* vars shadowed
8938 * by e.g. "local VAR" builtin (collect them
8939 * in the previously nested list instead):
8940 * don't want them to be restored immediately
8941 * after "local" completes.
8942 */
8943 G.shadowed_vars_pp = sv_shadowed;
8944
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008945 debug_printf_exec(": builtin '%s' '%s'...\n",
8946 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008947 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008948 rcode = x->b_function(argv_expanded) & 0xff;
8949 fflush_all();
8950 }
8951#if ENABLE_HUSH_FUNCTIONS
8952 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008953 debug_printf_exec(": function '%s' '%s'...\n",
8954 funcp->name, argv_expanded[1]);
8955 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008956 /*
8957 * But do collect *to old_vars list* vars shadowed
8958 * within function execution. To that end, restore
8959 * this pointer _after_ function run:
8960 */
8961 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008962 }
8963#endif
8964 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008965 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008966 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008967 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008968 if (n < 0 || !APPLET_IS_NOFORK(n))
8969 goto must_fork;
8970
8971 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008972 /* Collect all variables "shadowed" by helper into old_vars list */
8973 G.shadowed_vars_pp = &old_vars;
8974 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8975 G.shadowed_vars_pp = sv_shadowed;
8976
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008977 if (rcode == 0) {
8978 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8979 argv_expanded[0], argv_expanded[1]);
8980 /*
8981 * Note: signals (^C) can't interrupt here.
8982 * We remember them and they will be acted upon
8983 * after applet returns.
8984 * This makes applets which can run for a long time
8985 * and/or wait for user input ineligible for NOFORK:
8986 * for example, "yes" or "rm" (rm -i waits for input).
8987 */
8988 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008989 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008990 } else
8991 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008992
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008993 restore_redirects(squirrel);
8994 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008995 leave_var_nest_level();
8996 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008997
8998 /*
8999 * Try "usleep 99999999" + ^C + "echo $?"
9000 * with FEATURE_SH_NOFORK=y.
9001 */
9002 if (!funcp) {
9003 /* It was builtin or nofork.
9004 * if this would be a real fork/execed program,
9005 * it should have died if a fatal sig was received.
9006 * But OTOH, there was no separate process,
9007 * the sig was sent to _shell_, not to non-existing
9008 * child.
9009 * Let's just handle ^C only, this one is obvious:
9010 * we aren't ok with exitcode 0 when ^C was pressed
9011 * during builtin/nofork.
9012 */
9013 if (sigismember(&G.pending_set, SIGINT))
9014 rcode = 128 + SIGINT;
9015 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009016 free(argv_expanded);
9017 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9018 debug_leave();
9019 debug_printf_exec("run_pipe return %d\n", rcode);
9020 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009021 }
9022
9023 must_fork:
9024 /* NB: argv_expanded may already be created, and that
9025 * might include `cmd` runs! Do not rerun it! We *must*
9026 * use argv_expanded if it's non-NULL */
9027
9028 /* Going to fork a child per each pipe member */
9029 pi->alive_cmds = 0;
9030 next_infd = 0;
9031
9032 cmd_no = 0;
9033 while (cmd_no < pi->num_cmds) {
9034 struct fd_pair pipefds;
9035#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009036 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009037 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009038 nommu_save.old_vars = NULL;
9039 nommu_save.argv = NULL;
9040 nommu_save.argv_from_re_execing = NULL;
9041#endif
9042 command = &pi->cmds[cmd_no];
9043 cmd_no++;
9044 if (command->argv) {
9045 debug_printf_exec(": pipe member '%s' '%s'...\n",
9046 command->argv[0], command->argv[1]);
9047 } else {
9048 debug_printf_exec(": pipe member with no argv\n");
9049 }
9050
9051 /* pipes are inserted between pairs of commands */
9052 pipefds.rd = 0;
9053 pipefds.wr = 1;
9054 if (cmd_no < pi->num_cmds)
9055 xpiped_pair(pipefds);
9056
Denys Vlasenko5807e182018-02-08 19:19:04 +01009057#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009058 if (G.lineno_var)
9059 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
9060#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009061
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009062 command->pid = BB_MMU ? fork() : vfork();
9063 if (!command->pid) { /* child */
9064#if ENABLE_HUSH_JOB
9065 disable_restore_tty_pgrp_on_exit();
9066 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9067
9068 /* Every child adds itself to new process group
9069 * with pgid == pid_of_first_child_in_pipe */
9070 if (G.run_list_level == 1 && G_interactive_fd) {
9071 pid_t pgrp;
9072 pgrp = pi->pgrp;
9073 if (pgrp < 0) /* true for 1st process only */
9074 pgrp = getpid();
9075 if (setpgid(0, pgrp) == 0
9076 && pi->followup != PIPE_BG
9077 && G_saved_tty_pgrp /* we have ctty */
9078 ) {
9079 /* We do it in *every* child, not just first,
9080 * to avoid races */
9081 tcsetpgrp(G_interactive_fd, pgrp);
9082 }
9083 }
9084#endif
9085 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9086 /* 1st cmd in backgrounded pipe
9087 * should have its stdin /dev/null'ed */
9088 close(0);
9089 if (open(bb_dev_null, O_RDONLY))
9090 xopen("/", O_RDONLY);
9091 } else {
9092 xmove_fd(next_infd, 0);
9093 }
9094 xmove_fd(pipefds.wr, 1);
9095 if (pipefds.rd > 1)
9096 close(pipefds.rd);
9097 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009098 * and the pipe fd (fd#1) is available for dup'ing:
9099 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9100 * of cmd1 goes into pipe.
9101 */
9102 if (setup_redirects(command, NULL)) {
9103 /* Happens when redir file can't be opened:
9104 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9105 * FOO
9106 * hush: can't open '/qwe/rty': No such file or directory
9107 * BAZ
9108 * (echo BAR is not executed, it hits _exit(1) below)
9109 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009110 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009111 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009112
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009113 /* Stores to nommu_save list of env vars putenv'ed
9114 * (NOMMU, on MMU we don't need that) */
9115 /* cast away volatility... */
9116 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9117 /* pseudo_exec() does not return */
9118 }
9119
9120 /* parent or error */
9121#if ENABLE_HUSH_FAST
9122 G.count_SIGCHLD++;
9123//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9124#endif
9125 enable_restore_tty_pgrp_on_exit();
9126#if !BB_MMU
9127 /* Clean up after vforked child */
9128 free(nommu_save.argv);
9129 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009130 G.var_nest_level = sv_var_nest_level;
9131 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009132 add_vars(nommu_save.old_vars);
9133#endif
9134 free(argv_expanded);
9135 argv_expanded = NULL;
9136 if (command->pid < 0) { /* [v]fork failed */
9137 /* Clearly indicate, was it fork or vfork */
9138 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9139 } else {
9140 pi->alive_cmds++;
9141#if ENABLE_HUSH_JOB
9142 /* Second and next children need to know pid of first one */
9143 if (pi->pgrp < 0)
9144 pi->pgrp = command->pid;
9145#endif
9146 }
9147
9148 if (cmd_no > 1)
9149 close(next_infd);
9150 if (cmd_no < pi->num_cmds)
9151 close(pipefds.wr);
9152 /* Pass read (output) pipe end to next iteration */
9153 next_infd = pipefds.rd;
9154 }
9155
9156 if (!pi->alive_cmds) {
9157 debug_leave();
9158 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9159 return 1;
9160 }
9161
9162 debug_leave();
9163 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9164 return -1;
9165}
9166
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009167/* NB: called by pseudo_exec, and therefore must not modify any
9168 * global data until exec/_exit (we can be a child after vfork!) */
9169static int run_list(struct pipe *pi)
9170{
9171#if ENABLE_HUSH_CASE
9172 char *case_word = NULL;
9173#endif
9174#if ENABLE_HUSH_LOOPS
9175 struct pipe *loop_top = NULL;
9176 char **for_lcur = NULL;
9177 char **for_list = NULL;
9178#endif
9179 smallint last_followup;
9180 smalluint rcode;
9181#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9182 smalluint cond_code = 0;
9183#else
9184 enum { cond_code = 0 };
9185#endif
9186#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009187 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009188 smallint last_rword; /* ditto */
9189#endif
9190
9191 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9192 debug_enter();
9193
9194#if ENABLE_HUSH_LOOPS
9195 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009196 {
9197 struct pipe *cpipe;
9198 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9199 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9200 continue;
9201 /* current word is FOR or IN (BOLD in comments below) */
9202 if (cpipe->next == NULL) {
9203 syntax_error("malformed for");
9204 debug_leave();
9205 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9206 return 1;
9207 }
9208 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9209 if (cpipe->next->res_word == RES_DO)
9210 continue;
9211 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9212 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9213 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9214 ) {
9215 syntax_error("malformed for");
9216 debug_leave();
9217 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9218 return 1;
9219 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009220 }
9221 }
9222#endif
9223
9224 /* Past this point, all code paths should jump to ret: label
9225 * in order to return, no direct "return" statements please.
9226 * This helps to ensure that no memory is leaked. */
9227
9228#if ENABLE_HUSH_JOB
9229 G.run_list_level++;
9230#endif
9231
9232#if HAS_KEYWORDS
9233 rword = RES_NONE;
9234 last_rword = RES_XXXX;
9235#endif
9236 last_followup = PIPE_SEQ;
9237 rcode = G.last_exitcode;
9238
9239 /* Go through list of pipes, (maybe) executing them. */
9240 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009241 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009242 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009243
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009244 if (G.flag_SIGINT)
9245 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009246 if (G_flag_return_in_progress == 1)
9247 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009248
9249 IF_HAS_KEYWORDS(rword = pi->res_word;)
9250 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9251 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009252
9253 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009254 if (
9255#if ENABLE_HUSH_IF
9256 rword == RES_IF || rword == RES_ELIF ||
9257#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009258 pi->followup != PIPE_SEQ
9259 ) {
9260 G.errexit_depth++;
9261 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009262#if ENABLE_HUSH_LOOPS
9263 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9264 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9265 ) {
9266 /* start of a loop: remember where loop starts */
9267 loop_top = pi;
9268 G.depth_of_loop++;
9269 }
9270#endif
9271 /* Still in the same "if...", "then..." or "do..." branch? */
9272 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9273 if ((rcode == 0 && last_followup == PIPE_OR)
9274 || (rcode != 0 && last_followup == PIPE_AND)
9275 ) {
9276 /* It is "<true> || CMD" or "<false> && CMD"
9277 * and we should not execute CMD */
9278 debug_printf_exec("skipped cmd because of || or &&\n");
9279 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009280 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009281 }
9282 }
9283 last_followup = pi->followup;
9284 IF_HAS_KEYWORDS(last_rword = rword;)
9285#if ENABLE_HUSH_IF
9286 if (cond_code) {
9287 if (rword == RES_THEN) {
9288 /* if false; then ... fi has exitcode 0! */
9289 G.last_exitcode = rcode = EXIT_SUCCESS;
9290 /* "if <false> THEN cmd": skip cmd */
9291 continue;
9292 }
9293 } else {
9294 if (rword == RES_ELSE || rword == RES_ELIF) {
9295 /* "if <true> then ... ELSE/ELIF cmd":
9296 * skip cmd and all following ones */
9297 break;
9298 }
9299 }
9300#endif
9301#if ENABLE_HUSH_LOOPS
9302 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9303 if (!for_lcur) {
9304 /* first loop through for */
9305
9306 static const char encoded_dollar_at[] ALIGN1 = {
9307 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9308 }; /* encoded representation of "$@" */
9309 static const char *const encoded_dollar_at_argv[] = {
9310 encoded_dollar_at, NULL
9311 }; /* argv list with one element: "$@" */
9312 char **vals;
9313
9314 vals = (char**)encoded_dollar_at_argv;
9315 if (pi->next->res_word == RES_IN) {
9316 /* if no variable values after "in" we skip "for" */
9317 if (!pi->next->cmds[0].argv) {
9318 G.last_exitcode = rcode = EXIT_SUCCESS;
9319 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9320 break;
9321 }
9322 vals = pi->next->cmds[0].argv;
9323 } /* else: "for var; do..." -> assume "$@" list */
9324 /* create list of variable values */
9325 debug_print_strings("for_list made from", vals);
9326 for_list = expand_strvec_to_strvec(vals);
9327 for_lcur = for_list;
9328 debug_print_strings("for_list", for_list);
9329 }
9330 if (!*for_lcur) {
9331 /* "for" loop is over, clean up */
9332 free(for_list);
9333 for_list = NULL;
9334 for_lcur = NULL;
9335 break;
9336 }
9337 /* Insert next value from for_lcur */
9338 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009339 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009340 continue;
9341 }
9342 if (rword == RES_IN) {
9343 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9344 }
9345 if (rword == RES_DONE) {
9346 continue; /* "done" has no cmds too */
9347 }
9348#endif
9349#if ENABLE_HUSH_CASE
9350 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009351 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009352 case_word = expand_string_to_string(pi->cmds->argv[0],
9353 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009354 debug_printf_exec("CASE word1:'%s'\n", case_word);
9355 //unbackslash(case_word);
9356 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009357 continue;
9358 }
9359 if (rword == RES_MATCH) {
9360 char **argv;
9361
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009362 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009363 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9364 break;
9365 /* all prev words didn't match, does this one match? */
9366 argv = pi->cmds->argv;
9367 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009368 char *pattern;
9369 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9370 pattern = expand_string_to_string(*argv,
9371 EXP_FLAG_ESC_GLOB_CHARS,
9372 /*unbackslash:*/ 0
9373 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009374 /* TODO: which FNM_xxx flags to use? */
9375 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009376 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9377 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009378 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009379 if (cond_code == 0) {
9380 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009381 free(case_word);
9382 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009383 break;
9384 }
9385 argv++;
9386 }
9387 continue;
9388 }
9389 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009390 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009391 if (cond_code != 0)
9392 continue; /* not matched yet, skip this pipe */
9393 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009394 if (rword == RES_ESAC) {
9395 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9396 if (case_word) {
9397 /* "case" did not match anything: still set $? (to 0) */
9398 G.last_exitcode = rcode = EXIT_SUCCESS;
9399 }
9400 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009401#endif
9402 /* Just pressing <enter> in shell should check for jobs.
9403 * OTOH, in non-interactive shell this is useless
9404 * and only leads to extra job checks */
9405 if (pi->num_cmds == 0) {
9406 if (G_interactive_fd)
9407 goto check_jobs_and_continue;
9408 continue;
9409 }
9410
9411 /* After analyzing all keywords and conditions, we decided
9412 * to execute this pipe. NB: have to do checkjobs(NULL)
9413 * after run_pipe to collect any background children,
9414 * even if list execution is to be stopped. */
9415 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009416#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009417 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009418#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009419 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9420 if (r != -1) {
9421 /* We ran a builtin, function, or group.
9422 * rcode is already known
9423 * and we don't need to wait for anything. */
9424 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9425 G.last_exitcode = rcode;
9426 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009427#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009428 /* Was it "break" or "continue"? */
9429 if (G.flag_break_continue) {
9430 smallint fbc = G.flag_break_continue;
9431 /* We might fall into outer *loop*,
9432 * don't want to break it too */
9433 if (loop_top) {
9434 G.depth_break_continue--;
9435 if (G.depth_break_continue == 0)
9436 G.flag_break_continue = 0;
9437 /* else: e.g. "continue 2" should *break* once, *then* continue */
9438 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9439 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009440 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009441 break;
9442 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009443 /* "continue": simulate end of loop */
9444 rword = RES_DONE;
9445 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009446 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009447#endif
9448 if (G_flag_return_in_progress == 1) {
9449 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9450 break;
9451 }
9452 } else if (pi->followup == PIPE_BG) {
9453 /* What does bash do with attempts to background builtins? */
9454 /* even bash 3.2 doesn't do that well with nested bg:
9455 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9456 * I'm NOT treating inner &'s as jobs */
9457#if ENABLE_HUSH_JOB
9458 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009459 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009460#endif
9461 /* Last command's pid goes to $! */
9462 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009463 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009464 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009465/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009466 rcode = EXIT_SUCCESS;
9467 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009468 } else {
9469#if ENABLE_HUSH_JOB
9470 if (G.run_list_level == 1 && G_interactive_fd) {
9471 /* Waits for completion, then fg's main shell */
9472 rcode = checkjobs_and_fg_shell(pi);
9473 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009474 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009475 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009476#endif
9477 /* This one just waits for completion */
9478 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9479 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9480 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009481 G.last_exitcode = rcode;
9482 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009483 }
9484
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009485 /* Handle "set -e" */
9486 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9487 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9488 if (G.errexit_depth == 0)
9489 hush_exit(rcode);
9490 }
9491 G.errexit_depth = sv_errexit_depth;
9492
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009493 /* Analyze how result affects subsequent commands */
9494#if ENABLE_HUSH_IF
9495 if (rword == RES_IF || rword == RES_ELIF)
9496 cond_code = rcode;
9497#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009498 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009499 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009500 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009501#if ENABLE_HUSH_LOOPS
9502 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009503 if (pi->next
9504 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009505 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009506 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009507 if (rword == RES_WHILE) {
9508 if (rcode) {
9509 /* "while false; do...done" - exitcode 0 */
9510 G.last_exitcode = rcode = EXIT_SUCCESS;
9511 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009512 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009513 }
9514 }
9515 if (rword == RES_UNTIL) {
9516 if (!rcode) {
9517 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009518 break;
9519 }
9520 }
9521 }
9522#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009523 } /* for (pi) */
9524
9525#if ENABLE_HUSH_JOB
9526 G.run_list_level--;
9527#endif
9528#if ENABLE_HUSH_LOOPS
9529 if (loop_top)
9530 G.depth_of_loop--;
9531 free(for_list);
9532#endif
9533#if ENABLE_HUSH_CASE
9534 free(case_word);
9535#endif
9536 debug_leave();
9537 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9538 return rcode;
9539}
9540
9541/* Select which version we will use */
9542static int run_and_free_list(struct pipe *pi)
9543{
9544 int rcode = 0;
9545 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009546 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009547 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9548 rcode = run_list(pi);
9549 }
9550 /* free_pipe_list has the side effect of clearing memory.
9551 * In the long run that function can be merged with run_list,
9552 * but doing that now would hobble the debugging effort. */
9553 free_pipe_list(pi);
9554 debug_printf_exec("run_and_free_list return %d\n", rcode);
9555 return rcode;
9556}
9557
9558
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009559static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009560{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009561 sighandler_t old_handler;
9562 unsigned sig = 0;
9563 while ((mask >>= 1) != 0) {
9564 sig++;
9565 if (!(mask & 1))
9566 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009567 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009568 /* POSIX allows shell to re-enable SIGCHLD
9569 * even if it was SIG_IGN on entry.
9570 * Therefore we skip IGN check for it:
9571 */
9572 if (sig == SIGCHLD)
9573 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009574 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9575 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9576 */
9577 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009578 if (old_handler == SIG_IGN) {
9579 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009580 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009581#if ENABLE_HUSH_TRAP
9582 if (!G_traps)
9583 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9584 free(G_traps[sig]);
9585 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9586#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009587 }
9588 }
9589}
9590
9591/* Called a few times only (or even once if "sh -c") */
9592static void install_special_sighandlers(void)
9593{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009594 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009595
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009596 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009597 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009598 if (G_interactive_fd) {
9599 mask |= SPECIAL_INTERACTIVE_SIGS;
9600 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009601 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009602 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009603 /* Careful, do not re-install handlers we already installed */
9604 if (G.special_sig_mask != mask) {
9605 unsigned diff = mask & ~G.special_sig_mask;
9606 G.special_sig_mask = mask;
9607 install_sighandlers(diff);
9608 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009609}
9610
9611#if ENABLE_HUSH_JOB
9612/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009613/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009614static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009615{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009616 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009617
9618 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009619 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009620 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9621 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009622 + (1 << SIGBUS ) * HUSH_DEBUG
9623 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009624 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009625 + (1 << SIGABRT)
9626 /* bash 3.2 seems to handle these just like 'fatal' ones */
9627 + (1 << SIGPIPE)
9628 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009629 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009630 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009631 * we never want to restore pgrp on exit, and this fn is not called
9632 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009633 /*+ (1 << SIGHUP )*/
9634 /*+ (1 << SIGTERM)*/
9635 /*+ (1 << SIGINT )*/
9636 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009637 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009638
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009639 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009640}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009641#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009642
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009643static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009644{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009645 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009646 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009647 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009648 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009649 break;
9650 case 'x':
9651 IF_HUSH_MODE_X(G_x_mode = state;)
9652 break;
9653 case 'o':
9654 if (!o_opt) {
9655 /* "set -+o" without parameter.
9656 * in bash, set -o produces this output:
9657 * pipefail off
9658 * and set +o:
9659 * set +o pipefail
9660 * We always use the second form.
9661 */
9662 const char *p = o_opt_strings;
9663 idx = 0;
9664 while (*p) {
9665 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9666 idx++;
9667 p += strlen(p) + 1;
9668 }
9669 break;
9670 }
9671 idx = index_in_strings(o_opt_strings, o_opt);
9672 if (idx >= 0) {
9673 G.o_opt[idx] = state;
9674 break;
9675 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009676 case 'e':
9677 G.o_opt[OPT_O_ERREXIT] = state;
9678 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009679 default:
9680 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009681 }
9682 return EXIT_SUCCESS;
9683}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009684
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009685int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009686int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009687{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009688 enum {
9689 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009690 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009691 };
9692 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009693 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009694 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009695 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009696 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009697
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009698 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009699 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009700 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009701
Denys Vlasenko10c01312011-05-11 11:49:21 +02009702#if ENABLE_HUSH_FAST
9703 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9704#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009705#if !BB_MMU
9706 G.argv0_for_re_execing = argv[0];
9707#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009708
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009709 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009710 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9711 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009712 shell_ver = xzalloc(sizeof(*shell_ver));
9713 shell_ver->flg_export = 1;
9714 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009715 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009716 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009717 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009718
Denys Vlasenko605067b2010-09-06 12:10:51 +02009719 /* Create shell local variables from the values
9720 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009721 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009722 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009723 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009724 if (e) while (*e) {
9725 char *value = strchr(*e, '=');
9726 if (value) { /* paranoia */
9727 cur_var->next = xzalloc(sizeof(*cur_var));
9728 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009729 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009730 cur_var->max_len = strlen(*e);
9731 cur_var->flg_export = 1;
9732 }
9733 e++;
9734 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009735 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009736 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9737 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009738
9739 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009740 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009741
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009742#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9743 /* Set (but not export) PS1/2 unless already set */
9744 if (!get_local_var_value("PS1"))
9745 set_local_var_from_halves("PS1", "\\w \\$ ");
9746 if (!get_local_var_value("PS2"))
9747 set_local_var_from_halves("PS2", "> ");
9748#endif
9749
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009750#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009751 /* Set (but not export) HOSTNAME unless already set */
9752 if (!get_local_var_value("HOSTNAME")) {
9753 struct utsname uts;
9754 uname(&uts);
9755 set_local_var_from_halves("HOSTNAME", uts.nodename);
9756 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009757 /* bash also exports SHLVL and _,
9758 * and sets (but doesn't export) the following variables:
9759 * BASH=/bin/bash
9760 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9761 * BASH_VERSION='3.2.0(1)-release'
9762 * HOSTTYPE=i386
9763 * MACHTYPE=i386-pc-linux-gnu
9764 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009765 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009766 * EUID=<NNNNN>
9767 * UID=<NNNNN>
9768 * GROUPS=()
9769 * LINES=<NNN>
9770 * COLUMNS=<NNN>
9771 * BASH_ARGC=()
9772 * BASH_ARGV=()
9773 * BASH_LINENO=()
9774 * BASH_SOURCE=()
9775 * DIRSTACK=()
9776 * PIPESTATUS=([0]="0")
9777 * HISTFILE=/<xxx>/.bash_history
9778 * HISTFILESIZE=500
9779 * HISTSIZE=500
9780 * MAILCHECK=60
9781 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9782 * SHELL=/bin/bash
9783 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9784 * TERM=dumb
9785 * OPTERR=1
9786 * OPTIND=1
9787 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009788 * PS4='+ '
9789 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009790#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009791
Denys Vlasenko5807e182018-02-08 19:19:04 +01009792#if ENABLE_HUSH_LINENO_VAR
9793 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009794 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9795 set_local_var(p, /*flags*/ 0);
9796 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9797 }
9798#endif
9799
Denis Vlasenko38f63192007-01-22 09:03:07 +00009800#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009801 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009802#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009803
Eric Andersen94ac2442001-05-22 19:05:18 +00009804 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009805 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009806
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009807 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009808
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009809 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009810 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009811 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009812 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009813 * in order to intercept (more) signals.
9814 */
9815
9816 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009817 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009818 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009819 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009820 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009821 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009822#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009823 "<:$:R:V:"
9824# if ENABLE_HUSH_FUNCTIONS
9825 "F:"
9826# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009827#endif
9828 );
9829 if (opt <= 0)
9830 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009831 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009832 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009833 /* Possibilities:
9834 * sh ... -c 'script'
9835 * sh ... -c 'script' ARG0 [ARG1...]
9836 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009837 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009838 * "" needs to be replaced with NULL
9839 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009840 * Note: the form without ARG0 never happens:
9841 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009842 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009843 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009844 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009845 G.root_ppid = getppid();
9846 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009847 G.global_argv = argv + optind;
9848 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009849 if (builtin_argc) {
9850 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9851 const struct built_in_command *x;
9852
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009853 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009854 x = find_builtin(optarg);
9855 if (x) { /* paranoia */
9856 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9857 G.global_argv += builtin_argc;
9858 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009859 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009860 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009861 }
9862 goto final_return;
9863 }
9864 if (!G.global_argv[0]) {
9865 /* -c 'script' (no params): prevent empty $0 */
9866 G.global_argv--; /* points to argv[i] of 'script' */
9867 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009868 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009869 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009870 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009871 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009872 goto final_return;
9873 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009874 /* Well, we cannot just declare interactiveness,
9875 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009876 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009877 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009878 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009879 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009880 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009881 case 'l':
9882 flags |= OPT_login;
9883 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009884#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009885 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009886 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009887 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009888 case '$': {
9889 unsigned long long empty_trap_mask;
9890
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009891 G.root_pid = bb_strtou(optarg, &optarg, 16);
9892 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009893 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9894 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009895 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9896 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009897 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009898 optarg++;
9899 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009900 optarg++;
9901 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9902 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009903 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009904 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009905# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009906 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009907 for (sig = 1; sig < NSIG; sig++) {
9908 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009909 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009910 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009911 }
9912 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009913# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009914 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009915# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009916 optarg++;
9917 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009918# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009919# if ENABLE_HUSH_FUNCTIONS
9920 /* nommu uses re-exec trick for "... | func | ...",
9921 * should allow "return".
9922 * This accidentally allows returns in subshells.
9923 */
9924 G_flag_return_in_progress = -1;
9925# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009926 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009927 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009928 case 'R':
9929 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009930 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009931 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009932# if ENABLE_HUSH_FUNCTIONS
9933 case 'F': {
9934 struct function *funcp = new_function(optarg);
9935 /* funcp->name is already set to optarg */
9936 /* funcp->body is set to NULL. It's a special case. */
9937 funcp->body_as_string = argv[optind];
9938 optind++;
9939 break;
9940 }
9941# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009942#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009943 case 'n':
9944 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009945 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009946 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009947 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009948 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009949#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009950 fprintf(stderr, "Usage: sh [FILE]...\n"
9951 " or: sh -c command [args]...\n\n");
9952 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009953#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009954 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009955#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009956 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009957 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009958
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009959 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9960 G.global_argc = argc - (optind - 1);
9961 G.global_argv = argv + (optind - 1);
9962 G.global_argv[0] = argv[0];
9963
Denys Vlasenkodea47882009-10-09 15:40:49 +02009964 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009965 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009966 G.root_ppid = getppid();
9967 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009968
9969 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009970 if (flags & OPT_login) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009971 HFILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009972 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009973 input = hfopen("/etc/profile");
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009974 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009975 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009976 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009977 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009978 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009979 /* bash: after sourcing /etc/profile,
9980 * tries to source (in the given order):
9981 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009982 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009983 * bash also sources ~/.bash_logout on exit.
9984 * If called as sh, skips .bash_XXX files.
9985 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009986 }
9987
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009988 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9989 if (!(flags & OPT_s) && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009990 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +00009991 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009992 * "bash <script>" (which is never interactive (unless -i?))
9993 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009994 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009995 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009996 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009997 G.global_argc--;
9998 G.global_argv++;
9999 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010000 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010001 input = hfopen(G.global_argv[0]);
10002 if (!input) {
10003 bb_simple_perror_msg_and_die(G.global_argv[0]);
10004 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010005 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010006 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010007 parse_and_run_file(input);
10008#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010009 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010010#endif
10011 goto final_return;
10012 }
10013
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010014 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010015 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010016 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010017
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010018 /* A shell is interactive if the '-i' flag was given,
10019 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010020 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010021 * no arguments remaining or the -s flag given
10022 * standard input is a terminal
10023 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010024 * Refer to Posix.2, the description of the 'sh' utility.
10025 */
10026#if ENABLE_HUSH_JOB
10027 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010028 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10029 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10030 if (G_saved_tty_pgrp < 0)
10031 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010032
10033 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010034 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010035 if (G_interactive_fd < 0) {
10036 /* try to dup to any fd */
10037 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010038 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010039 /* give up */
10040 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010041 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010042 }
10043 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010044// TODO: track & disallow any attempts of user
10045// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +000010046 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010047 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010048 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010049 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010050
Mike Frysinger38478a62009-05-20 04:48:06 -040010051 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010052 /* If we were run as 'hush &', sleep until we are
10053 * in the foreground (tty pgrp == our pgrp).
10054 * If we get started under a job aware app (like bash),
10055 * make sure we are now in charge so we don't fight over
10056 * who gets the foreground */
10057 while (1) {
10058 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010059 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10060 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010061 break;
10062 /* send TTIN to ourself (should stop us) */
10063 kill(- shell_pgrp, SIGTTIN);
10064 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010065 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010066
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010067 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010068 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010069
Mike Frysinger38478a62009-05-20 04:48:06 -040010070 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010071 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010072 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010073 /* Put ourselves in our own process group
10074 * (bash, too, does this only if ctty is available) */
10075 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10076 /* Grab control of the terminal */
10077 tcsetpgrp(G_interactive_fd, getpid());
10078 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010079 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010080
10081# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10082 {
10083 const char *hp = get_local_var_value("HISTFILE");
10084 if (!hp) {
10085 hp = get_local_var_value("HOME");
10086 if (hp)
10087 hp = concat_path_file(hp, ".hush_history");
10088 } else {
10089 hp = xstrdup(hp);
10090 }
10091 if (hp) {
10092 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010093 //set_local_var(xasprintf("HISTFILE=%s", ...));
10094 }
10095# if ENABLE_FEATURE_SH_HISTFILESIZE
10096 hp = get_local_var_value("HISTFILESIZE");
10097 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10098# endif
10099 }
10100# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010101 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010102 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010103 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010104#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010105 /* No job control compiled in, only prompt/line editing */
10106 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010107 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010108 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010109 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010110 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010111 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010112 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010113 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010114 }
10115 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010116 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010117 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010118 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010119 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010120#else
10121 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010122 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010123#endif
10124 /* bash:
10125 * if interactive but not a login shell, sources ~/.bashrc
10126 * (--norc turns this off, --rcfile <file> overrides)
10127 */
10128
10129 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +020010130 /* note: ash and hush share this string */
10131 printf("\n\n%s %s\n"
10132 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10133 "\n",
10134 bb_banner,
10135 "hush - the humble shell"
10136 );
Mike Frysingerb2705e12009-03-23 08:44:02 +000010137 }
10138
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010139 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010140
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010141 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010142 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010143}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010144
10145
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010146/*
10147 * Built-ins
10148 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010149static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010150{
10151 return 0;
10152}
10153
Denys Vlasenko265062d2017-01-10 15:13:30 +010010154#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010155static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010156{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010157 int argc = string_array_len(argv);
10158 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010159}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010160#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010161#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010162static int FAST_FUNC builtin_test(char **argv)
10163{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010164 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010165}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010166#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010167#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010168static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010169{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010170 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010171}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010172#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010173#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010174static int FAST_FUNC builtin_printf(char **argv)
10175{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010176 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010177}
10178#endif
10179
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010180#if ENABLE_HUSH_HELP
10181static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10182{
10183 const struct built_in_command *x;
10184
10185 printf(
10186 "Built-in commands:\n"
10187 "------------------\n");
10188 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10189 if (x->b_descr)
10190 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10191 }
10192 return EXIT_SUCCESS;
10193}
10194#endif
10195
10196#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10197static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10198{
10199 show_history(G.line_input_state);
10200 return EXIT_SUCCESS;
10201}
10202#endif
10203
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010204static char **skip_dash_dash(char **argv)
10205{
10206 argv++;
10207 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10208 argv++;
10209 return argv;
10210}
10211
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010212static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010213{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010214 const char *newdir;
10215
10216 argv = skip_dash_dash(argv);
10217 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010218 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010219 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010220 * bash says "bash: cd: HOME not set" and does nothing
10221 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010222 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010223 const char *home = get_local_var_value("HOME");
10224 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010225 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010226 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010227 /* Mimic bash message exactly */
10228 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010229 return EXIT_FAILURE;
10230 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010231 /* Read current dir (get_cwd(1) is inside) and set PWD.
10232 * Note: do not enforce exporting. If PWD was unset or unexported,
10233 * set it again, but do not export. bash does the same.
10234 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010235 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010236 return EXIT_SUCCESS;
10237}
10238
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010239static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10240{
10241 puts(get_cwd(0));
10242 return EXIT_SUCCESS;
10243}
10244
10245static int FAST_FUNC builtin_eval(char **argv)
10246{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010247 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010248
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010249 if (!argv[0])
10250 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010251
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010252 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010253 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010254 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010255 /* bash:
10256 * eval "echo Hi; done" ("done" is syntax error):
10257 * "echo Hi" will not execute too.
10258 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010259 parse_and_run_string(argv[0]);
10260 } else {
10261 /* "The eval utility shall construct a command by
10262 * concatenating arguments together, separating
10263 * each with a <space> character."
10264 */
10265 char *str, *p;
10266 unsigned len = 0;
10267 char **pp = argv;
10268 do
10269 len += strlen(*pp) + 1;
10270 while (*++pp);
10271 str = p = xmalloc(len);
10272 pp = argv;
10273 for (;;) {
10274 p = stpcpy(p, *pp);
10275 pp++;
10276 if (!*pp)
10277 break;
10278 *p++ = ' ';
10279 }
10280 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010281 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010282 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010283 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010284 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010285 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010286}
10287
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010288static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010289{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010290 argv = skip_dash_dash(argv);
10291 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010292 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010293
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010294 /* Careful: we can end up here after [v]fork. Do not restore
10295 * tty pgrp then, only top-level shell process does that */
10296 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10297 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10298
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010299 /* Saved-redirect fds, script fds and G_interactive_fd are still
10300 * open here. However, they are all CLOEXEC, and execv below
10301 * closes them. Try interactive "exec ls -l /proc/self/fd",
10302 * it should show no extra open fds in the "ls" process.
10303 * If we'd try to run builtins/NOEXECs, this would need improving.
10304 */
10305 //close_saved_fds_and_FILE_fds();
10306
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010307 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010308 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010309 * and tcsetpgrp, and this is inherently racy.
10310 */
10311 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010312}
10313
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010314static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010315{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010316 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010317
10318 /* interactive bash:
10319 * # trap "echo EEE" EXIT
10320 * # exit
10321 * exit
10322 * There are stopped jobs.
10323 * (if there are _stopped_ jobs, running ones don't count)
10324 * # exit
10325 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010326 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010327 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010328 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010329 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010330
10331 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010332 argv = skip_dash_dash(argv);
10333 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010334 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010335 /* mimic bash: exit 123abc == exit 255 + error msg */
10336 xfunc_error_retval = 255;
10337 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010338 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010339}
10340
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010341#if ENABLE_HUSH_TYPE
10342/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10343static int FAST_FUNC builtin_type(char **argv)
10344{
10345 int ret = EXIT_SUCCESS;
10346
10347 while (*++argv) {
10348 const char *type;
10349 char *path = NULL;
10350
10351 if (0) {} /* make conditional compile easier below */
10352 /*else if (find_alias(*argv))
10353 type = "an alias";*/
10354#if ENABLE_HUSH_FUNCTIONS
10355 else if (find_function(*argv))
10356 type = "a function";
10357#endif
10358 else if (find_builtin(*argv))
10359 type = "a shell builtin";
10360 else if ((path = find_in_path(*argv)) != NULL)
10361 type = path;
10362 else {
10363 bb_error_msg("type: %s: not found", *argv);
10364 ret = EXIT_FAILURE;
10365 continue;
10366 }
10367
10368 printf("%s is %s\n", *argv, type);
10369 free(path);
10370 }
10371
10372 return ret;
10373}
10374#endif
10375
10376#if ENABLE_HUSH_READ
10377/* Interruptibility of read builtin in bash
10378 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10379 *
10380 * Empty trap makes read ignore corresponding signal, for any signal.
10381 *
10382 * SIGINT:
10383 * - terminates non-interactive shell;
10384 * - interrupts read in interactive shell;
10385 * if it has non-empty trap:
10386 * - executes trap and returns to command prompt in interactive shell;
10387 * - executes trap and returns to read in non-interactive shell;
10388 * SIGTERM:
10389 * - is ignored (does not interrupt) read in interactive shell;
10390 * - terminates non-interactive shell;
10391 * if it has non-empty trap:
10392 * - executes trap and returns to read;
10393 * SIGHUP:
10394 * - terminates shell (regardless of interactivity);
10395 * if it has non-empty trap:
10396 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010397 * SIGCHLD from children:
10398 * - does not interrupt read regardless of interactivity:
10399 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010400 */
10401static int FAST_FUNC builtin_read(char **argv)
10402{
10403 const char *r;
10404 char *opt_n = NULL;
10405 char *opt_p = NULL;
10406 char *opt_t = NULL;
10407 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010408 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010409 const char *ifs;
10410 int read_flags;
10411
10412 /* "!": do not abort on errors.
10413 * Option string must start with "sr" to match BUILTIN_READ_xxx
10414 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010415 read_flags = getopt32(argv,
10416#if BASH_READ_D
10417 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10418#else
10419 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10420#endif
10421 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010422 if (read_flags == (uint32_t)-1)
10423 return EXIT_FAILURE;
10424 argv += optind;
10425 ifs = get_local_var_value("IFS"); /* can be NULL */
10426
10427 again:
10428 r = shell_builtin_read(set_local_var_from_halves,
10429 argv,
10430 ifs,
10431 read_flags,
10432 opt_n,
10433 opt_p,
10434 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010435 opt_u,
10436 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010437 );
10438
10439 if ((uintptr_t)r == 1 && errno == EINTR) {
10440 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010441 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010442 goto again;
10443 }
10444
10445 if ((uintptr_t)r > 1) {
10446 bb_error_msg("%s", r);
10447 r = (char*)(uintptr_t)1;
10448 }
10449
10450 return (uintptr_t)r;
10451}
10452#endif
10453
10454#if ENABLE_HUSH_UMASK
10455static int FAST_FUNC builtin_umask(char **argv)
10456{
10457 int rc;
10458 mode_t mask;
10459
10460 rc = 1;
10461 mask = umask(0);
10462 argv = skip_dash_dash(argv);
10463 if (argv[0]) {
10464 mode_t old_mask = mask;
10465
10466 /* numeric umasks are taken as-is */
10467 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10468 if (!isdigit(argv[0][0]))
10469 mask ^= 0777;
10470 mask = bb_parse_mode(argv[0], mask);
10471 if (!isdigit(argv[0][0]))
10472 mask ^= 0777;
10473 if ((unsigned)mask > 0777) {
10474 mask = old_mask;
10475 /* bash messages:
10476 * bash: umask: 'q': invalid symbolic mode operator
10477 * bash: umask: 999: octal number out of range
10478 */
10479 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10480 rc = 0;
10481 }
10482 } else {
10483 /* Mimic bash */
10484 printf("%04o\n", (unsigned) mask);
10485 /* fall through and restore mask which we set to 0 */
10486 }
10487 umask(mask);
10488
10489 return !rc; /* rc != 0 - success */
10490}
10491#endif
10492
Denys Vlasenko41ade052017-01-08 18:56:24 +010010493#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010494static void print_escaped(const char *s)
10495{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010496 if (*s == '\'')
10497 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010498 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010499 const char *p = strchrnul(s, '\'');
10500 /* print 'xxxx', possibly just '' */
10501 printf("'%.*s'", (int)(p - s), s);
10502 if (*p == '\0')
10503 break;
10504 s = p;
10505 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010506 /* s points to '; print "'''...'''" */
10507 putchar('"');
10508 do putchar('\''); while (*++s == '\'');
10509 putchar('"');
10510 } while (*s);
10511}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010512#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010513
Denys Vlasenko1e660422017-07-17 21:10:50 +020010514#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010515static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010516{
10517 do {
10518 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010519 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010520
10521 /* So far we do not check that name is valid (TODO?) */
10522
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010523 if (*name_end == '\0') {
10524 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010525
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010526 vpp = get_ptr_to_local_var(name, name_end - name);
10527 var = vpp ? *vpp : NULL;
10528
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010529 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010530 /* export -n NAME (without =VALUE) */
10531 if (var) {
10532 var->flg_export = 0;
10533 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10534 unsetenv(name);
10535 } /* else: export -n NOT_EXISTING_VAR: no-op */
10536 continue;
10537 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010538 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010539 /* export NAME (without =VALUE) */
10540 if (var) {
10541 var->flg_export = 1;
10542 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10543 putenv(var->varstr);
10544 continue;
10545 }
10546 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010547 if (flags & SETFLAG_MAKE_RO) {
10548 /* readonly NAME (without =VALUE) */
10549 if (var) {
10550 var->flg_read_only = 1;
10551 continue;
10552 }
10553 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010554# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010555 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010556 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010557 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10558 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010559 /* "local x=abc; ...; local x" - ignore second local decl */
10560 continue;
10561 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010562 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010563# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010564 /* Exporting non-existing variable.
10565 * bash does not put it in environment,
10566 * but remembers that it is exported,
10567 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010568 * We just set it to "" and export.
10569 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010570 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010571 * bash sets the value to "".
10572 */
10573 /* Or, it's "readonly NAME" (without =VALUE).
10574 * bash remembers NAME and disallows its creation
10575 * in the future.
10576 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010577 name = xasprintf("%s=", name);
10578 } else {
10579 /* (Un)exporting/making local NAME=VALUE */
10580 name = xstrdup(name);
10581 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010582 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010583 if (set_local_var(name, flags))
10584 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010585 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010586 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010587}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010588#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010589
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010590#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010591static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010592{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010593 unsigned opt_unexport;
10594
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010595#if ENABLE_HUSH_EXPORT_N
10596 /* "!": do not abort on errors */
10597 opt_unexport = getopt32(argv, "!n");
10598 if (opt_unexport == (uint32_t)-1)
10599 return EXIT_FAILURE;
10600 argv += optind;
10601#else
10602 opt_unexport = 0;
10603 argv++;
10604#endif
10605
10606 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010607 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010608 if (e) {
10609 while (*e) {
10610#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010611 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010612#else
10613 /* ash emits: export VAR='VAL'
10614 * bash: declare -x VAR="VAL"
10615 * we follow ash example */
10616 const char *s = *e++;
10617 const char *p = strchr(s, '=');
10618
10619 if (!p) /* wtf? take next variable */
10620 continue;
10621 /* export var= */
10622 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010623 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010624 putchar('\n');
10625#endif
10626 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010627 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010628 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010629 return EXIT_SUCCESS;
10630 }
10631
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010632 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010633}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010634#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010635
Denys Vlasenko295fef82009-06-03 12:47:26 +020010636#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010637static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010638{
10639 if (G.func_nest_level == 0) {
10640 bb_error_msg("%s: not in a function", argv[0]);
10641 return EXIT_FAILURE; /* bash compat */
10642 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010643 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010644 /* Since all builtins run in a nested variable level,
10645 * need to use level - 1 here. Or else the variable will be removed at once
10646 * after builtin returns.
10647 */
10648 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010649}
10650#endif
10651
Denys Vlasenko1e660422017-07-17 21:10:50 +020010652#if ENABLE_HUSH_READONLY
10653static int FAST_FUNC builtin_readonly(char **argv)
10654{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010655 argv++;
10656 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010657 /* bash: readonly [-p]: list all readonly VARs
10658 * (-p has no effect in bash)
10659 */
10660 struct variable *e;
10661 for (e = G.top_var; e; e = e->next) {
10662 if (e->flg_read_only) {
10663//TODO: quote value: readonly VAR='VAL'
10664 printf("readonly %s\n", e->varstr);
10665 }
10666 }
10667 return EXIT_SUCCESS;
10668 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010669 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010670}
10671#endif
10672
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010673#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010674/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10675static int FAST_FUNC builtin_unset(char **argv)
10676{
10677 int ret;
10678 unsigned opts;
10679
10680 /* "!": do not abort on errors */
10681 /* "+": stop at 1st non-option */
10682 opts = getopt32(argv, "!+vf");
10683 if (opts == (unsigned)-1)
10684 return EXIT_FAILURE;
10685 if (opts == 3) {
10686 bb_error_msg("unset: -v and -f are exclusive");
10687 return EXIT_FAILURE;
10688 }
10689 argv += optind;
10690
10691 ret = EXIT_SUCCESS;
10692 while (*argv) {
10693 if (!(opts & 2)) { /* not -f */
10694 if (unset_local_var(*argv)) {
10695 /* unset <nonexistent_var> doesn't fail.
10696 * Error is when one tries to unset RO var.
10697 * Message was printed by unset_local_var. */
10698 ret = EXIT_FAILURE;
10699 }
10700 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010701# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010702 else {
10703 unset_func(*argv);
10704 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010705# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010706 argv++;
10707 }
10708 return ret;
10709}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010710#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010711
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010712#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010713/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10714 * built-in 'set' handler
10715 * SUSv3 says:
10716 * set [-abCefhmnuvx] [-o option] [argument...]
10717 * set [+abCefhmnuvx] [+o option] [argument...]
10718 * set -- [argument...]
10719 * set -o
10720 * set +o
10721 * Implementations shall support the options in both their hyphen and
10722 * plus-sign forms. These options can also be specified as options to sh.
10723 * Examples:
10724 * Write out all variables and their values: set
10725 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10726 * Turn on the -x and -v options: set -xv
10727 * Unset all positional parameters: set --
10728 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10729 * Set the positional parameters to the expansion of x, even if x expands
10730 * with a leading '-' or '+': set -- $x
10731 *
10732 * So far, we only support "set -- [argument...]" and some of the short names.
10733 */
10734static int FAST_FUNC builtin_set(char **argv)
10735{
10736 int n;
10737 char **pp, **g_argv;
10738 char *arg = *++argv;
10739
10740 if (arg == NULL) {
10741 struct variable *e;
10742 for (e = G.top_var; e; e = e->next)
10743 puts(e->varstr);
10744 return EXIT_SUCCESS;
10745 }
10746
10747 do {
10748 if (strcmp(arg, "--") == 0) {
10749 ++argv;
10750 goto set_argv;
10751 }
10752 if (arg[0] != '+' && arg[0] != '-')
10753 break;
10754 for (n = 1; arg[n]; ++n) {
10755 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10756 goto error;
10757 if (arg[n] == 'o' && argv[1])
10758 argv++;
10759 }
10760 } while ((arg = *++argv) != NULL);
10761 /* Now argv[0] is 1st argument */
10762
10763 if (arg == NULL)
10764 return EXIT_SUCCESS;
10765 set_argv:
10766
10767 /* NB: G.global_argv[0] ($0) is never freed/changed */
10768 g_argv = G.global_argv;
10769 if (G.global_args_malloced) {
10770 pp = g_argv;
10771 while (*++pp)
10772 free(*pp);
10773 g_argv[1] = NULL;
10774 } else {
10775 G.global_args_malloced = 1;
10776 pp = xzalloc(sizeof(pp[0]) * 2);
10777 pp[0] = g_argv[0]; /* retain $0 */
10778 g_argv = pp;
10779 }
10780 /* This realloc's G.global_argv */
10781 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10782
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010783 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010784
10785 return EXIT_SUCCESS;
10786
10787 /* Nothing known, so abort */
10788 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010789 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010790 return EXIT_FAILURE;
10791}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010792#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010793
10794static int FAST_FUNC builtin_shift(char **argv)
10795{
10796 int n = 1;
10797 argv = skip_dash_dash(argv);
10798 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010799 n = bb_strtou(argv[0], NULL, 10);
10800 if (errno || n < 0) {
10801 /* shared string with ash.c */
10802 bb_error_msg("Illegal number: %s", argv[0]);
10803 /*
10804 * ash aborts in this case.
10805 * bash prints error message and set $? to 1.
10806 * Interestingly, for "shift 99999" bash does not
10807 * print error message, but does set $? to 1
10808 * (and does no shifting at all).
10809 */
10810 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010811 }
10812 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010813 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010814 int m = 1;
10815 while (m <= n)
10816 free(G.global_argv[m++]);
10817 }
10818 G.global_argc -= n;
10819 memmove(&G.global_argv[1], &G.global_argv[n+1],
10820 G.global_argc * sizeof(G.global_argv[0]));
10821 return EXIT_SUCCESS;
10822 }
10823 return EXIT_FAILURE;
10824}
10825
Denys Vlasenko74d40582017-08-11 01:32:46 +020010826#if ENABLE_HUSH_GETOPTS
10827static int FAST_FUNC builtin_getopts(char **argv)
10828{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010829/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10830
Denys Vlasenko74d40582017-08-11 01:32:46 +020010831TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010832If a required argument is not found, and getopts is not silent,
10833a question mark (?) is placed in VAR, OPTARG is unset, and a
10834diagnostic message is printed. If getopts is silent, then a
10835colon (:) is placed in VAR and OPTARG is set to the option
10836character found.
10837
10838Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010839
10840"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010841*/
10842 char cbuf[2];
10843 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010844 int c, n, exitcode, my_opterr;
10845 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010846
10847 optstring = *++argv;
10848 if (!optstring || !(var = *++argv)) {
10849 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10850 return EXIT_FAILURE;
10851 }
10852
Denys Vlasenko238ff982017-08-29 13:38:30 +020010853 if (argv[1])
10854 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10855 else
10856 argv = G.global_argv;
10857 cbuf[1] = '\0';
10858
10859 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010860 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010861 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010862 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010863 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010864 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010865
10866 /* getopts stops on first non-option. Add "+" to force that */
10867 /*if (optstring[0] != '+')*/ {
10868 char *s = alloca(strlen(optstring) + 2);
10869 sprintf(s, "+%s", optstring);
10870 optstring = s;
10871 }
10872
Denys Vlasenko238ff982017-08-29 13:38:30 +020010873 /* Naively, now we should just
10874 * cp = get_local_var_value("OPTIND");
10875 * optind = cp ? atoi(cp) : 0;
10876 * optarg = NULL;
10877 * opterr = my_opterr;
10878 * c = getopt(string_array_len(argv), argv, optstring);
10879 * and be done? Not so fast...
10880 * Unlike normal getopt() usage in C programs, here
10881 * each successive call will (usually) have the same argv[] CONTENTS,
10882 * but not the ADDRESSES. Worse yet, it's possible that between
10883 * invocations of "getopts", there will be calls to shell builtins
10884 * which use getopt() internally. Example:
10885 * while getopts "abc" RES -a -bc -abc de; do
10886 * unset -ff func
10887 * done
10888 * This would not work correctly: getopt() call inside "unset"
10889 * modifies internal libc state which is tracking position in
10890 * multi-option strings ("-abc"). At best, it can skip options
10891 * or return the same option infinitely. With glibc implementation
10892 * of getopt(), it would use outright invalid pointers and return
10893 * garbage even _without_ "unset" mangling internal state.
10894 *
10895 * We resort to resetting getopt() state and calling it N times,
10896 * until we get Nth result (or failure).
10897 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10898 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010899 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010900 count = 0;
10901 n = string_array_len(argv);
10902 do {
10903 optarg = NULL;
10904 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10905 c = getopt(n, argv, optstring);
10906 if (c < 0)
10907 break;
10908 count++;
10909 } while (count <= G.getopt_count);
10910
10911 /* Set OPTIND. Prevent resetting of the magic counter! */
10912 set_local_var_from_halves("OPTIND", utoa(optind));
10913 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010914 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010915
10916 /* Set OPTARG */
10917 /* Always set or unset, never left as-is, even on exit/error:
10918 * "If no option was found, or if the option that was found
10919 * does not have an option-argument, OPTARG shall be unset."
10920 */
10921 cp = optarg;
10922 if (c == '?') {
10923 /* If ":optstring" and unknown option is seen,
10924 * it is stored to OPTARG.
10925 */
10926 if (optstring[1] == ':') {
10927 cbuf[0] = optopt;
10928 cp = cbuf;
10929 }
10930 }
10931 if (cp)
10932 set_local_var_from_halves("OPTARG", cp);
10933 else
10934 unset_local_var("OPTARG");
10935
10936 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010937 exitcode = EXIT_SUCCESS;
10938 if (c < 0) { /* -1: end of options */
10939 exitcode = EXIT_FAILURE;
10940 c = '?';
10941 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010942
Denys Vlasenko238ff982017-08-29 13:38:30 +020010943 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010944 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010945 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010946
Denys Vlasenko74d40582017-08-11 01:32:46 +020010947 return exitcode;
10948}
10949#endif
10950
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010951static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010952{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010953 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010954 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010955 save_arg_t sv;
10956 char *args_need_save;
10957#if ENABLE_HUSH_FUNCTIONS
10958 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010959#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010960
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010961 argv = skip_dash_dash(argv);
10962 filename = argv[0];
10963 if (!filename) {
10964 /* bash says: "bash: .: filename argument required" */
10965 return 2; /* bash compat */
10966 }
10967 arg_path = NULL;
10968 if (!strchr(filename, '/')) {
10969 arg_path = find_in_path(filename);
10970 if (arg_path)
10971 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010972 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010973 errno = ENOENT;
10974 bb_simple_perror_msg(filename);
10975 return EXIT_FAILURE;
10976 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010977 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010978 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010979 free(arg_path);
10980 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010981 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010982 /* POSIX: non-interactive shell should abort here,
10983 * not merely fail. So far no one complained :)
10984 */
10985 return EXIT_FAILURE;
10986 }
10987
10988#if ENABLE_HUSH_FUNCTIONS
10989 sv_flg = G_flag_return_in_progress;
10990 /* "we are inside sourced file, ok to use return" */
10991 G_flag_return_in_progress = -1;
10992#endif
10993 args_need_save = argv[1]; /* used as a boolean variable */
10994 if (args_need_save)
10995 save_and_replace_G_args(&sv, argv);
10996
10997 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10998 G.last_exitcode = 0;
10999 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011000 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011001
11002 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11003 restore_G_args(&sv, argv);
11004#if ENABLE_HUSH_FUNCTIONS
11005 G_flag_return_in_progress = sv_flg;
11006#endif
11007
11008 return G.last_exitcode;
11009}
11010
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011011#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011012static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011013{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011014 int sig;
11015 char *new_cmd;
11016
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011017 if (!G_traps)
11018 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011019
11020 argv++;
11021 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011022 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011023 /* No args: print all trapped */
11024 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011025 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011026 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011027 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011028 /* note: bash adds "SIG", but only if invoked
11029 * as "bash". If called as "sh", or if set -o posix,
11030 * then it prints short signal names.
11031 * We are printing short names: */
11032 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011033 }
11034 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011035 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011036 return EXIT_SUCCESS;
11037 }
11038
11039 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011040 /* If first arg is a number: reset all specified signals */
11041 sig = bb_strtou(*argv, NULL, 10);
11042 if (errno == 0) {
11043 int ret;
11044 process_sig_list:
11045 ret = EXIT_SUCCESS;
11046 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011047 sighandler_t handler;
11048
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011049 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011050 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011051 ret = EXIT_FAILURE;
11052 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011053 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011054 continue;
11055 }
11056
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011057 free(G_traps[sig]);
11058 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011059
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011060 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011061 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011062
11063 /* There is no signal for 0 (EXIT) */
11064 if (sig == 0)
11065 continue;
11066
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011067 if (new_cmd)
11068 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11069 else
11070 /* We are removing trap handler */
11071 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011072 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011073 }
11074 return ret;
11075 }
11076
11077 if (!argv[1]) { /* no second arg */
11078 bb_error_msg("trap: invalid arguments");
11079 return EXIT_FAILURE;
11080 }
11081
11082 /* First arg is "-": reset all specified to default */
11083 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11084 /* Everything else: set arg as signal handler
11085 * (includes "" case, which ignores signal) */
11086 if (argv[0][0] == '-') {
11087 if (argv[0][1] == '\0') { /* "-" */
11088 /* new_cmd remains NULL: "reset these sigs" */
11089 goto reset_traps;
11090 }
11091 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11092 argv++;
11093 }
11094 /* else: "-something", no special meaning */
11095 }
11096 new_cmd = *argv;
11097 reset_traps:
11098 argv++;
11099 goto process_sig_list;
11100}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011101#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011102
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011103#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011104static struct pipe *parse_jobspec(const char *str)
11105{
11106 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011107 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011108
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011109 if (sscanf(str, "%%%u", &jobnum) != 1) {
11110 if (str[0] != '%'
11111 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11112 ) {
11113 bb_error_msg("bad argument '%s'", str);
11114 return NULL;
11115 }
11116 /* It is "%%", "%+" or "%" - current job */
11117 jobnum = G.last_jobid;
11118 if (jobnum == 0) {
11119 bb_error_msg("no current job");
11120 return NULL;
11121 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011122 }
11123 for (pi = G.job_list; pi; pi = pi->next) {
11124 if (pi->jobid == jobnum) {
11125 return pi;
11126 }
11127 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011128 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011129 return NULL;
11130}
11131
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011132static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11133{
11134 struct pipe *job;
11135 const char *status_string;
11136
11137 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11138 for (job = G.job_list; job; job = job->next) {
11139 if (job->alive_cmds == job->stopped_cmds)
11140 status_string = "Stopped";
11141 else
11142 status_string = "Running";
11143
11144 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11145 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011146
11147 clean_up_last_dead_job();
11148
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011149 return EXIT_SUCCESS;
11150}
11151
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011152/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011153static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011154{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011155 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011156 struct pipe *pi;
11157
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011158 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011159 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011160
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011161 /* If they gave us no args, assume they want the last backgrounded task */
11162 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011163 for (pi = G.job_list; pi; pi = pi->next) {
11164 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011165 goto found;
11166 }
11167 }
11168 bb_error_msg("%s: no current job", argv[0]);
11169 return EXIT_FAILURE;
11170 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011171
11172 pi = parse_jobspec(argv[1]);
11173 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011174 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011175 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011176 /* TODO: bash prints a string representation
11177 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011178 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011179 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011180 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011181 }
11182
11183 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011184 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11185 for (i = 0; i < pi->num_cmds; i++) {
11186 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011187 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011188 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011189
11190 i = kill(- pi->pgrp, SIGCONT);
11191 if (i < 0) {
11192 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011193 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011194 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011195 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011196 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011197 }
11198
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011199 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011200 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011201 return checkjobs_and_fg_shell(pi);
11202 }
11203 return EXIT_SUCCESS;
11204}
11205#endif
11206
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011207#if ENABLE_HUSH_KILL
11208static int FAST_FUNC builtin_kill(char **argv)
11209{
11210 int ret = 0;
11211
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011212# if ENABLE_HUSH_JOB
11213 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11214 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011215
11216 do {
11217 struct pipe *pi;
11218 char *dst;
11219 int j, n;
11220
11221 if (argv[i][0] != '%')
11222 continue;
11223 /*
11224 * "kill %N" - job kill
11225 * Converting to pgrp / pid kill
11226 */
11227 pi = parse_jobspec(argv[i]);
11228 if (!pi) {
11229 /* Eat bad jobspec */
11230 j = i;
11231 do {
11232 j++;
11233 argv[j - 1] = argv[j];
11234 } while (argv[j]);
11235 ret = 1;
11236 i--;
11237 continue;
11238 }
11239 /*
11240 * In jobs started under job control, we signal
11241 * entire process group by kill -PGRP_ID.
11242 * This happens, f.e., in interactive shell.
11243 *
11244 * Otherwise, we signal each child via
11245 * kill PID1 PID2 PID3.
11246 * Testcases:
11247 * sh -c 'sleep 1|sleep 1 & kill %1'
11248 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11249 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11250 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011251 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011252 dst = alloca(n * sizeof(int)*4);
11253 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011254 if (G_interactive_fd)
11255 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011256 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011257 struct command *cmd = &pi->cmds[j];
11258 /* Skip exited members of the job */
11259 if (cmd->pid == 0)
11260 continue;
11261 /*
11262 * kill_main has matching code to expect
11263 * leading space. Needed to not confuse
11264 * negative pids with "kill -SIGNAL_NO" syntax
11265 */
11266 dst += sprintf(dst, " %u", (int)cmd->pid);
11267 }
11268 *dst = '\0';
11269 } while (argv[++i]);
11270 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011271# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011272
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011273 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011274 ret = run_applet_main(argv, kill_main);
11275 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011276 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011277 return ret;
11278}
11279#endif
11280
11281#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011282/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011283#if !ENABLE_HUSH_JOB
11284# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11285#endif
11286static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011287{
11288 int ret = 0;
11289 for (;;) {
11290 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011291 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011292
Denys Vlasenko830ea352016-11-08 04:59:11 +010011293 if (!sigisemptyset(&G.pending_set))
11294 goto check_sig;
11295
Denys Vlasenko7e675362016-10-28 21:57:31 +020011296 /* waitpid is not interruptible by SA_RESTARTed
11297 * signals which we use. Thus, this ugly dance:
11298 */
11299
11300 /* Make sure possible SIGCHLD is stored in kernel's
11301 * pending signal mask before we call waitpid.
11302 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011303 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011304 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011305 sigfillset(&oldset); /* block all signals, remember old set */
11306 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011307
11308 if (!sigisemptyset(&G.pending_set)) {
11309 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011310 goto restore;
11311 }
11312
11313 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011314/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011315 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011316 debug_printf_exec("checkjobs:%d\n", ret);
11317#if ENABLE_HUSH_JOB
11318 if (waitfor_pipe) {
11319 int rcode = job_exited_or_stopped(waitfor_pipe);
11320 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11321 if (rcode >= 0) {
11322 ret = rcode;
11323 sigprocmask(SIG_SETMASK, &oldset, NULL);
11324 break;
11325 }
11326 }
11327#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011328 /* if ECHILD, there are no children (ret is -1 or 0) */
11329 /* if ret == 0, no children changed state */
11330 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011331 if (errno == ECHILD || ret) {
11332 ret--;
11333 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011334 ret = 0;
11335 sigprocmask(SIG_SETMASK, &oldset, NULL);
11336 break;
11337 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011338 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011339 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11340 /* Note: sigsuspend invokes signal handler */
11341 sigsuspend(&oldset);
11342 restore:
11343 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011344 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011345 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011346 sig = check_and_run_traps();
11347 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011348 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011349 ret = 128 + sig;
11350 break;
11351 }
11352 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11353 }
11354 return ret;
11355}
11356
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011357static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011358{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011359 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011360 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011361
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011362 argv = skip_dash_dash(argv);
11363 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011364 /* Don't care about wait results */
11365 /* Note 1: must wait until there are no more children */
11366 /* Note 2: must be interruptible */
11367 /* Examples:
11368 * $ sleep 3 & sleep 6 & wait
11369 * [1] 30934 sleep 3
11370 * [2] 30935 sleep 6
11371 * [1] Done sleep 3
11372 * [2] Done sleep 6
11373 * $ sleep 3 & sleep 6 & wait
11374 * [1] 30936 sleep 3
11375 * [2] 30937 sleep 6
11376 * [1] Done sleep 3
11377 * ^C <-- after ~4 sec from keyboard
11378 * $
11379 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011380 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011381 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011382
Denys Vlasenko7e675362016-10-28 21:57:31 +020011383 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011384 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011385 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011386#if ENABLE_HUSH_JOB
11387 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011388 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011389 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011390 wait_pipe = parse_jobspec(*argv);
11391 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011392 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011393 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011394 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011395 } else {
11396 /* waiting on "last dead job" removes it */
11397 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011398 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011399 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011400 /* else: parse_jobspec() already emitted error msg */
11401 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011402 }
11403#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011404 /* mimic bash message */
11405 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011406 ret = EXIT_FAILURE;
11407 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011408 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011409
Denys Vlasenko7e675362016-10-28 21:57:31 +020011410 /* Do we have such child? */
11411 ret = waitpid(pid, &status, WNOHANG);
11412 if (ret < 0) {
11413 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011414 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011415 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011416 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011417 /* "wait $!" but last bg task has already exited. Try:
11418 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11419 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011420 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011421 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011422 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011423 } else {
11424 /* Example: "wait 1". mimic bash message */
11425 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011426 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011427 } else {
11428 /* ??? */
11429 bb_perror_msg("wait %s", *argv);
11430 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011431 continue; /* bash checks all argv[] */
11432 }
11433 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011434 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011435 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011436 } else {
11437 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011438 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011439 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011440 if (WIFSIGNALED(status))
11441 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011442 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011443 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011444
11445 return ret;
11446}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011447#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011448
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011449#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11450static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11451{
11452 if (argv[1]) {
11453 def = bb_strtou(argv[1], NULL, 10);
11454 if (errno || def < def_min || argv[2]) {
11455 bb_error_msg("%s: bad arguments", argv[0]);
11456 def = UINT_MAX;
11457 }
11458 }
11459 return def;
11460}
11461#endif
11462
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011463#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011464static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011465{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011466 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011467 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011468 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011469 /* if we came from builtin_continue(), need to undo "= 1" */
11470 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011471 return EXIT_SUCCESS; /* bash compat */
11472 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011473 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011474
11475 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11476 if (depth == UINT_MAX)
11477 G.flag_break_continue = BC_BREAK;
11478 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011479 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011480
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011481 return EXIT_SUCCESS;
11482}
11483
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011484static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011485{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011486 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11487 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011488}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011489#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011490
11491#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011492static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011493{
11494 int rc;
11495
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011496 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011497 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11498 return EXIT_FAILURE; /* bash compat */
11499 }
11500
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011501 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011502
11503 /* bash:
11504 * out of range: wraps around at 256, does not error out
11505 * non-numeric param:
11506 * f() { false; return qwe; }; f; echo $?
11507 * bash: return: qwe: numeric argument required <== we do this
11508 * 255 <== we also do this
11509 */
11510 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11511 return rc;
11512}
11513#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011514
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011515#if ENABLE_HUSH_TIMES
11516static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11517{
11518 static const uint8_t times_tbl[] ALIGN1 = {
11519 ' ', offsetof(struct tms, tms_utime),
11520 '\n', offsetof(struct tms, tms_stime),
11521 ' ', offsetof(struct tms, tms_cutime),
11522 '\n', offsetof(struct tms, tms_cstime),
11523 0
11524 };
11525 const uint8_t *p;
11526 unsigned clk_tck;
11527 struct tms buf;
11528
11529 clk_tck = bb_clk_tck();
11530
11531 times(&buf);
11532 p = times_tbl;
11533 do {
11534 unsigned sec, frac;
11535 unsigned long t;
11536 t = *(clock_t *)(((char *) &buf) + p[1]);
11537 sec = t / clk_tck;
11538 frac = t % clk_tck;
11539 printf("%um%u.%03us%c",
11540 sec / 60, sec % 60,
11541 (frac * 1000) / clk_tck,
11542 p[0]);
11543 p += 2;
11544 } while (*p);
11545
11546 return EXIT_SUCCESS;
11547}
11548#endif
11549
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011550#if ENABLE_HUSH_MEMLEAK
11551static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11552{
11553 void *p;
11554 unsigned long l;
11555
11556# ifdef M_TRIM_THRESHOLD
11557 /* Optional. Reduces probability of false positives */
11558 malloc_trim(0);
11559# endif
11560 /* Crude attempt to find where "free memory" starts,
11561 * sans fragmentation. */
11562 p = malloc(240);
11563 l = (unsigned long)p;
11564 free(p);
11565 p = malloc(3400);
11566 if (l < (unsigned long)p) l = (unsigned long)p;
11567 free(p);
11568
11569
11570# if 0 /* debug */
11571 {
11572 struct mallinfo mi = mallinfo();
11573 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11574 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11575 }
11576# endif
11577
11578 if (!G.memleak_value)
11579 G.memleak_value = l;
11580
11581 l -= G.memleak_value;
11582 if ((long)l < 0)
11583 l = 0;
11584 l /= 1024;
11585 if (l > 127)
11586 l = 127;
11587
11588 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11589 return l;
11590}
11591#endif