blob: 559595d2e4b248d271585c4697b28a03b6219e7f [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * TODO:
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//config: hush is a small shell. It handles the normal flow control
100//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101//config: case/esac. Redirections, here documents, $((arithmetic))
102//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//config:config HUSH_BASH_SOURCE_CURDIR
127//config: bool "'source' and '.' builtins search current directory after $PATH"
128//config: default n # do not encourage non-standard behavior
129//config: depends on HUSH_BASH_COMPAT
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//config: Enable interactive mode (prompt and command editing).
139//config: Without this, hush simply reads and executes commands
140//config: from stdin just like a shell script from a file.
141//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154//config: command (not entire shell), fg/bg builtins work. Without this option,
155//config: "cmd &" still works by simply spawning a process and immediately
156//config: prompting for next command (or executing next command in a script),
157//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
360#ifndef F_DUPFD_CLOEXEC
361# define F_DUPFD_CLOEXEC F_DUPFD
362#endif
363#ifndef PIPE_BUF
364# define PIPE_BUF 4096 /* amount of buffering in a pipe */
365#endif
366
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000367
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100368/* So far, all bash compat is controlled by one config option */
369/* Separate defines document which part of code implements what */
370#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
371#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100372#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
373#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200374#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200375#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100376
377
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200378/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000379#define LEAK_HUNTING 0
380#define BUILD_AS_NOMMU 0
381/* Enable/disable sanity checks. Ok to enable in production,
382 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
383 * Keeping 1 for now even in released versions.
384 */
385#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200386/* Slightly bigger (+200 bytes), but faster hush.
387 * So far it only enables a trick with counting SIGCHLDs and forks,
388 * which allows us to do fewer waitpid's.
389 * (we can detect a case where neither forks were done nor SIGCHLDs happened
390 * and therefore waitpid will return the same result as last time)
391 */
392#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200393/* TODO: implement simplified code for users which do not need ${var%...} ops
394 * So far ${var%...} ops are always enabled:
395 */
396#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000397
398
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000399#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000400# undef BB_MMU
401# undef USE_FOR_NOMMU
402# undef USE_FOR_MMU
403# define BB_MMU 0
404# define USE_FOR_NOMMU(...) __VA_ARGS__
405# define USE_FOR_MMU(...)
406#endif
407
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200408#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100409#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000410/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000411# undef CONFIG_FEATURE_SH_STANDALONE
412# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000413# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100414# undef IF_NOT_FEATURE_SH_STANDALONE
415# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# define IF_FEATURE_SH_STANDALONE(...)
417# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000418#endif
419
Denis Vlasenko05743d72008-02-10 12:10:08 +0000420#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000421# undef ENABLE_FEATURE_EDITING
422# define ENABLE_FEATURE_EDITING 0
423# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
424# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200425# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
426# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000427#endif
428
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000429/* Do we support ANY keywords? */
430#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000431# define HAS_KEYWORDS 1
432# define IF_HAS_KEYWORDS(...) __VA_ARGS__
433# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000434#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000435# define HAS_KEYWORDS 0
436# define IF_HAS_KEYWORDS(...)
437# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000438#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000439
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000440/* If you comment out one of these below, it will be #defined later
441 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000442#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000443/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000444#define debug_printf_parse(...) do {} while (0)
445#define debug_print_tree(a, b) do {} while (0)
446#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000447#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000448#define debug_printf_jobs(...) do {} while (0)
449#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200450#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000451#define debug_printf_glob(...) do {} while (0)
Denys Vlasenko2db74612017-07-07 22:07:28 +0200452#define debug_printf_redir(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000453#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000454#define debug_printf_subst(...) do {} while (0)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200455#define debug_printf_prompt(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000456#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000457
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000458#define ERR_PTR ((void*)(long)1)
459
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100460#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000461
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200462#define _SPECIAL_VARS_STR "_*@$!?#"
463#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
464#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100465#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200466/* Support / and // replace ops */
467/* Note that // is stored as \ in "encoded" string representation */
468# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
469# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
470# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
471#else
472# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
473# define VAR_SUBST_OPS "%#:-=+?"
474# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
475#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200476
Denys Vlasenko932b9972018-01-11 12:39:48 +0100477#define SPECIAL_VAR_SYMBOL_STR "\3"
478#define SPECIAL_VAR_SYMBOL 3
479/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
480#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000481
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200482struct variable;
483
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000484static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
485
486/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000487 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000488 */
489#if !BB_MMU
490typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200491 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000492 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000493 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000494} nommu_save_t;
495#endif
496
Denys Vlasenko9b782552010-09-08 13:33:26 +0200497enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000498 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000499#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000500 RES_IF ,
501 RES_THEN ,
502 RES_ELIF ,
503 RES_ELSE ,
504 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000505#endif
506#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000507 RES_FOR ,
508 RES_WHILE ,
509 RES_UNTIL ,
510 RES_DO ,
511 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000512#endif
513#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000514 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000515#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000516#if ENABLE_HUSH_CASE
517 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200518 /* three pseudo-keywords support contrived "case" syntax: */
519 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
520 RES_MATCH , /* "word)" */
521 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000522 RES_ESAC ,
523#endif
524 RES_XXXX ,
525 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200526};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000527
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000528typedef struct o_string {
529 char *data;
530 int length; /* position where data is appended */
531 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200532 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000533 /* At least some part of the string was inside '' or "",
534 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200535 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000536 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200537 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000538} o_string;
539enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200540 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
541 EXP_FLAG_GLOB = 0x2,
542 /* Protect newly added chars against globbing
543 * by prepending \ to *, ?, [, \ */
544 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
545};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000546/* Used for initialization: o_string foo = NULL_O_STRING; */
547#define NULL_O_STRING { NULL }
548
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200549#ifndef debug_printf_parse
550static const char *const assignment_flag[] = {
551 "MAYBE_ASSIGNMENT",
552 "DEFINITELY_ASSIGNMENT",
553 "NOT_ASSIGNMENT",
554 "WORD_IS_KEYWORD",
555};
556#endif
557
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000558typedef struct in_str {
559 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200560 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200561 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000562 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000564
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200565/* The descrip member of this structure is only used to make
566 * debugging output pretty */
567static const struct {
568 int mode;
569 signed char default_fd;
570 char descrip[3];
571} redir_table[] = {
572 { O_RDONLY, 0, "<" },
573 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
574 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
575 { O_CREAT|O_RDWR, 1, "<>" },
576 { O_RDONLY, 0, "<<" },
577/* Should not be needed. Bogus default_fd helps in debugging */
578/* { O_RDONLY, 77, "<<" }, */
579};
580
Eric Andersen25f27032001-04-26 23:22:31 +0000581struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000582 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000583 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000584 int rd_fd; /* fd to redirect */
585 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
586 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000587 smallint rd_type; /* (enum redir_type) */
588 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000589 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200590 * bit 0: do we need to trim leading tabs?
591 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000592 */
Eric Andersen25f27032001-04-26 23:22:31 +0000593};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000594typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200595 REDIRECT_INPUT = 0,
596 REDIRECT_OVERWRITE = 1,
597 REDIRECT_APPEND = 2,
598 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000599 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200600 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000601
602 REDIRFD_CLOSE = -3,
603 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000604 REDIRFD_TO_FILE = -1,
605 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000606
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000607 HEREDOC_SKIPTABS = 1,
608 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000609} redir_type;
610
Eric Andersen25f27032001-04-26 23:22:31 +0000611
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000612struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000613 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200614 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100615#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100616 unsigned lineno;
617#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200618 smallint cmd_type; /* CMD_xxx */
619#define CMD_NORMAL 0
620#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200621#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
622/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
623 * "export v=t*"
624 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200625# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000626#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200627#if ENABLE_HUSH_FUNCTIONS
628# define CMD_FUNCDEF 3
629#endif
630
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100631 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200632 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
633 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000634#if !BB_MMU
635 char *group_as_string;
636#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000637#if ENABLE_HUSH_FUNCTIONS
638 struct function *child_func;
639/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200640 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000641 * When we execute "f1() {a;}" cmd, we create new function and clear
642 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200643 * When we execute "f1() {b;}", we notice that f1 exists,
644 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000645 * we put those fields back into cmd->xxx
646 * (struct function has ->parent_cmd ptr to facilitate that).
647 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
648 * Without this trick, loop would execute a;b;b;b;...
649 * instead of correct sequence a;b;a;b;...
650 * When command is freed, it severs the link
651 * (sets ->child_func->parent_cmd to NULL).
652 */
653#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000654 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000655/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
656 * and on execution these are substituted with their values.
657 * Substitution can make _several_ words out of one argv[n]!
658 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000659 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000660 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000661 struct redir_struct *redirects; /* I/O redirections */
662};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000663/* Is there anything in this command at all? */
664#define IS_NULL_CMD(cmd) \
665 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
666
Eric Andersen25f27032001-04-26 23:22:31 +0000667struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000668 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000669 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000670 int alive_cmds; /* number of commands running (not exited) */
671 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000672#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100673 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000674 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000675 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000676#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000677 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000678 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000679 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
680 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000681};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000682typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100683 PIPE_SEQ = 0,
684 PIPE_AND = 1,
685 PIPE_OR = 2,
686 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000687} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000688/* Is there anything in this pipe at all? */
689#define IS_NULL_PIPE(pi) \
690 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000691
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000692/* This holds pointers to the various results of parsing */
693struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000694 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000695 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000696 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000697 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000698 /* last command in pipe (being constructed right now) */
699 struct command *command;
700 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000701 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200702 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000703#if !BB_MMU
704 o_string as_string;
705#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200706 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000707#if HAS_KEYWORDS
708 smallint ctx_res_w;
709 smallint ctx_inverted; /* "! cmd | cmd" */
710#if ENABLE_HUSH_CASE
711 smallint ctx_dsemicolon; /* ";;" seen */
712#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000713 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
714 int old_flag;
715 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000716 * example: "if pipe1; pipe2; then pipe3; fi"
717 * when we see "if" or "then", we malloc and copy current context,
718 * and make ->stack point to it. then we parse pipeN.
719 * when closing "then" / fi" / whatever is found,
720 * we move list_head into ->stack->command->group,
721 * copy ->stack into current context, and delete ->stack.
722 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000723 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000724 struct parse_context *stack;
725#endif
726};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200727enum {
728 MAYBE_ASSIGNMENT = 0,
729 DEFINITELY_ASSIGNMENT = 1,
730 NOT_ASSIGNMENT = 2,
731 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
732 WORD_IS_KEYWORD = 3,
733};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000734
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000735/* On program start, environ points to initial environment.
736 * putenv adds new pointers into it, unsetenv removes them.
737 * Neither of these (de)allocates the strings.
738 * setenv allocates new strings in malloc space and does putenv,
739 * and thus setenv is unusable (leaky) for shell's purposes */
740#define setenv(...) setenv_is_leaky_dont_use()
741struct variable {
742 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000743 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000744 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200745 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000746 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000747 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000748};
749
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000750enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000751 BC_BREAK = 1,
752 BC_CONTINUE = 2,
753};
754
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000755#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000756struct function {
757 struct function *next;
758 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000759 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000760 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200761# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000762 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200763# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000764};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000765#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000766
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000767
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100768/* set -/+o OPT support. (TODO: make it optional)
769 * bash supports the following opts:
770 * allexport off
771 * braceexpand on
772 * emacs on
773 * errexit off
774 * errtrace off
775 * functrace off
776 * hashall on
777 * histexpand off
778 * history on
779 * ignoreeof off
780 * interactive-comments on
781 * keyword off
782 * monitor on
783 * noclobber off
784 * noexec off
785 * noglob off
786 * nolog off
787 * notify off
788 * nounset off
789 * onecmd off
790 * physical off
791 * pipefail off
792 * posix off
793 * privileged off
794 * verbose off
795 * vi off
796 * xtrace off
797 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800798static const char o_opt_strings[] ALIGN1 =
799 "pipefail\0"
800 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200801 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800802#if ENABLE_HUSH_MODE_X
803 "xtrace\0"
804#endif
805 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100806enum {
807 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800808 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200809 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800810#if ENABLE_HUSH_MODE_X
811 OPT_O_XTRACE,
812#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100813 NUM_OPT_O
814};
815
816
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200817struct FILE_list {
818 struct FILE_list *next;
819 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200820 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200821};
822
823
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000824/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000825/* Sorted roughly by size (smaller offsets == smaller code) */
826struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000827 /* interactive_fd != 0 means we are an interactive shell.
828 * If we are, then saved_tty_pgrp can also be != 0, meaning
829 * that controlling tty is available. With saved_tty_pgrp == 0,
830 * job control still works, but terminal signals
831 * (^C, ^Z, ^Y, ^\) won't work at all, and background
832 * process groups can only be created with "cmd &".
833 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
834 * to give tty to the foreground process group,
835 * and will take it back when the group is stopped (^Z)
836 * or killed (^C).
837 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000838#if ENABLE_HUSH_INTERACTIVE
839 /* 'interactive_fd' is a fd# open to ctty, if we have one
840 * _AND_ if we decided to act interactively */
841 int interactive_fd;
842 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200843 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000844# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000845#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000846# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000847#endif
848#if ENABLE_FEATURE_EDITING
849 line_input_t *line_input_state;
850#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000851 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200852 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000853 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200854#if ENABLE_HUSH_RANDOM_SUPPORT
855 random_t random_gen;
856#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000857#if ENABLE_HUSH_JOB
858 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100859 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000860 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000861 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400862# define G_saved_tty_pgrp (G.saved_tty_pgrp)
863#else
864# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000865#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200866 /* How deeply are we in context where "set -e" is ignored */
867 int errexit_depth;
868 /* "set -e" rules (do we follow them correctly?):
869 * Exit if pipe, list, or compound command exits with a non-zero status.
870 * Shell does not exit if failed command is part of condition in
871 * if/while, part of && or || list except the last command, any command
872 * in a pipe but the last, or if the command's return value is being
873 * inverted with !. If a compound command other than a subshell returns a
874 * non-zero status because a command failed while -e was being ignored, the
875 * shell does not exit. A trap on ERR, if set, is executed before the shell
876 * exits [ERR is a bashism].
877 *
878 * If a compound command or function executes in a context where -e is
879 * ignored, none of the commands executed within are affected by the -e
880 * setting. If a compound command or function sets -e while executing in a
881 * context where -e is ignored, that setting does not have any effect until
882 * the compound command or the command containing the function call completes.
883 */
884
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100885 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100886#if ENABLE_HUSH_MODE_X
887# define G_x_mode (G.o_opt[OPT_O_XTRACE])
888#else
889# define G_x_mode 0
890#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200891#if ENABLE_HUSH_INTERACTIVE
892 smallint promptmode; /* 0: PS1, 1: PS2 */
893#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000894 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000895#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000896 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000897#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000898#if ENABLE_HUSH_FUNCTIONS
899 /* 0: outside of a function (or sourced file)
900 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000901 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000902 */
903 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200904# define G_flag_return_in_progress (G.flag_return_in_progress)
905#else
906# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000907#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000908 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200909 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000910 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200911 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200912 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100913#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000914 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000915 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100916# define G_global_args_malloced (G.global_args_malloced)
917#else
918# define G_global_args_malloced 0
919#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000920 /* how many non-NULL argv's we have. NB: $# + 1 */
921 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000922 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000923#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000924 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000925#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000926#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000927 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000928 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000929#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200930#if ENABLE_HUSH_GETOPTS
931 unsigned getopt_count;
932#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000933 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200934 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000935 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200936 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200937 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200938 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200939 unsigned var_nest_level;
940#if ENABLE_HUSH_FUNCTIONS
941# if ENABLE_HUSH_LOCAL
942 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200943# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200944 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000945#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000946 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200947#if ENABLE_HUSH_FAST
948 unsigned count_SIGCHLD;
949 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200950 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200951#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100952#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100953 unsigned lineno;
954 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100955#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200956 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200957 /* Which signals have non-DFL handler (even with no traps set)?
958 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200959 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200960 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200961 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200962 * Other than these two times, never modified.
963 */
964 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200965#if ENABLE_HUSH_JOB
966 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100967# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200968#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200969# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200970#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100971#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000972 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100973# define G_traps G.traps
974#else
975# define G_traps ((char**)NULL)
976#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200977 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100978#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000979 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100980#endif
981#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000982 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000983#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200984 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200985#if ENABLE_FEATURE_EDITING
986 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
987#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000988};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000989#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000990/* Not #defining name to G.name - this quickly gets unwieldy
991 * (too many defines). Also, I actually prefer to see when a variable
992 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000993#define INIT_G() do { \
994 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200995 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
996 sigfillset(&G.sa.sa_mask); \
997 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000998} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000999
1000
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001001/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001002static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001003#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001004static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001005#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001006static int builtin_eval(char **argv) FAST_FUNC;
1007static int builtin_exec(char **argv) FAST_FUNC;
1008static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001009#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001010static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001011#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001012#if ENABLE_HUSH_READONLY
1013static int builtin_readonly(char **argv) FAST_FUNC;
1014#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001015#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001016static int builtin_fg_bg(char **argv) FAST_FUNC;
1017static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001018#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001019#if ENABLE_HUSH_GETOPTS
1020static int builtin_getopts(char **argv) FAST_FUNC;
1021#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001022#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001023static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001024#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001025#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001026static int builtin_history(char **argv) FAST_FUNC;
1027#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001028#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001029static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001030#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001031#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001032static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001033#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001034#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001035static int builtin_printf(char **argv) FAST_FUNC;
1036#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001038#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001039static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001040#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001041#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001042static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001043#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001044static int builtin_shift(char **argv) FAST_FUNC;
1045static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001046#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001047static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001048#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001049#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001050static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001051#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001052#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001053static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001054#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001055#if ENABLE_HUSH_TIMES
1056static int builtin_times(char **argv) FAST_FUNC;
1057#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001058static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001059#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001060static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001061#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001062#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001063static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001064#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001065#if ENABLE_HUSH_KILL
1066static int builtin_kill(char **argv) FAST_FUNC;
1067#endif
1068#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001069static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001070#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001071#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001072static int builtin_break(char **argv) FAST_FUNC;
1073static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001074#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001075#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001076static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001077#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001078
1079/* Table of built-in functions. They can be forked or not, depending on
1080 * context: within pipes, they fork. As simple commands, they do not.
1081 * When used in non-forking context, they can change global variables
1082 * in the parent shell process. If forked, of course they cannot.
1083 * For example, 'unset foo | whatever' will parse and run, but foo will
1084 * still be set at the end. */
1085struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001086 const char *b_cmd;
1087 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001088#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001089 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001090# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001091#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001092# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001093#endif
1094};
1095
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001096static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001097 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001098 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001099#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001100 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001101#endif
1102#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001103 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001104#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001105 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001106#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001107 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001108#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001109 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1110 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001111 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001112#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001113 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001114#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001115#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001116 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001117#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001118#if ENABLE_HUSH_GETOPTS
1119 BLTIN("getopts" , builtin_getopts , NULL),
1120#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001122 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001123#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001124#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001125 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001126#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001127#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001128 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001129#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001130#if ENABLE_HUSH_KILL
1131 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1132#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001133#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001134 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001135#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001136#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001137 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001138#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001139#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001140 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001141#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001142#if ENABLE_HUSH_READONLY
1143 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1144#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001145#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001146 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001147#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001148#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001149 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001150#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001151 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001152#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001153 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001154#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001155#if ENABLE_HUSH_TIMES
1156 BLTIN("times" , builtin_times , NULL),
1157#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001158#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001159 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001160#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001161 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001162#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001163 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001164#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001165#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001166 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001167#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001168#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001169 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001170#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001171#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001172 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001173#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001174#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001175 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001176#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001177};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001178/* These builtins won't be used if we are on NOMMU and need to re-exec
1179 * (it's cheaper to run an external program in this case):
1180 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001181static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001182#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001183 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001184#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001185#if BASH_TEST2
1186 BLTIN("[[" , builtin_test , NULL),
1187#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001188#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001189 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001190#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001191#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001192 BLTIN("printf" , builtin_printf , NULL),
1193#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001194 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001195#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001196 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001197#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001198};
1199
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001200
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001201/* Debug printouts.
1202 */
1203#if HUSH_DEBUG
1204/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001205# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001206# define debug_enter() (G.debug_indent++)
1207# define debug_leave() (G.debug_indent--)
1208#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001209# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001210# define debug_enter() ((void)0)
1211# define debug_leave() ((void)0)
1212#endif
1213
1214#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001215# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001216#endif
1217
1218#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001219# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001220#endif
1221
1222#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001223#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001224#endif
1225
1226#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001227# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001228#endif
1229
1230#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001231# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001232# define DEBUG_JOBS 1
1233#else
1234# define DEBUG_JOBS 0
1235#endif
1236
1237#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001238# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001239# define DEBUG_EXPAND 1
1240#else
1241# define DEBUG_EXPAND 0
1242#endif
1243
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001244#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001245# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001246#endif
1247
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001248#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001249# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001250# define DEBUG_GLOB 1
1251#else
1252# define DEBUG_GLOB 0
1253#endif
1254
Denys Vlasenko2db74612017-07-07 22:07:28 +02001255#ifndef debug_printf_redir
1256# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1257#endif
1258
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001259#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001260# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001261#endif
1262
1263#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001264# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001265#endif
1266
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001267#ifndef debug_printf_prompt
1268# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1269#endif
1270
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001271#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001272# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001273# define DEBUG_CLEAN 1
1274#else
1275# define DEBUG_CLEAN 0
1276#endif
1277
1278#if DEBUG_EXPAND
1279static void debug_print_strings(const char *prefix, char **vv)
1280{
1281 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001282 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001283 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001284 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001285}
1286#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001287# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001288#endif
1289
1290
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001291/* Leak hunting. Use hush_leaktool.sh for post-processing.
1292 */
1293#if LEAK_HUNTING
1294static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001295{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001296 void *ptr = xmalloc((size + 0xff) & ~0xff);
1297 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1298 return ptr;
1299}
1300static void *xxrealloc(int lineno, void *ptr, size_t size)
1301{
1302 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1303 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1304 return ptr;
1305}
1306static char *xxstrdup(int lineno, const char *str)
1307{
1308 char *ptr = xstrdup(str);
1309 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1310 return ptr;
1311}
1312static void xxfree(void *ptr)
1313{
1314 fdprintf(2, "free %p\n", ptr);
1315 free(ptr);
1316}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001317# define xmalloc(s) xxmalloc(__LINE__, s)
1318# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1319# define xstrdup(s) xxstrdup(__LINE__, s)
1320# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001321#endif
1322
1323
1324/* Syntax and runtime errors. They always abort scripts.
1325 * In interactive use they usually discard unparsed and/or unexecuted commands
1326 * and return to the prompt.
1327 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1328 */
1329#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001330# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001331# define syntax_error(lineno, msg) syntax_error(msg)
1332# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1333# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1334# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1335# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001336#endif
1337
Denys Vlasenko39701202017-08-02 19:44:05 +02001338static void die_if_script(void)
1339{
1340 if (!G_interactive_fd) {
1341 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1342 xfunc_error_retval = G.last_exitcode;
1343 xfunc_die();
1344 }
1345}
1346
1347static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001348{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001349 va_list p;
1350
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001351#if HUSH_DEBUG >= 2
1352 bb_error_msg("hush.c:%u", lineno);
1353#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001354 va_start(p, fmt);
1355 bb_verror_msg(fmt, p, NULL);
1356 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001357 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001358}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001359
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001360static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001361{
1362 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001363 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001364 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001365 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001366 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001367}
1368
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001369static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001370{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001371 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001372 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001373}
1374
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001375static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001376{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001377 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001378//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1379// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001380}
1381
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001382static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001383{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001384 char msg[2] = { ch, '\0' };
1385 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001386}
1387
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001388static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001389{
1390 char msg[2];
1391 msg[0] = ch;
1392 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001393#if HUSH_DEBUG >= 2
1394 bb_error_msg("hush.c:%u", lineno);
1395#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001396 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001397 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001398}
1399
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001400#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001401# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001402# undef syntax_error
1403# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001404# undef syntax_error_unterm_ch
1405# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001406# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001407#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001408# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001409# define syntax_error(msg) syntax_error(__LINE__, msg)
1410# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1411# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1412# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1413# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001414#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001415
Denis Vlasenko552433b2009-04-04 19:29:21 +00001416
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001417#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001418static void cmdedit_update_prompt(void);
1419#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001420# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001421#endif
1422
1423
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001424/* Utility functions
1425 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001426/* Replace each \x with x in place, return ptr past NUL. */
1427static char *unbackslash(char *src)
1428{
Denys Vlasenko71885402009-09-24 01:44:13 +02001429 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001430 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001431 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001432 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001433 if (*src != '\0') {
1434 /* \x -> x */
1435 *dst++ = *src++;
1436 continue;
1437 }
1438 /* else: "\<nul>". Do not delete this backslash.
1439 * Testcase: eval 'echo ok\'
1440 */
1441 *dst++ = '\\';
1442 /* fallthrough */
1443 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001444 if ((*dst++ = *src++) == '\0')
1445 break;
1446 }
1447 return dst;
1448}
1449
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001450static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001451{
1452 int i;
1453 unsigned count1;
1454 unsigned count2;
1455 char **v;
1456
1457 v = strings;
1458 count1 = 0;
1459 if (v) {
1460 while (*v) {
1461 count1++;
1462 v++;
1463 }
1464 }
1465 count2 = 0;
1466 v = add;
1467 while (*v) {
1468 count2++;
1469 v++;
1470 }
1471 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1472 v[count1 + count2] = NULL;
1473 i = count2;
1474 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001475 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001476 return v;
1477}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001478#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001479static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1480{
1481 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1482 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1483 return ptr;
1484}
1485#define add_strings_to_strings(strings, add, need_to_dup) \
1486 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1487#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001488
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001489/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001490static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001491{
1492 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001493 v[0] = add;
1494 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001495 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001496}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001497#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001498static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1499{
1500 char **ptr = add_string_to_strings(strings, add);
1501 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1502 return ptr;
1503}
1504#define add_string_to_strings(strings, add) \
1505 xx_add_string_to_strings(__LINE__, strings, add)
1506#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001507
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001508static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001509{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001510 char **v;
1511
1512 if (!strings)
1513 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001514 v = strings;
1515 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001516 free(*v);
1517 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001518 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001519 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001520}
1521
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001522static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001523{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001524 int newfd;
1525 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001526 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1527 if (newfd >= 0) {
1528 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1529 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1530 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001531 if (errno == EBUSY)
1532 goto repeat;
1533 if (errno == EINTR)
1534 goto repeat;
1535 }
1536 return newfd;
1537}
1538
Denys Vlasenko657e9002017-07-30 23:34:04 +02001539static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001540{
1541 int newfd;
1542 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001543 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001544 if (newfd < 0) {
1545 if (errno == EBUSY)
1546 goto repeat;
1547 if (errno == EINTR)
1548 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001549 /* fd was not open? */
1550 if (errno == EBADF)
1551 return fd;
1552 xfunc_die();
1553 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001554 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1555 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001556 close(fd);
1557 return newfd;
1558}
1559
1560
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001561/* Manipulating the list of open FILEs */
1562static FILE *remember_FILE(FILE *fp)
1563{
1564 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001565 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001566 n->next = G.FILE_list;
1567 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001568 n->fp = fp;
1569 n->fd = fileno(fp);
1570 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001571 }
1572 return fp;
1573}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001574static void fclose_and_forget(FILE *fp)
1575{
1576 struct FILE_list **pp = &G.FILE_list;
1577 while (*pp) {
1578 struct FILE_list *cur = *pp;
1579 if (cur->fp == fp) {
1580 *pp = cur->next;
1581 free(cur);
1582 break;
1583 }
1584 pp = &cur->next;
1585 }
1586 fclose(fp);
1587}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001588static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001589{
1590 struct FILE_list *fl = G.FILE_list;
1591 while (fl) {
1592 if (fd == fl->fd) {
1593 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001594 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001595 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001596 return 1;
1597 }
1598 fl = fl->next;
1599 }
1600 return 0;
1601}
1602static void restore_redirected_FILEs(void)
1603{
1604 struct FILE_list *fl = G.FILE_list;
1605 while (fl) {
1606 int should_be = fileno(fl->fp);
1607 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001608 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001609 xmove_fd(fl->fd, should_be);
1610 fl->fd = should_be;
1611 }
1612 fl = fl->next;
1613 }
1614}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001615#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001616static void close_all_FILE_list(void)
1617{
1618 struct FILE_list *fl = G.FILE_list;
1619 while (fl) {
1620 /* fclose would also free FILE object.
1621 * It is disastrous if we share memory with a vforked parent.
1622 * I'm not sure we never come here after vfork.
1623 * Therefore just close fd, nothing more.
1624 */
1625 /*fclose(fl->fp); - unsafe */
1626 close(fl->fd);
1627 fl = fl->next;
1628 }
1629}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001630#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001631static int fd_in_FILEs(int fd)
1632{
1633 struct FILE_list *fl = G.FILE_list;
1634 while (fl) {
1635 if (fl->fd == fd)
1636 return 1;
1637 fl = fl->next;
1638 }
1639 return 0;
1640}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001641
1642
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001643/* Helpers for setting new $n and restoring them back
1644 */
1645typedef struct save_arg_t {
1646 char *sv_argv0;
1647 char **sv_g_argv;
1648 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001649 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001650} save_arg_t;
1651
1652static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1653{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001654 sv->sv_argv0 = argv[0];
1655 sv->sv_g_argv = G.global_argv;
1656 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001657 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001658
1659 argv[0] = G.global_argv[0]; /* retain $0 */
1660 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001661 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001662
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001663 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001664}
1665
1666static void restore_G_args(save_arg_t *sv, char **argv)
1667{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001668#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001669 if (G.global_args_malloced) {
1670 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001671 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001672 while (*++pp) /* note: does not free $0 */
1673 free(*pp);
1674 free(G.global_argv);
1675 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001676#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001677 argv[0] = sv->sv_argv0;
1678 G.global_argv = sv->sv_g_argv;
1679 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001680 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001681}
1682
1683
Denis Vlasenkod5762932009-03-31 11:22:57 +00001684/* Basic theory of signal handling in shell
1685 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001686 * This does not describe what hush does, rather, it is current understanding
1687 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001688 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1689 *
1690 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1691 * is finished or backgrounded. It is the same in interactive and
1692 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001693 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001694 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001695 * backgrounds (i.e. stops) or kills all members of currently running
1696 * pipe.
1697 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001698 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001699 * or by SIGINT in interactive shell.
1700 *
1701 * Trap handlers will execute even within trap handlers. (right?)
1702 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001703 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1704 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001705 *
1706 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001707 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001708 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001709 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001710 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001711 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001712 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001713 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001714 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001715 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001716 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001717 *
1718 * SIGQUIT: ignore
1719 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001720 * SIGHUP (interactive):
1721 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001722 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001723 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1724 * that all pipe members are stopped. Try this in bash:
1725 * while :; do :; done - ^Z does not background it
1726 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001727 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001728 * of the command line, show prompt. NB: ^C does not send SIGINT
1729 * to interactive shell while shell is waiting for a pipe,
1730 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001731 * Example 1: this waits 5 sec, but does not execute ls:
1732 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1733 * Example 2: this does not wait and does not execute ls:
1734 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1735 * Example 3: this does not wait 5 sec, but executes ls:
1736 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001737 * Example 4: this does not wait and does not execute ls:
1738 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001739 *
1740 * (What happens to signals which are IGN on shell start?)
1741 * (What happens with signal mask on shell start?)
1742 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001743 * Old implementation
1744 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001745 * We use in-kernel pending signal mask to determine which signals were sent.
1746 * We block all signals which we don't want to take action immediately,
1747 * i.e. we block all signals which need to have special handling as described
1748 * above, and all signals which have traps set.
1749 * After each pipe execution, we extract any pending signals via sigtimedwait()
1750 * and act on them.
1751 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001752 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001753 * sigset_t blocked_set: current blocked signal set
1754 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001755 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001756 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001757 * "trap 'cmd' SIGxxx":
1758 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001759 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001760 * unblock signals with special interactive handling
1761 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001762 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001763 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001764 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001765 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001766 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001767 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001768 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001769 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001770 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001771 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001772 * Standard says "When a subshell is entered, traps that are not being ignored
1773 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001774 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001775 *
1776 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001777 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001778 * masked signals are not visible!
1779 *
1780 * New implementation
1781 * ==================
1782 * We record each signal we are interested in by installing signal handler
1783 * for them - a bit like emulating kernel pending signal mask in userspace.
1784 * We are interested in: signals which need to have special handling
1785 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001786 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001787 * After each pipe execution, we extract any pending signals
1788 * and act on them.
1789 *
1790 * unsigned special_sig_mask: a mask of shell-special signals.
1791 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1792 * char *traps[sig] if trap for sig is set (even if it's '').
1793 * sigset_t pending_set: set of sigs we received.
1794 *
1795 * "trap - SIGxxx":
1796 * if sig is in special_sig_mask, set handler back to:
1797 * record_pending_signo, or to IGN if it's a tty stop signal
1798 * if sig is in fatal_sig_mask, set handler back to sigexit.
1799 * else: set handler back to SIG_DFL
1800 * "trap 'cmd' SIGxxx":
1801 * set handler to record_pending_signo.
1802 * "trap '' SIGxxx":
1803 * set handler to SIG_IGN.
1804 * after [v]fork, if we plan to be a shell:
1805 * set signals with special interactive handling to SIG_DFL
1806 * (because child shell is not interactive),
1807 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1808 * after [v]fork, if we plan to exec:
1809 * POSIX says fork clears pending signal mask in child - no need to clear it.
1810 *
1811 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1812 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1813 *
1814 * Note (compat):
1815 * Standard says "When a subshell is entered, traps that are not being ignored
1816 * are set to the default actions". bash interprets it so that traps which
1817 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001818 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001819enum {
1820 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001821 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001822 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001823 | (1 << SIGHUP)
1824 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001825 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001826#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001827 | (1 << SIGTTIN)
1828 | (1 << SIGTTOU)
1829 | (1 << SIGTSTP)
1830#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001831 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001832};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001833
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001834static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001835{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001836 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001837#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001838 if (sig == SIGCHLD) {
1839 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001840//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001841 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001842#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001843}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001844
Denys Vlasenko0806e402011-05-12 23:06:20 +02001845static sighandler_t install_sighandler(int sig, sighandler_t handler)
1846{
1847 struct sigaction old_sa;
1848
1849 /* We could use signal() to install handlers... almost:
1850 * except that we need to mask ALL signals while handlers run.
1851 * I saw signal nesting in strace, race window isn't small.
1852 * SA_RESTART is also needed, but in Linux, signal()
1853 * sets SA_RESTART too.
1854 */
1855 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1856 /* sigfillset(&G.sa.sa_mask); - already done */
1857 /* G.sa.sa_flags = SA_RESTART; - already done */
1858 G.sa.sa_handler = handler;
1859 sigaction(sig, &G.sa, &old_sa);
1860 return old_sa.sa_handler;
1861}
1862
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001863static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001864
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001865static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001866static void restore_ttypgrp_and__exit(void)
1867{
1868 /* xfunc has failed! die die die */
1869 /* no EXIT traps, this is an escape hatch! */
1870 G.exiting = 1;
1871 hush_exit(xfunc_error_retval);
1872}
1873
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001874#if ENABLE_HUSH_JOB
1875
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001876/* Needed only on some libc:
1877 * It was observed that on exit(), fgetc'ed buffered data
1878 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1879 * With the net effect that even after fork(), not vfork(),
1880 * exit() in NOEXECed applet in "sh SCRIPT":
1881 * noexec_applet_here
1882 * echo END_OF_SCRIPT
1883 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1884 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001885 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001886 * and in `cmd` handling.
1887 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1888 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001889static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001890static void fflush_and__exit(void)
1891{
1892 fflush_all();
1893 _exit(xfunc_error_retval);
1894}
1895
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001896/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001897# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001898/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001899# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001900
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001901/* Restores tty foreground process group, and exits.
1902 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001903 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001904 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001905 * We also call it if xfunc is exiting.
1906 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001907static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001908static void sigexit(int sig)
1909{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001910 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001911 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001912 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1913 /* Disable all signals: job control, SIGPIPE, etc.
1914 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1915 */
1916 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001917 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001918 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001919
1920 /* Not a signal, just exit */
1921 if (sig <= 0)
1922 _exit(- sig);
1923
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001924 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001925}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001926#else
1927
Denys Vlasenko8391c482010-05-22 17:50:43 +02001928# define disable_restore_tty_pgrp_on_exit() ((void)0)
1929# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001930
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001931#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001932
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001933static sighandler_t pick_sighandler(unsigned sig)
1934{
1935 sighandler_t handler = SIG_DFL;
1936 if (sig < sizeof(unsigned)*8) {
1937 unsigned sigmask = (1 << sig);
1938
1939#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001940 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001941 if (G_fatal_sig_mask & sigmask)
1942 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001943 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001944#endif
1945 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001946 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001947 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001948 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001949 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001950 * in an endless loop when we try to do some
1951 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001952 */
1953 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1954 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001955 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001956 }
1957 return handler;
1958}
1959
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001960/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001961static void hush_exit(int exitcode)
1962{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001963#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1964 save_history(G.line_input_state);
1965#endif
1966
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001967 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001968 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001969 char *argv[3];
1970 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001971 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001972 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001973 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001974 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001975 * "trap" will still show it, if executed
1976 * in the handler */
1977 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001978 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001979
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001980#if ENABLE_FEATURE_CLEAN_UP
1981 {
1982 struct variable *cur_var;
1983 if (G.cwd != bb_msg_unknown)
1984 free((char*)G.cwd);
1985 cur_var = G.top_var;
1986 while (cur_var) {
1987 struct variable *tmp = cur_var;
1988 if (!cur_var->max_len)
1989 free(cur_var->varstr);
1990 cur_var = cur_var->next;
1991 free(tmp);
1992 }
1993 }
1994#endif
1995
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001996 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001997#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001998 sigexit(- (exitcode & 0xff));
1999#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002000 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002001#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002002}
2003
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002004
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002005//TODO: return a mask of ALL handled sigs?
2006static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002007{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002008 int last_sig = 0;
2009
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002010 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002011 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002012
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002013 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002014 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002015 sig = 0;
2016 do {
2017 sig++;
2018 if (sigismember(&G.pending_set, sig)) {
2019 sigdelset(&G.pending_set, sig);
2020 goto got_sig;
2021 }
2022 } while (sig < NSIG);
2023 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002024 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002025 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002026 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002027 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002028 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002029 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002030 char *argv[3];
2031 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002032 argv[1] = xstrdup(G_traps[sig]);
2033 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002034 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002035 save_rcode = G.last_exitcode;
2036 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002037 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002038//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002039 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002040 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002041 } /* else: "" trap, ignoring signal */
2042 continue;
2043 }
2044 /* not a trap: special action */
2045 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002046 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002047 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002048 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002049 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002050 break;
2051#if ENABLE_HUSH_JOB
2052 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002053//TODO: why are we doing this? ash and dash don't do this,
2054//they have no handler for SIGHUP at all,
2055//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002056 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002057 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002058 /* bash is observed to signal whole process groups,
2059 * not individual processes */
2060 for (job = G.job_list; job; job = job->next) {
2061 if (job->pgrp <= 0)
2062 continue;
2063 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2064 if (kill(- job->pgrp, SIGHUP) == 0)
2065 kill(- job->pgrp, SIGCONT);
2066 }
2067 sigexit(SIGHUP);
2068 }
2069#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002070#if ENABLE_HUSH_FAST
2071 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002072 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002073 G.count_SIGCHLD++;
2074//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2075 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002076 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002077 * This simplifies wait builtin a bit.
2078 */
2079 break;
2080#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002081 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002082 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002083 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002084 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002085 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002086 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002087 * in interactive shell, because TERM is ignored.
2088 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002089 break;
2090 }
2091 }
2092 return last_sig;
2093}
2094
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002095
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002096static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002097{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002098 if (force || G.cwd == NULL) {
2099 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2100 * we must not try to free(bb_msg_unknown) */
2101 if (G.cwd == bb_msg_unknown)
2102 G.cwd = NULL;
2103 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2104 if (!G.cwd)
2105 G.cwd = bb_msg_unknown;
2106 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002107 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002108}
2109
Denis Vlasenko83506862007-11-23 13:11:42 +00002110
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002111/*
2112 * Shell and environment variable support
2113 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002114static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002116 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002117 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002118
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002119 pp = &G.top_var;
2120 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002121 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002122 return pp;
2123 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002124 }
2125 return NULL;
2126}
2127
Denys Vlasenko03dad222010-01-12 23:29:57 +01002128static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002129{
Denys Vlasenko29082232010-07-16 13:52:32 +02002130 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002131 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002132
2133 if (G.expanded_assignments) {
2134 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002135 while (*cpp) {
2136 char *cp = *cpp;
2137 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2138 return cp + len + 1;
2139 cpp++;
2140 }
2141 }
2142
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002143 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002144 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002145 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002146
Denys Vlasenkodea47882009-10-09 15:40:49 +02002147 if (strcmp(name, "PPID") == 0)
2148 return utoa(G.root_ppid);
2149 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002150#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002151 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002152 return utoa(next_random(&G.random_gen));
2153#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002154 return NULL;
2155}
2156
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002157static void handle_changed_special_names(const char *name, unsigned name_len)
2158{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002159 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2160 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2161 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002162 cmdedit_update_prompt();
2163 return;
2164 }
2165
2166 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2167 && name_len == 6
2168 ) {
2169#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002170 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002171 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002172 return;
2173 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002174#endif
2175#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002176 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002177 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002178 return;
2179 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002180#endif
2181 }
2182}
2183
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002184/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002185 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002186 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002187#define SETFLAG_EXPORT (1 << 0)
2188#define SETFLAG_UNEXPORT (1 << 1)
2189#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002190#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002191static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002192{
Denys Vlasenko61407802018-04-04 21:14:28 +02002193 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002194 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002195 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002196 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002197 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002198 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002199
Denis Vlasenko950bd722009-04-21 11:23:56 +00002200 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002201 if (HUSH_DEBUG && !eq_sign)
2202 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002203
Denis Vlasenko950bd722009-04-21 11:23:56 +00002204 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002205 cur_pp = &G.top_var;
2206 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002207 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002208 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002209 continue;
2210 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002211
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002212 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002213 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002214 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002215 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002216//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2217//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002218 return -1;
2219 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002220 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002221 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2222 *eq_sign = '\0';
2223 unsetenv(str);
2224 *eq_sign = '=';
2225 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002226 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002227 /* bash 3.2.33(1) and exported vars:
2228 * # export z=z
2229 * # f() { local z=a; env | grep ^z; }
2230 * # f
2231 * z=a
2232 * # env | grep ^z
2233 * z=z
2234 */
2235 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002236 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002237 /* New variable is local ("local VAR=VAL" or
2238 * "VAR=VAL cmd")
2239 * and existing one is global, or local
2240 * on a lower level that new one.
2241 * Remove it from global variable list:
2242 */
2243 *cur_pp = cur->next;
2244 if (G.shadowed_vars_pp) {
2245 /* Save in "shadowed" list */
2246 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2247 cur->flg_export ? "exported " : "",
2248 cur->varstr, cur->var_nest_level, str, local_lvl
2249 );
2250 cur->next = *G.shadowed_vars_pp;
2251 *G.shadowed_vars_pp = cur;
2252 } else {
2253 /* Came from pseudo_exec_argv(), no need to save: delete it */
2254 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2255 cur->flg_export ? "exported " : "",
2256 cur->varstr, cur->var_nest_level, str, local_lvl
2257 );
2258 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2259 free_me = cur->varstr; /* then free it later */
2260 free(cur);
2261 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002262 break;
2263 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002264
Denis Vlasenko950bd722009-04-21 11:23:56 +00002265 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002266 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002267 free_and_exp:
2268 free(str);
2269 goto exp;
2270 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002271
2272 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002273 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002274 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002275 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002276 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002277 strcpy(cur->varstr, str);
2278 goto free_and_exp;
2279 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002280 /* Can't reuse */
2281 cur->max_len = 0;
2282 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002283 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002284 /* max_len == 0 signifies "malloced" var, which we can
2285 * (and have to) free. But we can't free(cur->varstr) here:
2286 * if cur->flg_export is 1, it is in the environment.
2287 * We should either unsetenv+free, or wait until putenv,
2288 * then putenv(new)+free(old).
2289 */
2290 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002291 goto set_str_and_exp;
2292 }
2293
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002294 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002295 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002296 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002297 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002298 cur->next = *cur_pp;
2299 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002300
2301 set_str_and_exp:
2302 cur->varstr = str;
2303 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002304#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002305 if (flags & SETFLAG_MAKE_RO) {
2306 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002307 }
2308#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002309 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002310 cur->flg_export = 1;
2311 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002312 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002313 cur->flg_export = 0;
2314 /* unsetenv was already done */
2315 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002316 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002317 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002318 i = putenv(cur->varstr);
2319 /* only now we can free old exported malloced string */
2320 free(free_me);
2321 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002322 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002323 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002324 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002325
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002326 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002327
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002328 return 0;
2329}
2330
Denys Vlasenko6db47842009-09-05 20:15:17 +02002331/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002332static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002333{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002334 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002335}
2336
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002337#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002338static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002339{
2340 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002341 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002342
Denys Vlasenko61407802018-04-04 21:14:28 +02002343 cur_pp = &G.top_var;
2344 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002345 if (strncmp(cur->varstr, name, name_len) == 0
2346 && cur->varstr[name_len] == '='
2347 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002348 if (cur->flg_read_only) {
2349 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002350 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002351 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002352
Denys Vlasenko61407802018-04-04 21:14:28 +02002353 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002354 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2355 bb_unsetenv(cur->varstr);
2356 if (!cur->max_len)
2357 free(cur->varstr);
2358 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002359
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002360 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002361 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002362 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002363 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002364
2365 /* Handle "unset PS1" et al even if did not find the variable to unset */
2366 handle_changed_special_names(name, name_len);
2367
Mike Frysingerd690f682009-03-30 06:50:54 +00002368 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002369}
2370
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002371static int unset_local_var(const char *name)
2372{
2373 return unset_local_var_len(name, strlen(name));
2374}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002375#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002376
Denys Vlasenkob2b14cb2018-06-26 18:09:22 +02002377#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2378 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002379static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002380{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002381 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002382 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002383}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002384#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002385
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002386
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002387/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002388 * Helpers for "var1=val1 var2=val2 cmd" feature
2389 */
2390static void add_vars(struct variable *var)
2391{
2392 struct variable *next;
2393
2394 while (var) {
2395 next = var->next;
2396 var->next = G.top_var;
2397 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002398 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002399 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002400 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002401 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002402 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002403 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002404 var = next;
2405 }
2406}
2407
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002408/* We put strings[i] into variable table and possibly putenv them.
2409 * If variable is read only, we can free the strings[i]
2410 * which attempts to overwrite it.
2411 * The strings[] vector itself is freed.
2412 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002413static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002414{
2415 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002416
2417 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002418 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002419
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002420 s = strings;
2421 while (*s) {
2422 struct variable *var_p;
2423 struct variable **var_pp;
2424 char *eq;
2425
2426 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002427 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002428 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002429 var_pp = get_ptr_to_local_var(*s, eq - *s);
2430 if (var_pp) {
2431 var_p = *var_pp;
2432 if (var_p->flg_read_only) {
2433 char **p;
2434 bb_error_msg("%s: readonly variable", *s);
2435 /*
2436 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2437 * If VAR is readonly, leaving it in the list
2438 * after asssignment error (msg above)
2439 * causes doubled error message later, on unset.
2440 */
2441 debug_printf_env("removing/freeing '%s' element\n", *s);
2442 free(*s);
2443 p = s;
2444 do { *p = p[1]; p++; } while (*p);
2445 goto next;
2446 }
2447 /* below, set_local_var() with nest level will
2448 * "shadow" (remove) this variable from
2449 * global linked list.
2450 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002451 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002452 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2453 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002454 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002455 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002456 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002457 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002458}
2459
2460
2461/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002462 * Unicode helper
2463 */
2464static void reinit_unicode_for_hush(void)
2465{
2466 /* Unicode support should be activated even if LANG is set
2467 * _during_ shell execution, not only if it was set when
2468 * shell was started. Therefore, re-check LANG every time:
2469 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002470 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2471 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002472 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002473 const char *s = get_local_var_value("LC_ALL");
2474 if (!s) s = get_local_var_value("LC_CTYPE");
2475 if (!s) s = get_local_var_value("LANG");
2476 reinit_unicode(s);
2477 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002478}
2479
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002480/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002481 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002482 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483
2484#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002485/* To test correct lineedit/interactive behavior, type from command line:
2486 * echo $P\
2487 * \
2488 * AT\
2489 * H\
2490 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002491 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002492 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002493# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002494static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002495{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002496 G.PS1 = get_local_var_value("PS1");
2497 if (G.PS1 == NULL)
2498 G.PS1 = "";
2499 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002500 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002501 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002502}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002503# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002504static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002505{
2506 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002507
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002508 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002509
2510 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2511 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002512 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002513 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2514 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002515 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002516 /* bash uses $PWD value, even if it is set by user.
2517 * It uses current dir only if PWD is unset.
2518 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002519 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002520 }
2521 prompt_str = G.PS1;
2522 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002523 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002524 return prompt_str;
2525}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002526static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002527{
2528 int r;
2529 const char *prompt_str;
2530
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002531 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002532# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002533 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002534 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002535 if (G.flag_SIGINT) {
2536 /* There was ^C'ed, make it look prettier: */
2537 bb_putchar('\n');
2538 G.flag_SIGINT = 0;
2539 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002540 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002541 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002542 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002543 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002544 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002545 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002546 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002547 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002548 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002549 if (r != 0 && !G.flag_SIGINT)
2550 break;
2551 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002552 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2553 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002554 G.last_exitcode = 128 + SIGINT;
2555 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002556 if (r < 0) {
2557 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002558 i->p = NULL;
2559 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002560 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002561 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002562 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002563 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002564# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002565 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002566 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002567 if (i->last_char == '\0' || i->last_char == '\n') {
2568 /* Why check_and_run_traps here? Try this interactively:
2569 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2570 * $ <[enter], repeatedly...>
2571 * Without check_and_run_traps, handler never runs.
2572 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002573 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002574 fputs(prompt_str, stdout);
2575 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002576 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002577//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002578 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002579 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2580 * no ^C masking happens during fgetc, no special code for ^C:
2581 * it generates SIGINT as usual.
2582 */
2583 check_and_run_traps();
2584 if (G.flag_SIGINT)
2585 G.last_exitcode = 128 + SIGINT;
2586 if (r != '\0')
2587 break;
2588 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002589 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002590# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002591}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002592/* This is the magic location that prints prompts
2593 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002594static int fgetc_interactive(struct in_str *i)
2595{
2596 int ch;
2597 /* If it's interactive stdin, get new line. */
2598 if (G_interactive_fd && i->file == stdin) {
2599 /* Returns first char (or EOF), the rest is in i->p[] */
2600 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002601 G.promptmode = 1; /* PS2 */
2602 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002603 } else {
2604 /* Not stdin: script file, sourced file, etc */
2605 do ch = fgetc(i->file); while (ch == '\0');
2606 }
2607 return ch;
2608}
2609#else
2610static inline int fgetc_interactive(struct in_str *i)
2611{
2612 int ch;
2613 do ch = fgetc(i->file); while (ch == '\0');
2614 return ch;
2615}
2616#endif /* INTERACTIVE */
2617
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002618static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002619{
2620 int ch;
2621
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002622 if (!i->file) {
2623 /* string-based in_str */
2624 ch = (unsigned char)*i->p;
2625 if (ch != '\0') {
2626 i->p++;
2627 i->last_char = ch;
2628 return ch;
2629 }
2630 return EOF;
2631 }
2632
2633 /* FILE-based in_str */
2634
Denys Vlasenko4074d492016-09-30 01:49:53 +02002635#if ENABLE_FEATURE_EDITING
2636 /* This can be stdin, check line editing char[] buffer */
2637 if (i->p && *i->p != '\0') {
2638 ch = (unsigned char)*i->p++;
2639 goto out;
2640 }
2641#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002642 /* peek_buf[] is an int array, not char. Can contain EOF. */
2643 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002644 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002645 int ch2 = i->peek_buf[1];
2646 i->peek_buf[0] = ch2;
2647 if (ch2 == 0) /* very likely, avoid redundant write */
2648 goto out;
2649 i->peek_buf[1] = 0;
2650 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002651 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002652
Denys Vlasenko4074d492016-09-30 01:49:53 +02002653 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002654 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002655 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002656 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002657#if ENABLE_HUSH_LINENO_VAR
2658 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002659 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002660 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2661 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002662#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002663 return ch;
2664}
2665
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002666static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002667{
2668 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002669
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002670 if (!i->file) {
2671 /* string-based in_str */
2672 /* Doesn't report EOF on NUL. None of the callers care. */
2673 return (unsigned char)*i->p;
2674 }
2675
2676 /* FILE-based in_str */
2677
Denys Vlasenko4074d492016-09-30 01:49:53 +02002678#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002679 /* This can be stdin, check line editing char[] buffer */
2680 if (i->p && *i->p != '\0')
2681 return (unsigned char)*i->p;
2682#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002683 /* peek_buf[] is an int array, not char. Can contain EOF. */
2684 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002685 if (ch != 0)
2686 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002687
Denys Vlasenko4074d492016-09-30 01:49:53 +02002688 /* Need to get a new char */
2689 ch = fgetc_interactive(i);
2690 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2691
2692 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2693#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2694 if (i->p) {
2695 i->p -= 1;
2696 return ch;
2697 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002698#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002699 i->peek_buf[0] = ch;
2700 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002701 return ch;
2702}
2703
Denys Vlasenko4074d492016-09-30 01:49:53 +02002704/* Only ever called if i_peek() was called, and did not return EOF.
2705 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2706 * not end-of-line. Therefore we never need to read a new editing line here.
2707 */
2708static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002709{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002710 int ch;
2711
2712 /* There are two cases when i->p[] buffer exists.
2713 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002714 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002715 * In both cases, we know that i->p[0] exists and not NUL, and
2716 * the peek2 result is in i->p[1].
2717 */
2718 if (i->p)
2719 return (unsigned char)i->p[1];
2720
2721 /* Now we know it is a file-based in_str. */
2722
2723 /* peek_buf[] is an int array, not char. Can contain EOF. */
2724 /* Is there 2nd char? */
2725 ch = i->peek_buf[1];
2726 if (ch == 0) {
2727 /* We did not read it yet, get it now */
2728 do ch = fgetc(i->file); while (ch == '\0');
2729 i->peek_buf[1] = ch;
2730 }
2731
2732 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2733 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002734}
2735
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002736static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2737{
2738 for (;;) {
2739 int ch, ch2;
2740
2741 ch = i_getch(input);
2742 if (ch != '\\')
2743 return ch;
2744 ch2 = i_peek(input);
2745 if (ch2 != '\n')
2746 return ch;
2747 /* backslash+newline, skip it */
2748 i_getch(input);
2749 }
2750}
2751
2752/* Note: this function _eats_ \<newline> pairs, safe to use plain
2753 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2754 */
2755static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2756{
2757 for (;;) {
2758 int ch, ch2;
2759
2760 ch = i_peek(input);
2761 if (ch != '\\')
2762 return ch;
2763 ch2 = i_peek2(input);
2764 if (ch2 != '\n')
2765 return ch;
2766 /* backslash+newline, skip it */
2767 i_getch(input);
2768 i_getch(input);
2769 }
2770}
2771
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002772static void setup_file_in_str(struct in_str *i, FILE *f)
2773{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002774 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002775 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002776 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002777}
2778
2779static void setup_string_in_str(struct in_str *i, const char *s)
2780{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002781 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002782 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002783 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002784}
2785
2786
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002787/*
2788 * o_string support
2789 */
2790#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002791
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002792static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002793{
2794 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002795 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002796 if (o->data)
2797 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002798}
2799
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002800static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002801{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002802 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002803 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002804}
2805
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002806static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2807{
2808 free(o->data);
2809}
2810
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002811static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002812{
2813 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002814 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002815 o->data = xrealloc(o->data, 1 + o->maxlen);
2816 }
2817}
2818
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002819static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002820{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002821 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002822 if (o->length < o->maxlen) {
2823 /* likely. avoid o_grow_by() call */
2824 add:
2825 o->data[o->length] = ch;
2826 o->length++;
2827 o->data[o->length] = '\0';
2828 return;
2829 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002830 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002831 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002832}
2833
Denys Vlasenko657086a2016-09-29 18:07:42 +02002834#if 0
2835/* Valid only if we know o_string is not empty */
2836static void o_delchr(o_string *o)
2837{
2838 o->length--;
2839 o->data[o->length] = '\0';
2840}
2841#endif
2842
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002843static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002844{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002845 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002846 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002847 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002848}
2849
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002850static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002851{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002852 o_addblock(o, str, strlen(str));
2853}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002854
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002855#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002856static void nommu_addchr(o_string *o, int ch)
2857{
2858 if (o)
2859 o_addchr(o, ch);
2860}
2861#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002862# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002863#endif
2864
2865static void o_addstr_with_NUL(o_string *o, const char *str)
2866{
2867 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002868}
2869
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002870/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002871 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002872 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2873 * Apparently, on unquoted $v bash still does globbing
2874 * ("v='*.txt'; echo $v" prints all .txt files),
2875 * but NOT brace expansion! Thus, there should be TWO independent
2876 * quoting mechanisms on $v expansion side: one protects
2877 * $v from brace expansion, and other additionally protects "$v" against globbing.
2878 * We have only second one.
2879 */
2880
Denys Vlasenko9e800222010-10-03 14:28:04 +02002881#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002882# define MAYBE_BRACES "{}"
2883#else
2884# define MAYBE_BRACES ""
2885#endif
2886
Eric Andersen25f27032001-04-26 23:22:31 +00002887/* My analysis of quoting semantics tells me that state information
2888 * is associated with a destination, not a source.
2889 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002890static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002891{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002892 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002893 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002894 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002895 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002896 o_grow_by(o, sz);
2897 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002898 o->data[o->length] = '\\';
2899 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002900 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002901 o->data[o->length] = ch;
2902 o->length++;
2903 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002904}
2905
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002906static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002907{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002908 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002909 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2910 && strchr("*?[\\" MAYBE_BRACES, ch)
2911 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002912 sz++;
2913 o->data[o->length] = '\\';
2914 o->length++;
2915 }
2916 o_grow_by(o, sz);
2917 o->data[o->length] = ch;
2918 o->length++;
2919 o->data[o->length] = '\0';
2920}
2921
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002922static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002923{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002924 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002925 char ch;
2926 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002927 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002928 if (ordinary_cnt > len) /* paranoia */
2929 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002930 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002931 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002932 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002933 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002934 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002935
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002936 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002937 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002938 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002939 sz++;
2940 o->data[o->length] = '\\';
2941 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002942 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002943 o_grow_by(o, sz);
2944 o->data[o->length] = ch;
2945 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002946 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002947 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002948}
2949
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002950static void o_addQblock(o_string *o, const char *str, int len)
2951{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002952 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002953 o_addblock(o, str, len);
2954 return;
2955 }
2956 o_addqblock(o, str, len);
2957}
2958
Denys Vlasenko38292b62010-09-05 14:49:40 +02002959static void o_addQstr(o_string *o, const char *str)
2960{
2961 o_addQblock(o, str, strlen(str));
2962}
2963
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002964/* A special kind of o_string for $VAR and `cmd` expansion.
2965 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002966 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002967 * list[i] contains an INDEX (int!) into this string data.
2968 * It means that if list[] needs to grow, data needs to be moved higher up
2969 * but list[i]'s need not be modified.
2970 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002971 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002972 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2973 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002974#if DEBUG_EXPAND || DEBUG_GLOB
2975static void debug_print_list(const char *prefix, o_string *o, int n)
2976{
2977 char **list = (char**)o->data;
2978 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2979 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002980
2981 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002982 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002983 prefix, list, n, string_start, o->length, o->maxlen,
2984 !!(o->o_expflags & EXP_FLAG_GLOB),
2985 o->has_quoted_part,
2986 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002987 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002988 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002989 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2990 o->data + (int)(uintptr_t)list[i] + string_start,
2991 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002992 i++;
2993 }
2994 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002995 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002996 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002997 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002998 }
2999}
3000#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003001# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003002#endif
3003
3004/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3005 * in list[n] so that it points past last stored byte so far.
3006 * It returns n+1. */
3007static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003008{
3009 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003010 int string_start;
3011 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003012
3013 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003014 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3015 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003016 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003017 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003018 /* list[n] points to string_start, make space for 16 more pointers */
3019 o->maxlen += 0x10 * sizeof(list[0]);
3020 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003021 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003022 memmove(list + n + 0x10, list + n, string_len);
3023 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003024 } else {
3025 debug_printf_list("list[%d]=%d string_start=%d\n",
3026 n, string_len, string_start);
3027 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003028 } else {
3029 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003030 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3031 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003032 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3033 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003034 o->has_empty_slot = 0;
3035 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003036 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003037 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003038 return n + 1;
3039}
3040
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003041/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003042static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003043{
3044 char **list = (char**)o->data;
3045 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3046
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003047 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003048}
3049
Denys Vlasenko9e800222010-10-03 14:28:04 +02003050#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003051/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3052 * first, it processes even {a} (no commas), second,
3053 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003054 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003055 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003056
3057/* Helper */
3058static int glob_needed(const char *s)
3059{
3060 while (*s) {
3061 if (*s == '\\') {
3062 if (!s[1])
3063 return 0;
3064 s += 2;
3065 continue;
3066 }
3067 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3068 return 1;
3069 s++;
3070 }
3071 return 0;
3072}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003073/* Return pointer to next closing brace or to comma */
3074static const char *next_brace_sub(const char *cp)
3075{
3076 unsigned depth = 0;
3077 cp++;
3078 while (*cp != '\0') {
3079 if (*cp == '\\') {
3080 if (*++cp == '\0')
3081 break;
3082 cp++;
3083 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003084 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003085 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003086 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003087 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003088 depth++;
3089 }
3090
3091 return *cp != '\0' ? cp : NULL;
3092}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003093/* Recursive brace globber. Note: may garble pattern[]. */
3094static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003095{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003096 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003097 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003098 const char *next;
3099 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003100 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003101 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003102
3103 debug_printf_glob("glob_brace('%s')\n", pattern);
3104
3105 begin = pattern;
3106 while (1) {
3107 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003108 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003109 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003110 /* Find the first sub-pattern and at the same time
3111 * find the rest after the closing brace */
3112 next = next_brace_sub(begin);
3113 if (next == NULL) {
3114 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003115 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003116 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003117 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003118 /* "{abc}" with no commas - illegal
3119 * brace expr, disregard and skip it */
3120 begin = next + 1;
3121 continue;
3122 }
3123 break;
3124 }
3125 if (*begin == '\\' && begin[1] != '\0')
3126 begin++;
3127 begin++;
3128 }
3129 debug_printf_glob("begin:%s\n", begin);
3130 debug_printf_glob("next:%s\n", next);
3131
3132 /* Now find the end of the whole brace expression */
3133 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003134 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003135 rest = next_brace_sub(rest);
3136 if (rest == NULL) {
3137 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003138 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003139 }
3140 debug_printf_glob("rest:%s\n", rest);
3141 }
3142 rest_len = strlen(++rest) + 1;
3143
3144 /* We are sure the brace expression is well-formed */
3145
3146 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003147 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003148
3149 /* We have a brace expression. BEGIN points to the opening {,
3150 * NEXT points past the terminator of the first element, and REST
3151 * points past the final }. We will accumulate result names from
3152 * recursive runs for each brace alternative in the buffer using
3153 * GLOB_APPEND. */
3154
3155 p = begin + 1;
3156 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003157 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003158 memcpy(
3159 mempcpy(
3160 mempcpy(new_pattern_buf,
3161 /* We know the prefix for all sub-patterns */
3162 pattern, begin - pattern),
3163 p, next - p),
3164 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003165
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003166 /* Note: glob_brace() may garble new_pattern_buf[].
3167 * That's why we re-copy prefix every time (1st memcpy above).
3168 */
3169 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003170 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003171 /* We saw the last entry */
3172 break;
3173 }
3174 p = next + 1;
3175 next = next_brace_sub(next);
3176 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003177 free(new_pattern_buf);
3178 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003179
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003180 simple_glob:
3181 {
3182 int gr;
3183 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003184
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003185 memset(&globdata, 0, sizeof(globdata));
3186 gr = glob(pattern, 0, NULL, &globdata);
3187 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3188 if (gr != 0) {
3189 if (gr == GLOB_NOMATCH) {
3190 globfree(&globdata);
3191 /* NB: garbles parameter */
3192 unbackslash(pattern);
3193 o_addstr_with_NUL(o, pattern);
3194 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3195 return o_save_ptr_helper(o, n);
3196 }
3197 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003198 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003199 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3200 * but we didn't specify it. Paranoia again. */
3201 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3202 }
3203 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3204 char **argv = globdata.gl_pathv;
3205 while (1) {
3206 o_addstr_with_NUL(o, *argv);
3207 n = o_save_ptr_helper(o, n);
3208 argv++;
3209 if (!*argv)
3210 break;
3211 }
3212 }
3213 globfree(&globdata);
3214 }
3215 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003216}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003217/* Performs globbing on last list[],
3218 * saving each result as a new list[].
3219 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003220static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003221{
3222 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003223
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003224 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003225 if (!o->data)
3226 return o_save_ptr_helper(o, n);
3227 pattern = o->data + o_get_last_ptr(o, n);
3228 debug_printf_glob("glob pattern '%s'\n", pattern);
3229 if (!glob_needed(pattern)) {
3230 /* unbackslash last string in o in place, fix length */
3231 o->length = unbackslash(pattern) - o->data;
3232 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3233 return o_save_ptr_helper(o, n);
3234 }
3235
3236 copy = xstrdup(pattern);
3237 /* "forget" pattern in o */
3238 o->length = pattern - o->data;
3239 n = glob_brace(copy, o, n);
3240 free(copy);
3241 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003242 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003243 return n;
3244}
3245
Denys Vlasenko238081f2010-10-03 14:26:26 +02003246#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003247
3248/* Helper */
3249static int glob_needed(const char *s)
3250{
3251 while (*s) {
3252 if (*s == '\\') {
3253 if (!s[1])
3254 return 0;
3255 s += 2;
3256 continue;
3257 }
3258 if (*s == '*' || *s == '[' || *s == '?')
3259 return 1;
3260 s++;
3261 }
3262 return 0;
3263}
3264/* Performs globbing on last list[],
3265 * saving each result as a new list[].
3266 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003267static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003268{
3269 glob_t globdata;
3270 int gr;
3271 char *pattern;
3272
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003273 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003274 if (!o->data)
3275 return o_save_ptr_helper(o, n);
3276 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003277 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003278 if (!glob_needed(pattern)) {
3279 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003280 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003281 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003282 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003283 return o_save_ptr_helper(o, n);
3284 }
3285
3286 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003287 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3288 * If we glob "*.\*" and don't find anything, we need
3289 * to fall back to using literal "*.*", but GLOB_NOCHECK
3290 * will return "*.\*"!
3291 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003292 gr = glob(pattern, 0, NULL, &globdata);
3293 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003294 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003295 if (gr == GLOB_NOMATCH) {
3296 globfree(&globdata);
3297 goto literal;
3298 }
3299 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003300 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003301 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3302 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003303 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003304 }
3305 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3306 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003307 /* "forget" pattern in o */
3308 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003309 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003310 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003311 n = o_save_ptr_helper(o, n);
3312 argv++;
3313 if (!*argv)
3314 break;
3315 }
3316 }
3317 globfree(&globdata);
3318 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003319 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003320 return n;
3321}
3322
Denys Vlasenko238081f2010-10-03 14:26:26 +02003323#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003324
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003325/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003326 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003327static int o_save_ptr(o_string *o, int n)
3328{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003329 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003330 /* If o->has_empty_slot, list[n] was already globbed
3331 * (if it was requested back then when it was filled)
3332 * so don't do that again! */
3333 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003334 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003335 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003336 return o_save_ptr_helper(o, n);
3337}
3338
3339/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003340static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003341{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003342 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003343 int string_start;
3344
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003345 if (DEBUG_EXPAND)
3346 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003347 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003348 list = (char**)o->data;
3349 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3350 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003351 while (n) {
3352 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003353 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003354 }
3355 return list;
3356}
3357
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003358static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003359
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003360/* Returns pi->next - next pipe in the list */
3361static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003362{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003363 struct pipe *next;
3364 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003365
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003366 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003367 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003368 struct command *command;
3369 struct redir_struct *r, *rnext;
3370
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003371 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003372 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003373 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003374 if (DEBUG_CLEAN) {
3375 int a;
3376 char **p;
3377 for (a = 0, p = command->argv; *p; a++, p++) {
3378 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3379 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003380 }
3381 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003382 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003383 }
3384 /* not "else if": on syntax error, we may have both! */
3385 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003386 debug_printf_clean(" begin group (cmd_type:%d)\n",
3387 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003388 free_pipe_list(command->group);
3389 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003390 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003391 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003392 /* else is crucial here.
3393 * If group != NULL, child_func is meaningless */
3394#if ENABLE_HUSH_FUNCTIONS
3395 else if (command->child_func) {
3396 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3397 command->child_func->parent_cmd = NULL;
3398 }
3399#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003400#if !BB_MMU
3401 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003402 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003403#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003404 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003405 debug_printf_clean(" redirect %d%s",
3406 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003407 /* guard against the case >$FOO, where foo is unset or blank */
3408 if (r->rd_filename) {
3409 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3410 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003411 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003412 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003413 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003414 rnext = r->next;
3415 free(r);
3416 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003417 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003418 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003419 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003420 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003421#if ENABLE_HUSH_JOB
3422 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003423 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003424#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003425
3426 next = pi->next;
3427 free(pi);
3428 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003429}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003430
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003431static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003432{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003433 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003434#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003435 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003436#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003437 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003438 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003439 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003440}
3441
3442
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003443/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003444
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003445#ifndef debug_print_tree
3446static void debug_print_tree(struct pipe *pi, int lvl)
3447{
3448 static const char *const PIPE[] = {
3449 [PIPE_SEQ] = "SEQ",
3450 [PIPE_AND] = "AND",
3451 [PIPE_OR ] = "OR" ,
3452 [PIPE_BG ] = "BG" ,
3453 };
3454 static const char *RES[] = {
3455 [RES_NONE ] = "NONE" ,
3456# if ENABLE_HUSH_IF
3457 [RES_IF ] = "IF" ,
3458 [RES_THEN ] = "THEN" ,
3459 [RES_ELIF ] = "ELIF" ,
3460 [RES_ELSE ] = "ELSE" ,
3461 [RES_FI ] = "FI" ,
3462# endif
3463# if ENABLE_HUSH_LOOPS
3464 [RES_FOR ] = "FOR" ,
3465 [RES_WHILE] = "WHILE",
3466 [RES_UNTIL] = "UNTIL",
3467 [RES_DO ] = "DO" ,
3468 [RES_DONE ] = "DONE" ,
3469# endif
3470# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3471 [RES_IN ] = "IN" ,
3472# endif
3473# if ENABLE_HUSH_CASE
3474 [RES_CASE ] = "CASE" ,
3475 [RES_CASE_IN ] = "CASE_IN" ,
3476 [RES_MATCH] = "MATCH",
3477 [RES_CASE_BODY] = "CASE_BODY",
3478 [RES_ESAC ] = "ESAC" ,
3479# endif
3480 [RES_XXXX ] = "XXXX" ,
3481 [RES_SNTX ] = "SNTX" ,
3482 };
3483 static const char *const CMDTYPE[] = {
3484 "{}",
3485 "()",
3486 "[noglob]",
3487# if ENABLE_HUSH_FUNCTIONS
3488 "func()",
3489# endif
3490 };
3491
3492 int pin, prn;
3493
3494 pin = 0;
3495 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003496 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3497 lvl*2, "",
3498 pin,
3499 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3500 RES[pi->res_word],
3501 pi->followup, PIPE[pi->followup]
3502 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003503 prn = 0;
3504 while (prn < pi->num_cmds) {
3505 struct command *command = &pi->cmds[prn];
3506 char **argv = command->argv;
3507
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003508 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003509 lvl*2, "", prn,
3510 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003511#if ENABLE_HUSH_LINENO_VAR
3512 fdprintf(2, " LINENO:%u", command->lineno);
3513#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003514 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003515 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003516 CMDTYPE[command->cmd_type],
3517 argv
3518# if !BB_MMU
3519 , " group_as_string:", command->group_as_string
3520# else
3521 , "", ""
3522# endif
3523 );
3524 debug_print_tree(command->group, lvl+1);
3525 prn++;
3526 continue;
3527 }
3528 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003529 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003530 argv++;
3531 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003532 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003533 prn++;
3534 }
3535 pi = pi->next;
3536 pin++;
3537 }
3538}
3539#endif /* debug_print_tree */
3540
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003541static struct pipe *new_pipe(void)
3542{
Eric Andersen25f27032001-04-26 23:22:31 +00003543 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003544 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003545 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003546 return pi;
3547}
3548
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003549/* Command (member of a pipe) is complete, or we start a new pipe
3550 * if ctx->command is NULL.
3551 * No errors possible here.
3552 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003553static int done_command(struct parse_context *ctx)
3554{
3555 /* The command is really already in the pipe structure, so
3556 * advance the pipe counter and make a new, null command. */
3557 struct pipe *pi = ctx->pipe;
3558 struct command *command = ctx->command;
3559
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003560#if 0 /* Instead we emit error message at run time */
3561 if (ctx->pending_redirect) {
3562 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003563 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003564 ctx->pending_redirect = NULL;
3565 }
3566#endif
3567
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003568 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003569 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003570 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003571 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003572 }
3573 pi->num_cmds++;
3574 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003575 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003576 } else {
3577 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3578 }
3579
3580 /* Only real trickiness here is that the uncommitted
3581 * command structure is not counted in pi->num_cmds. */
3582 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003583 ctx->command = command = &pi->cmds[pi->num_cmds];
3584 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003585 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003586#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003587 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003588 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003589#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003590 return pi->num_cmds; /* used only for 0/nonzero check */
3591}
3592
3593static void done_pipe(struct parse_context *ctx, pipe_style type)
3594{
3595 int not_null;
3596
3597 debug_printf_parse("done_pipe entered, followup %d\n", type);
3598 /* Close previous command */
3599 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003600#if HAS_KEYWORDS
3601 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3602 ctx->ctx_inverted = 0;
3603 ctx->pipe->res_word = ctx->ctx_res_w;
3604#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003605 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3606 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003607 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3608 * in a backgrounded subshell.
3609 */
3610 struct pipe *pi;
3611 struct command *command;
3612
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003613 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003614 pi = ctx->list_head;
3615 while (pi != ctx->pipe) {
3616 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3617 goto no_conv;
3618 pi = pi->next;
3619 }
3620
3621 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3622 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3623 pi = xzalloc(sizeof(*pi));
3624 pi->followup = PIPE_BG;
3625 pi->num_cmds = 1;
3626 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3627 command = &pi->cmds[0];
3628 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3629 command->cmd_type = CMD_NORMAL;
3630 command->group = ctx->list_head;
3631#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003632 command->group_as_string = xstrndup(
3633 ctx->as_string.data,
3634 ctx->as_string.length - 1 /* do not copy last char, "&" */
3635 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003636#endif
3637 /* Replace all pipes in ctx with one newly created */
3638 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003639 } else {
3640 no_conv:
3641 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003642 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003643
3644 /* Without this check, even just <enter> on command line generates
3645 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003646 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003647 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003648#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003649 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003650#endif
3651#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003652 || ctx->ctx_res_w == RES_DONE
3653 || ctx->ctx_res_w == RES_FOR
3654 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003655#endif
3656#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003657 || ctx->ctx_res_w == RES_ESAC
3658#endif
3659 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003660 struct pipe *new_p;
3661 debug_printf_parse("done_pipe: adding new pipe: "
3662 "not_null:%d ctx->ctx_res_w:%d\n",
3663 not_null, ctx->ctx_res_w);
3664 new_p = new_pipe();
3665 ctx->pipe->next = new_p;
3666 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003667 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003668 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003669 * This is used to control execution.
3670 * RES_FOR and RES_IN are NOT sticky (needed to support
3671 * cases where variable or value happens to match a keyword):
3672 */
3673#if ENABLE_HUSH_LOOPS
3674 if (ctx->ctx_res_w == RES_FOR
3675 || ctx->ctx_res_w == RES_IN)
3676 ctx->ctx_res_w = RES_NONE;
3677#endif
3678#if ENABLE_HUSH_CASE
3679 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003680 ctx->ctx_res_w = RES_CASE_BODY;
3681 if (ctx->ctx_res_w == RES_CASE)
3682 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003683#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003684 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003685 /* Create the memory for command, roughly:
3686 * ctx->pipe->cmds = new struct command;
3687 * ctx->command = &ctx->pipe->cmds[0];
3688 */
3689 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003690 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003691 }
3692 debug_printf_parse("done_pipe return\n");
3693}
3694
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003695static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003696{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003697 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003698 if (MAYBE_ASSIGNMENT != 0)
3699 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003700 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003701 /* Create the memory for command, roughly:
3702 * ctx->pipe->cmds = new struct command;
3703 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003704 */
3705 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003706}
3707
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003708/* If a reserved word is found and processed, parse context is modified
3709 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003710 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003711#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003712struct reserved_combo {
3713 char literal[6];
3714 unsigned char res;
3715 unsigned char assignment_flag;
3716 int flag;
3717};
3718enum {
3719 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003720# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003721 FLAG_IF = (1 << RES_IF ),
3722 FLAG_THEN = (1 << RES_THEN ),
3723 FLAG_ELIF = (1 << RES_ELIF ),
3724 FLAG_ELSE = (1 << RES_ELSE ),
3725 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003726# endif
3727# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003728 FLAG_FOR = (1 << RES_FOR ),
3729 FLAG_WHILE = (1 << RES_WHILE),
3730 FLAG_UNTIL = (1 << RES_UNTIL),
3731 FLAG_DO = (1 << RES_DO ),
3732 FLAG_DONE = (1 << RES_DONE ),
3733 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003734# endif
3735# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003736 FLAG_MATCH = (1 << RES_MATCH),
3737 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003738# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003739 FLAG_START = (1 << RES_XXXX ),
3740};
3741
3742static const struct reserved_combo* match_reserved_word(o_string *word)
3743{
Eric Andersen25f27032001-04-26 23:22:31 +00003744 /* Mostly a list of accepted follow-up reserved words.
3745 * FLAG_END means we are done with the sequence, and are ready
3746 * to turn the compound list into a command.
3747 * FLAG_START means the word must start a new compound list.
3748 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003749 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003750# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003751 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3752 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3753 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3754 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3755 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3756 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003757# endif
3758# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003759 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3760 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3761 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3762 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3763 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3764 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003765# endif
3766# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003767 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3768 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003769# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003770 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003771 const struct reserved_combo *r;
3772
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003773 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003774 if (strcmp(word->data, r->literal) == 0)
3775 return r;
3776 }
3777 return NULL;
3778}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003779/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003780 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003781static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003782{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003783# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003784 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003785 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003786 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003787# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003788 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003789
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003790 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003791 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003792 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003793 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003794 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003795
3796 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003797# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003798 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3799 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003800 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003801 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003802# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003803 if (r->flag == 0) { /* '!' */
3804 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003805 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003806 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003807 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003808 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003809 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003810 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003811 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003812 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003813
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003814 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003815 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003816 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003817 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003818 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003819 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003820 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003821 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003822 } else {
3823 /* "{...} fi" is ok. "{...} if" is not
3824 * Example:
3825 * if { echo foo; } then { echo bar; } fi */
3826 if (ctx->command->group)
3827 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003828 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003829
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003830 ctx->ctx_res_w = r->res;
3831 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003832 ctx->is_assignment = r->assignment_flag;
3833 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003834
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003835 if (ctx->old_flag & FLAG_END) {
3836 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003837
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003838 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003839 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003840 old = ctx->stack;
3841 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003842 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003843# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003844 /* At this point, the compound command's string is in
3845 * ctx->as_string... except for the leading keyword!
3846 * Consider this example: "echo a | if true; then echo a; fi"
3847 * ctx->as_string will contain "true; then echo a; fi",
3848 * with "if " remaining in old->as_string!
3849 */
3850 {
3851 char *str;
3852 int len = old->as_string.length;
3853 /* Concatenate halves */
3854 o_addstr(&old->as_string, ctx->as_string.data);
3855 o_free_unsafe(&ctx->as_string);
3856 /* Find where leading keyword starts in first half */
3857 str = old->as_string.data + len;
3858 if (str > old->as_string.data)
3859 str--; /* skip whitespace after keyword */
3860 while (str > old->as_string.data && isalpha(str[-1]))
3861 str--;
3862 /* Ugh, we're done with this horrid hack */
3863 old->command->group_as_string = xstrdup(str);
3864 debug_printf_parse("pop, remembering as:'%s'\n",
3865 old->command->group_as_string);
3866 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003867# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003868 *ctx = *old; /* physical copy */
3869 free(old);
3870 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003871 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003872}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003873#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003874
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003875/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003876 * Normal return is 0. Syntax errors return 1.
3877 * Note: on return, word is reset, but not o_free'd!
3878 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003879static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003880{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003881 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003882
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003883 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3884 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003885 debug_printf_parse("done_word return 0: true null, ignored\n");
3886 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003887 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003888
Eric Andersen25f27032001-04-26 23:22:31 +00003889 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003890 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3891 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003892 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003893 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003894 * If the redirection operator is "<<" or "<<-", the word
3895 * that follows the redirection operator shall be
3896 * subjected to quote removal; it is unspecified whether
3897 * any of the other expansions occur. For the other
3898 * redirection operators, the word that follows the
3899 * redirection operator shall be subjected to tilde
3900 * expansion, parameter expansion, command substitution,
3901 * arithmetic expansion, and quote removal.
3902 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003903 * on the word by a non-interactive shell; an interactive
3904 * shell may perform it, but shall do so only when
3905 * the expansion would result in one word."
3906 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003907//bash does not do parameter/command substitution or arithmetic expansion
3908//for _heredoc_ redirection word: these constructs look for exact eof marker
3909// as written:
3910// <<EOF$t
3911// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003912// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3913
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003914 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003915 /* Cater for >\file case:
3916 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3917 * Same with heredocs:
3918 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3919 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003920 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3921 unbackslash(ctx->pending_redirect->rd_filename);
3922 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003923 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003924 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3925 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003926 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003927 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003928 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003929 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003930#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003931# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003932 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003933 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003934 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003935 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003936 /* ctx->ctx_res_w = RES_MATCH; */
3937 ctx->ctx_dsemicolon = 0;
3938 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003939# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003940 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003941# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003942 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3943 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003944# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003945# if ENABLE_HUSH_CASE
3946 && ctx->ctx_res_w != RES_CASE
3947# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003948 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003949 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003950 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003951 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003952 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003953# if ENABLE_HUSH_LINENO_VAR
3954/* Case:
3955 * "while ...; do
3956 * cmd ..."
3957 * If we don't close the pipe _now_, immediately after "do", lineno logic
3958 * sees "cmd" as starting at "do" - i.e., at the previous line.
3959 */
3960 if (0
3961 IF_HUSH_IF(|| reserved->res == RES_THEN)
3962 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3963 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3964 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3965 ) {
3966 done_pipe(ctx, PIPE_SEQ);
3967 }
3968# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003969 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003970 debug_printf_parse("done_word return %d\n",
3971 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003972 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003973 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003974# if defined(CMD_SINGLEWORD_NOGLOB)
3975 if (0
3976# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003977 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02003978# endif
3979 /* In bash, local/export/readonly are special, args
3980 * are assignments and therefore expansion of them
3981 * should be "one-word" expansion:
3982 * $ export i=`echo 'a b'` # one arg: "i=a b"
3983 * compare with:
3984 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3985 * ls: cannot access i=a: No such file or directory
3986 * ls: cannot access b: No such file or directory
3987 * Note: bash 3.2.33(1) does this only if export word
3988 * itself is not quoted:
3989 * $ export i=`echo 'aaa bbb'`; echo "$i"
3990 * aaa bbb
3991 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3992 * aaa
3993 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003994 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
3995 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
3996 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02003997 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003998 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3999 }
4000 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004001# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004002 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004003#endif /* HAS_KEYWORDS */
4004
Denis Vlasenkobb929512009-04-16 10:59:40 +00004005 if (command->group) {
4006 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004007 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004008 debug_printf_parse("done_word return 1: syntax error, "
4009 "groups and arglists don't mix\n");
4010 return 1;
4011 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004012
4013 /* If this word wasn't an assignment, next ones definitely
4014 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004015 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4016 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004017 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004018 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004019 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004020 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004021 command->assignment_cnt++;
4022 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4023 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004024 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4025 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004026 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004027 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4028 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004029 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004030 }
Eric Andersen25f27032001-04-26 23:22:31 +00004031
Denis Vlasenko06810332007-05-21 23:30:54 +00004032#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004033 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004034 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004035 || !is_well_formed_var_name(command->argv[0], '\0')
4036 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004037 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004038 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004039 return 1;
4040 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004041 /* Force FOR to have just one word (variable name) */
4042 /* NB: basically, this makes hush see "for v in ..."
4043 * syntax as if it is "for v; in ...". FOR and IN become
4044 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004045 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004046 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004047#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004048#if ENABLE_HUSH_CASE
4049 /* Force CASE to have just one word */
4050 if (ctx->ctx_res_w == RES_CASE) {
4051 done_pipe(ctx, PIPE_SEQ);
4052 }
4053#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004054
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004055 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004056
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004057 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004058 return 0;
4059}
4060
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004061
4062/* Peek ahead in the input to find out if we have a "&n" construct,
4063 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004064 * Return:
4065 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4066 * REDIRFD_SYNTAX_ERR if syntax error,
4067 * REDIRFD_TO_FILE if no & was seen,
4068 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004069 */
4070#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004071#define parse_redir_right_fd(as_string, input) \
4072 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004073#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004074static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004075{
4076 int ch, d, ok;
4077
4078 ch = i_peek(input);
4079 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004080 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004081
4082 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004083 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004084 ch = i_peek(input);
4085 if (ch == '-') {
4086 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004087 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004088 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004089 }
4090 d = 0;
4091 ok = 0;
4092 while (ch != EOF && isdigit(ch)) {
4093 d = d*10 + (ch-'0');
4094 ok = 1;
4095 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004096 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004097 ch = i_peek(input);
4098 }
4099 if (ok) return d;
4100
4101//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4102
4103 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004104 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004105}
4106
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004107/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004108 */
4109static int parse_redirect(struct parse_context *ctx,
4110 int fd,
4111 redir_type style,
4112 struct in_str *input)
4113{
4114 struct command *command = ctx->command;
4115 struct redir_struct *redir;
4116 struct redir_struct **redirp;
4117 int dup_num;
4118
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004119 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004120 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004121 /* Check for a '>&1' type redirect */
4122 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4123 if (dup_num == REDIRFD_SYNTAX_ERR)
4124 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004125 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004126 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004127 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004128 if (dup_num) { /* <<-... */
4129 ch = i_getch(input);
4130 nommu_addchr(&ctx->as_string, ch);
4131 ch = i_peek(input);
4132 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004133 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004134
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004135 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004136 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004137 if (ch == '|') {
4138 /* >|FILE redirect ("clobbering" >).
4139 * Since we do not support "set -o noclobber" yet,
4140 * >| and > are the same for now. Just eat |.
4141 */
4142 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004143 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004144 }
4145 }
4146
4147 /* Create a new redir_struct and append it to the linked list */
4148 redirp = &command->redirects;
4149 while ((redir = *redirp) != NULL) {
4150 redirp = &(redir->next);
4151 }
4152 *redirp = redir = xzalloc(sizeof(*redir));
4153 /* redir->next = NULL; */
4154 /* redir->rd_filename = NULL; */
4155 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004156 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004157
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004158 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4159 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004160
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004161 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004162 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004163 /* Erik had a check here that the file descriptor in question
4164 * is legit; I postpone that to "run time"
4165 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004166 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4167 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004168 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004169#if 0 /* Instead we emit error message at run time */
4170 if (ctx->pending_redirect) {
4171 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004172 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004173 }
4174#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 /* Set ctx->pending_redirect, so we know what to do at the
4176 * end of the next parsed word. */
4177 ctx->pending_redirect = redir;
4178 }
4179 return 0;
4180}
4181
Eric Andersen25f27032001-04-26 23:22:31 +00004182/* If a redirect is immediately preceded by a number, that number is
4183 * supposed to tell which file descriptor to redirect. This routine
4184 * looks for such preceding numbers. In an ideal world this routine
4185 * needs to handle all the following classes of redirects...
4186 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4187 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4188 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4189 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004190 *
4191 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4192 * "2.7 Redirection
4193 * ... If n is quoted, the number shall not be recognized as part of
4194 * the redirection expression. For example:
4195 * echo \2>a
4196 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004197 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004198 *
4199 * A -1 return means no valid number was found,
4200 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004201 */
4202static int redirect_opt_num(o_string *o)
4203{
4204 int num;
4205
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004206 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004207 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004208 num = bb_strtou(o->data, NULL, 10);
4209 if (errno || num < 0)
4210 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004211 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004212 return num;
4213}
4214
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004215#if BB_MMU
4216#define fetch_till_str(as_string, input, word, skip_tabs) \
4217 fetch_till_str(input, word, skip_tabs)
4218#endif
4219static char *fetch_till_str(o_string *as_string,
4220 struct in_str *input,
4221 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004222 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004223{
4224 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004225 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004226 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004227 int ch;
4228
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004229 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004230
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004231 while (1) {
4232 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004233 if (ch != EOF)
4234 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004235 if (ch == '\n' || ch == EOF) {
4236 check_heredoc_end:
4237 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4238 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4239 heredoc.data[past_EOL] = '\0';
4240 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4241 return heredoc.data;
4242 }
4243 if (ch == '\n') {
4244 /* This is a new line.
4245 * Remember position and backslash-escaping status.
4246 */
4247 o_addchr(&heredoc, ch);
4248 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004249 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004250 past_EOL = heredoc.length;
4251 /* Get 1st char of next line, possibly skipping leading tabs */
4252 do {
4253 ch = i_getch(input);
4254 if (ch != EOF)
4255 nommu_addchr(as_string, ch);
4256 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4257 /* If this immediately ended the line,
4258 * go back to end-of-line checks.
4259 */
4260 if (ch == '\n')
4261 goto check_heredoc_end;
4262 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004263 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004264 }
4265 if (ch == EOF) {
4266 o_free_unsafe(&heredoc);
4267 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004268 }
4269 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004270 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004271 if (prev == '\\' && ch == '\\')
4272 /* Correctly handle foo\\<eol> (not a line cont.) */
4273 prev = 0; /* not \ */
4274 else
4275 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004276 }
4277}
4278
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004279/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4280 * and load them all. There should be exactly heredoc_cnt of them.
4281 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004282static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4283{
4284 struct pipe *pi = ctx->list_head;
4285
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004286 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004287 int i;
4288 struct command *cmd = pi->cmds;
4289
4290 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4291 pi->num_cmds,
4292 cmd->argv ? cmd->argv[0] : "NONE");
4293 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004294 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004295
4296 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4297 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004298 while (redir) {
4299 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004300 char *p;
4301
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004302 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004303 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004304 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004305 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004306 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004307 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004308 return 1;
4309 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004310 free(redir->rd_filename);
4311 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004312 heredoc_cnt--;
4313 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004314 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004315 }
4316 cmd++;
4317 }
4318 pi = pi->next;
4319 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004320#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004321 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004322 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004323 bb_error_msg_and_die("heredoc BUG 2");
4324#endif
4325 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004326}
4327
4328
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004329static int run_list(struct pipe *pi);
4330#if BB_MMU
4331#define parse_stream(pstring, input, end_trigger) \
4332 parse_stream(input, end_trigger)
4333#endif
4334static struct pipe *parse_stream(char **pstring,
4335 struct in_str *input,
4336 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004337
Eric Andersen25f27032001-04-26 23:22:31 +00004338
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004339static int parse_group(struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004340 struct in_str *input, int ch)
4341{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004342 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004343 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004344 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004345#if BB_MMU
4346# define as_string NULL
4347#else
4348 char *as_string = NULL;
4349#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004350 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004351 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004352 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004353
4354 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004355#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004356 if (ch == '(' && !ctx->word.has_quoted_part) {
4357 if (ctx->word.length)
4358 if (done_word(ctx))
Denis Vlasenkobb929512009-04-16 10:59:40 +00004359 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004360 if (!command->argv)
4361 goto skip; /* (... */
4362 if (command->argv[1]) { /* word word ... (... */
4363 syntax_error_unexpected_ch('(');
4364 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004365 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004366 /* it is "word(..." or "word (..." */
4367 do
4368 ch = i_getch(input);
4369 while (ch == ' ' || ch == '\t');
4370 if (ch != ')') {
4371 syntax_error_unexpected_ch(ch);
4372 return 1;
4373 }
4374 nommu_addchr(&ctx->as_string, ch);
4375 do
4376 ch = i_getch(input);
4377 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004378 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004379 syntax_error_unexpected_ch(ch);
4380 return 1;
4381 }
4382 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004383 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004384 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004385 }
4386#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004387
4388#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004389 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004390 || ctx->word.length /* word{... */
4391 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004392 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004393 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004394 debug_printf_parse("parse_group return 1: "
4395 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004396 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004397 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004398#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004399
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004400 IF_HUSH_FUNCTIONS(skip:)
4401
Denis Vlasenko240c2552009-04-03 03:45:05 +00004402 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004403 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004404 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004405 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4406 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004407 } else {
4408 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004409 ch = i_peek(input);
4410 if (ch != ' ' && ch != '\t' && ch != '\n'
4411 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4412 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004413 syntax_error_unexpected_ch(ch);
4414 return 1;
4415 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004416 if (ch != '(') {
4417 ch = i_getch(input);
4418 nommu_addchr(&ctx->as_string, ch);
4419 }
Eric Andersen25f27032001-04-26 23:22:31 +00004420 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004421
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004422 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004423#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004424 if (as_string)
4425 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004426#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004427
4428 /* empty ()/{} or parse error? */
4429 if (!pipe_list || pipe_list == ERR_PTR) {
4430 /* parse_stream already emitted error msg */
4431 if (!BB_MMU)
4432 free(as_string);
4433 debug_printf_parse("parse_group return 1: "
4434 "parse_stream returned %p\n", pipe_list);
4435 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004436 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004437#if !BB_MMU
4438 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4439 command->group_as_string = as_string;
4440 debug_printf_parse("end of group, remembering as:'%s'\n",
4441 command->group_as_string);
4442#endif
4443
4444#if ENABLE_HUSH_FUNCTIONS
4445 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4446 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4447 struct command *cmd2;
4448
4449 cmd2 = xzalloc(sizeof(*cmd2));
4450 cmd2->cmd_type = CMD_SUBSHELL;
4451 cmd2->group = pipe_list;
4452# if !BB_MMU
4453//UNTESTED!
4454 cmd2->group_as_string = command->group_as_string;
4455 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4456# endif
4457
4458 pipe_list = new_pipe();
4459 pipe_list->cmds = cmd2;
4460 pipe_list->num_cmds = 1;
4461 }
4462#endif
4463
4464 command->group = pipe_list;
4465
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004466 debug_printf_parse("parse_group return 0\n");
4467 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004468 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004469#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004470}
4471
Denys Vlasenko0b883582016-12-23 16:49:07 +01004472#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004473/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004474static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004475/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004476static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004477{
4478 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004479 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004480 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004481 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004482 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004483 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004484 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004485 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004486 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004487 }
4488}
4489/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004490static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004491{
4492 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004493 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004494 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004495 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004496 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004497 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004498 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004499 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004500 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004501 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004502 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004503 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004504 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004505 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004506 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4507 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004508 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004509 continue;
4510 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004511 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004512 }
4513}
4514/* Process `cmd` - copy contents until "`" is seen. Complicated by
4515 * \` quoting.
4516 * "Within the backquoted style of command substitution, backslash
4517 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4518 * The search for the matching backquote shall be satisfied by the first
4519 * backquote found without a preceding backslash; during this search,
4520 * if a non-escaped backquote is encountered within a shell comment,
4521 * a here-document, an embedded command substitution of the $(command)
4522 * form, or a quoted string, undefined results occur. A single-quoted
4523 * or double-quoted string that begins, but does not end, within the
4524 * "`...`" sequence produces undefined results."
4525 * Example Output
4526 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4527 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004528static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004529{
4530 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004531 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004532 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004533 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004534 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004535 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4536 ch = i_getch(input);
4537 if (ch != '`'
4538 && ch != '$'
4539 && ch != '\\'
4540 && (!in_dquote || ch != '"')
4541 ) {
4542 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004543 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004544 }
4545 if (ch == EOF) {
4546 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004547 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004548 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004549 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004550 }
4551}
4552/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4553 * quoting and nested ()s.
4554 * "With the $(command) style of command substitution, all characters
4555 * following the open parenthesis to the matching closing parenthesis
4556 * constitute the command. Any valid shell script can be used for command,
4557 * except a script consisting solely of redirections which produces
4558 * unspecified results."
4559 * Example Output
4560 * echo $(echo '(TEST)' BEST) (TEST) BEST
4561 * echo $(echo 'TEST)' BEST) TEST) BEST
4562 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004563 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004564 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004565 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004566 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4567 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004568 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004569#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004570static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004571{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004572 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004573 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004574# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004575 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004576# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004577 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4578
Denys Vlasenko817a2022018-06-26 15:35:17 +02004579#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004580 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004581#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004582 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4583
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004584 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004585 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004586 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004587 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004588 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004589 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004590 if (ch == end_ch
4591# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004592 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004593# endif
4594 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004595 if (!dbl)
4596 break;
4597 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004598 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004599 i_getch(input); /* eat second ')' */
4600 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004601 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004602 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004603 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004604 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004605 if (ch == '(' || ch == '{') {
4606 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004607 if (!add_till_closing_bracket(dest, input, ch))
4608 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004609 o_addchr(dest, ch);
4610 continue;
4611 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004612 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004613 if (!add_till_single_quote(dest, input))
4614 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004615 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004616 continue;
4617 }
4618 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004619 if (!add_till_double_quote(dest, input))
4620 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004621 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004622 continue;
4623 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004624 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004625 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4626 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004627 o_addchr(dest, ch);
4628 continue;
4629 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004630 if (ch == '\\') {
4631 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004632 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004633 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004634 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004635 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004636 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004637#if 0
4638 if (ch == '\n') {
4639 /* "backslash+newline", ignore both */
4640 o_delchr(dest); /* undo insertion of '\' */
4641 continue;
4642 }
4643#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004644 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004645 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004646 continue;
4647 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004648 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004649 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004650 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004651}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004652#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004653
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004654/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004655#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004656#define parse_dollar(as_string, dest, input, quote_mask) \
4657 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004658#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004659#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004660static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004661 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004662 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004663{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004664 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004665
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004666 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004667 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004668 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004669 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004670 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004671 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004673 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004674 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004675 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004676 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004677 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004678 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004679 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004680 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004681 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004682 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004683 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004684 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004685 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004686 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004687 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004688 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004689 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004690 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004691 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004692 o_addchr(dest, ch | quote_mask);
4693 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004694 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004695 case '$': /* pid */
4696 case '!': /* last bg pid */
4697 case '?': /* last exit code */
4698 case '#': /* number of args */
4699 case '*': /* args */
4700 case '@': /* args */
4701 goto make_one_char_var;
4702 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004703 char len_single_ch;
4704
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4706
Denys Vlasenko74369502010-05-21 19:52:01 +02004707 ch = i_getch(input); /* eat '{' */
4708 nommu_addchr(as_string, ch);
4709
Denys Vlasenko46e64982016-09-29 19:50:55 +02004710 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004711 /* It should be ${?}, or ${#var},
4712 * or even ${?+subst} - operator acting on a special variable,
4713 * or the beginning of variable name.
4714 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004715 if (ch == EOF
4716 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4717 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004718 bad_dollar_syntax:
4719 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004720 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4721 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004722 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004723 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004724 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004725 ch |= quote_mask;
4726
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004727 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004728 * However, this regresses some of our testsuite cases
4729 * which check invalid constructs like ${%}.
4730 * Oh well... let's check that the var name part is fine... */
4731
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004732 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004733 unsigned pos;
4734
Denys Vlasenko74369502010-05-21 19:52:01 +02004735 o_addchr(dest, ch);
4736 debug_printf_parse(": '%c'\n", ch);
4737
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004738 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004739 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004740 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004741 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004742
Denys Vlasenko74369502010-05-21 19:52:01 +02004743 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004744 unsigned end_ch;
4745 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004746 /* handle parameter expansions
4747 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4748 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004749 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4750 if (len_single_ch != '#'
4751 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4752 || i_peek(input) != '}'
4753 ) {
4754 goto bad_dollar_syntax;
4755 }
4756 /* else: it's "length of C" ${#C} op,
4757 * where C is a single char
4758 * special var name, e.g. ${#!}.
4759 */
4760 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004761 /* Eat everything until closing '}' (or ':') */
4762 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004763 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004764 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004765 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004766 ) {
4767 /* It's ${var:N[:M]} thing */
4768 end_ch = '}' * 0x100 + ':';
4769 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004770 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004771 && ch == '/'
4772 ) {
4773 /* It's ${var/[/]pattern[/repl]} thing */
4774 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4775 i_getch(input);
4776 nommu_addchr(as_string, '/');
4777 ch = '\\';
4778 }
4779 end_ch = '}' * 0x100 + '/';
4780 }
4781 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004782 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004783 if (!BB_MMU)
4784 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004785#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004786 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004787 if (last_ch == 0) /* error? */
4788 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004789#else
4790#error Simple code to only allow ${var} is not implemented
4791#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004792 if (as_string) {
4793 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004794 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004795 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004796
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004797 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4798 && (end_ch & 0xff00)
4799 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004800 /* close the first block: */
4801 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004802 /* while parsing N from ${var:N[:M]}
4803 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004804 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004805 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004806 end_ch = '}';
4807 goto again;
4808 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004809 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004810 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004811 /* it's ${var:N} - emulate :999999999 */
4812 o_addstr(dest, "999999999");
4813 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004814 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004815 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004816 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004817 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004818 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004819 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4820 break;
4821 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004822#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004823 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004824 unsigned pos;
4825
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004826 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004827 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004828# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004829 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004830 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004831 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004832 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4833 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004834 if (!BB_MMU)
4835 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004836 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4837 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004838 if (as_string) {
4839 o_addstr(as_string, dest->data + pos);
4840 o_addchr(as_string, ')');
4841 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004842 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004843 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004844 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004845 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004846# endif
4847# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004848 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4849 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004850 if (!BB_MMU)
4851 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004852 if (!add_till_closing_bracket(dest, input, ')'))
4853 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004854 if (as_string) {
4855 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004856 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004857 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004858 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004859# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004860 break;
4861 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004862#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004863 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004864 goto make_var;
4865#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004866 /* TODO: $_ and $-: */
4867 /* $_ Shell or shell script name; or last argument of last command
4868 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4869 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004870 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004871 ch = i_getch(input);
4872 nommu_addchr(as_string, ch);
4873 ch = i_peek_and_eat_bkslash_nl(input);
4874 if (isalnum(ch)) { /* it's $_name or $_123 */
4875 ch = '_';
4876 goto make_var1;
4877 }
4878 /* else: it's $_ */
4879#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004880 default:
4881 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004882 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004883 debug_printf_parse("parse_dollar return 1 (ok)\n");
4884 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004885#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004886}
4887
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004888#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02004889#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004890 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004891#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004892#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004893static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004894 o_string *dest,
4895 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02004896 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004897{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004898 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004899 int next;
4900
4901 again:
4902 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004903 if (ch != EOF)
4904 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004905 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004906 debug_printf_parse("encode_string return 1 (ok)\n");
4907 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004908 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004909 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004910 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004911 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004912 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004913 }
4914 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004915 if (ch != '\n') {
4916 next = i_peek(input);
4917 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004918 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004919 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02004920 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004921 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02004922 /* Testcase: in interactive shell a file with
4923 * echo "unterminated string\<eof>
4924 * is sourced.
4925 */
4926 syntax_error_unterm_ch('"');
4927 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004928 }
4929 /* bash:
4930 * "The backslash retains its special meaning [in "..."]
4931 * only when followed by one of the following characters:
4932 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004933 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004934 * NB: in (unquoted) heredoc, above does not apply to ",
4935 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004936 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004937 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004938 ch = i_getch(input); /* eat next */
4939 if (ch == '\n')
4940 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004941 } /* else: ch remains == '\\', and we double it below: */
4942 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004943 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004944 goto again;
4945 }
4946 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004947 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4948 debug_printf_parse("encode_string return 0: "
4949 "parse_dollar returned 0 (error)\n");
4950 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004951 }
4952 goto again;
4953 }
4954#if ENABLE_HUSH_TICK
4955 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004956 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004957 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4958 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004959 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4960 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004961 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4962 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004963 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004964 }
4965#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004966 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004967 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004968#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004969}
4970
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004971/*
4972 * Scan input until EOF or end_trigger char.
4973 * Return a list of pipes to execute, or NULL on EOF
4974 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004975 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004976 * reset parsing machinery and start parsing anew,
4977 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004978 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004979static struct pipe *parse_stream(char **pstring,
4980 struct in_str *input,
4981 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004982{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004983 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004984 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004985
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004986 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004987 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004988 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004989 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004990 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004991 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004992
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004993 initialize_context(&ctx);
4994
4995 /* If very first arg is "" or '', ctx.word.data may end up NULL.
4996 * Preventing this:
4997 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02004998 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004999
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005000 /* We used to separate words on $IFS here. This was wrong.
5001 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005002 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005003 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005004
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005005 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005006 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005007 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005008 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005009 int ch;
5010 int next;
5011 int redir_fd;
5012 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005013
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005014 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005015 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005016 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005017 if (ch == EOF) {
5018 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005019
5020 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005021 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005022 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005023 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005024 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005025 syntax_error_unterm_ch('(');
5026 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005027 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005028 if (end_trigger == '}') {
5029 syntax_error_unterm_ch('{');
5030 goto parse_error;
5031 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005032
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005033 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005034 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005035 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005036 o_free(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005037 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005038 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005039 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005040 /* (this makes bare "&" cmd a no-op.
5041 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005042 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005043 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005044 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005045 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005046 pi = NULL;
5047 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005048#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005049 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005050 if (pstring)
5051 *pstring = ctx.as_string.data;
5052 else
5053 o_free_unsafe(&ctx.as_string);
5054#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005055 debug_leave();
5056 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005057 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005058 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005059
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005060 /* Handle "'" and "\" first, as they won't play nice with
5061 * i_peek_and_eat_bkslash_nl() anyway:
5062 * echo z\\
5063 * and
5064 * echo '\
5065 * '
5066 * would break.
5067 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005068 if (ch == '\\') {
5069 ch = i_getch(input);
5070 if (ch == '\n')
5071 continue; /* drop \<newline>, get next char */
5072 nommu_addchr(&ctx.as_string, '\\');
5073 o_addchr(&ctx.word, '\\');
5074 if (ch == EOF) {
5075 /* Testcase: eval 'echo Ok\' */
5076 /* bash-4.3.43 was removing backslash,
5077 * but 4.4.19 retains it, most other shells too
5078 */
5079 continue; /* get next char */
5080 }
5081 /* Example: echo Hello \2>file
5082 * we need to know that word 2 is quoted
5083 */
5084 ctx.word.has_quoted_part = 1;
5085 nommu_addchr(&ctx.as_string, ch);
5086 o_addchr(&ctx.word, ch);
5087 continue; /* get next char */
5088 }
5089 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005090 if (ch == '\'') {
5091 ctx.word.has_quoted_part = 1;
5092 next = i_getch(input);
5093 if (next == '\'' && !ctx.pending_redirect)
5094 goto insert_empty_quoted_str_marker;
5095
5096 ch = next;
5097 while (1) {
5098 if (ch == EOF) {
5099 syntax_error_unterm_ch('\'');
5100 goto parse_error;
5101 }
5102 nommu_addchr(&ctx.as_string, ch);
5103 if (ch == '\'')
5104 break;
5105 if (ch == SPECIAL_VAR_SYMBOL) {
5106 /* Convert raw ^C to corresponding special variable reference */
5107 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5108 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5109 }
5110 o_addqchr(&ctx.word, ch);
5111 ch = i_getch(input);
5112 }
5113 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005114 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005115
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005116 next = '\0';
5117 if (ch != '\n')
5118 next = i_peek_and_eat_bkslash_nl(input);
5119
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005120 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005121 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005122 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005123 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005124 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005125 || ctx.word.length /* word{... - non-special */
5126 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005127 || (next != ';' /* }; - special */
5128 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005129 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005130 && next != '&' /* }& and }&& ... - special */
5131 && next != '|' /* }|| ... - special */
5132 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005133 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005134 ) {
5135 /* They are not special, skip "{}" */
5136 is_special += 2;
5137 }
5138 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005139 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005140
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005141 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005142 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005143 o_addQchr(&ctx.word, ch);
5144 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5145 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005146 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005147 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005148 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005149 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5150 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005151 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005152 continue;
5153 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005154
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005155 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005156#if ENABLE_HUSH_LINENO_VAR
5157/* Case:
5158 * "while ...; do<whitespace><newline>
5159 * cmd ..."
5160 * would think that "cmd" starts in <whitespace> -
5161 * i.e., at the previous line.
5162 * We need to skip all whitespace before newlines.
5163 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005164 while (ch != '\n') {
5165 next = i_peek(input);
5166 if (next != ' ' && next != '\t' && next != '\n')
5167 break; /* next char is not ws */
5168 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005169 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005170 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005171#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005172 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005173 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005174 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005175 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005176 /* Is this a case when newline is simply ignored?
5177 * Some examples:
5178 * "cmd | <newline> cmd ..."
5179 * "case ... in <newline> word) ..."
5180 */
5181 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005182 && ctx.word.length == 0 && !ctx.word.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005183 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005184 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005185 * Without check #1, interactive shell
5186 * ignores even bare <newline>,
5187 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005188 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005189 * ps2> _ <=== wrong, should be ps1
5190 * Without check #2, "cmd & <newline>"
5191 * is similarly mistreated.
5192 * (BTW, this makes "cmd & cmd"
5193 * and "cmd && cmd" non-orthogonal.
5194 * Really, ask yourself, why
5195 * "cmd && <newline>" doesn't start
5196 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005197 * The only reason is that it might be
5198 * a "cmd1 && <nl> cmd2 &" construct,
5199 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005200 */
5201 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005202 if (pi->num_cmds != 0 /* check #1 */
5203 && pi->followup != PIPE_BG /* check #2 */
5204 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005205 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005206 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005207 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005208 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005209 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005210 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5211 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005212 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005213 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005214 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005215 heredoc_cnt = 0;
5216 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005217 ctx.is_assignment = MAYBE_ASSIGNMENT;
5218 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005219 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005220 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005221 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005222 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005223 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005224
5225 /* "cmd}" or "cmd }..." without semicolon or &:
5226 * } is an ordinary char in this case, even inside { cmd; }
5227 * Pathological example: { ""}; } should exec "}" cmd
5228 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005229 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005230 if (ctx.word.length != 0 /* word} */
5231 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005232 ) {
5233 goto ordinary_char;
5234 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005235 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5236 /* Generally, there should be semicolon: "cmd; }"
5237 * However, bash allows to omit it if "cmd" is
5238 * a group. Examples:
5239 * { { echo 1; } }
5240 * {(echo 1)}
5241 * { echo 0 >&2 | { echo 1; } }
5242 * { while false; do :; done }
5243 * { case a in b) ;; esac }
5244 */
5245 if (ctx.command->group)
5246 goto term_group;
5247 goto ordinary_char;
5248 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005249 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005250 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005251 goto skip_end_trigger;
5252 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005253 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005254 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005255 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005256 && (ch != ';' || heredoc_cnt == 0)
5257#if ENABLE_HUSH_CASE
5258 && (ch != ')'
5259 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005260 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005261 )
5262#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005263 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005264 if (heredoc_cnt) {
5265 /* This is technically valid:
5266 * { cat <<HERE; }; echo Ok
5267 * heredoc
5268 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005269 * HERE
5270 * but we don't support this.
5271 * We require heredoc to be in enclosing {}/(),
5272 * if any.
5273 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005274 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005275 goto parse_error;
5276 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005277 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005278 goto parse_error;
5279 }
5280 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005281 ctx.is_assignment = MAYBE_ASSIGNMENT;
5282 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005283 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005284 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005285 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005286 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005287 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005288#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005289 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005290 if (pstring)
5291 *pstring = ctx.as_string.data;
5292 else
5293 o_free_unsafe(&ctx.as_string);
5294#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005295 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5296 /* Example: bare "{ }", "()" */
5297 G.last_exitcode = 2; /* bash compat */
5298 syntax_error_unexpected_ch(ch);
5299 goto parse_error2;
5300 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005301 debug_printf_parse("parse_stream return %p: "
5302 "end_trigger char found\n",
5303 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005304 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005305 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005306 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005307 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005308
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005309 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005310 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005311
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005312 /* Catch <, > before deciding whether this word is
5313 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5314 switch (ch) {
5315 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005316 redir_fd = redirect_opt_num(&ctx.word);
5317 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005318 goto parse_error;
5319 }
5320 redir_style = REDIRECT_OVERWRITE;
5321 if (next == '>') {
5322 redir_style = REDIRECT_APPEND;
5323 ch = i_getch(input);
5324 nommu_addchr(&ctx.as_string, ch);
5325 }
5326#if 0
5327 else if (next == '(') {
5328 syntax_error(">(process) not supported");
5329 goto parse_error;
5330 }
5331#endif
5332 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5333 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005334 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005335 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005336 redir_fd = redirect_opt_num(&ctx.word);
5337 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005338 goto parse_error;
5339 }
5340 redir_style = REDIRECT_INPUT;
5341 if (next == '<') {
5342 redir_style = REDIRECT_HEREDOC;
5343 heredoc_cnt++;
5344 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5345 ch = i_getch(input);
5346 nommu_addchr(&ctx.as_string, ch);
5347 } else if (next == '>') {
5348 redir_style = REDIRECT_IO;
5349 ch = i_getch(input);
5350 nommu_addchr(&ctx.as_string, ch);
5351 }
5352#if 0
5353 else if (next == '(') {
5354 syntax_error("<(process) not supported");
5355 goto parse_error;
5356 }
5357#endif
5358 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5359 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005360 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005361 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005362 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005363 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005364 /* note: we do not add it to &ctx.as_string */
5365/* TODO: in bash:
5366 * comment inside $() goes to the next \n, even inside quoted string (!):
5367 * cmd "$(cmd2 #comment)" - syntax error
5368 * cmd "`cmd2 #comment`" - ok
5369 * We accept both (comment ends where command subst ends, in both cases).
5370 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005371 while (1) {
5372 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005373 if (ch == '\n') {
5374 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005375 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005376 }
5377 ch = i_getch(input);
5378 if (ch == EOF)
5379 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005380 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005381 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005382 }
5383 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005384 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005385 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005386
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005387 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005388 /* check that we are not in word in "a=1 2>word b=1": */
5389 && !ctx.pending_redirect
5390 ) {
5391 /* ch is a special char and thus this word
5392 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005393 ctx.is_assignment = NOT_ASSIGNMENT;
5394 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005395 }
5396
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005397 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5398
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005399 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005400 case SPECIAL_VAR_SYMBOL:
5401 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005402 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5403 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005404 /* fall through */
5405 case '#':
5406 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005407 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005408 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005409 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005410 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005411 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005412 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005413 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005414 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005415 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005416 case '"':
5417 ctx.word.has_quoted_part = 1;
5418 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005419 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005420 insert_empty_quoted_str_marker:
5421 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005422 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5423 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005424 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005425 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005426 if (ctx.is_assignment == NOT_ASSIGNMENT)
5427 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005428 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005429 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005430 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005431 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005432#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005433 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005434 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005435
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005436 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5437 o_addchr(&ctx.word, '`');
5438 USE_FOR_NOMMU(pos = ctx.word.length;)
5439 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005440 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005441# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005442 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005443 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005444# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005445 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5446 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005447 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005448 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005449#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005450 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005451#if ENABLE_HUSH_CASE
5452 case_semi:
5453#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005454 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005455 goto parse_error;
5456 }
5457 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005458#if ENABLE_HUSH_CASE
5459 /* Eat multiple semicolons, detect
5460 * whether it means something special */
5461 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005462 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005463 if (ch != ';')
5464 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005465 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005466 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005467 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005468 ctx.ctx_dsemicolon = 1;
5469 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005470 break;
5471 }
5472 }
5473#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005474 new_cmd:
5475 /* We just finished a cmd. New one may start
5476 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005477 ctx.is_assignment = MAYBE_ASSIGNMENT;
5478 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005479 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005480 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005481 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005482 goto parse_error;
5483 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005484 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005485 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005486 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005487 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005488 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005489 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005490 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005491 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005492 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005493 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005494 goto parse_error;
5495 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005496#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005497 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005498 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005499#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005500 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005501 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005502 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005503 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005504 } else {
5505 /* we could pick up a file descriptor choice here
5506 * with redirect_opt_num(), but bash doesn't do it.
5507 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005508 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005509 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005510 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005511 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005512#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005513 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005514 if (ctx.ctx_res_w == RES_MATCH
5515 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005516 && ctx.word.length == 0 /* not word(... */
5517 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005518 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005519 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005520 }
5521#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005522 case '{':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005523 if (parse_group(&ctx, input, ch) != 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005524 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005525 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005526 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005527 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005528#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005529 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005530 goto case_semi;
5531#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005532 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005533 /* proper use of this character is caught by end_trigger:
5534 * if we see {, we call parse_group(..., end_trigger='}')
5535 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005536 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005537 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005538 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005539 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005540 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005541 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005542 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005543 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005544
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005545 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005546 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005547 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005548 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005549 struct parse_context *pctx;
5550 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005551
5552 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005553 * Sample for finding leaks on syntax error recovery path.
5554 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005555 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005556 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005557 * while if (true | { true;}); then echo ok; fi; do break; done
5558 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005559 */
5560 pctx = &ctx;
5561 do {
5562 /* Update pipe/command counts,
5563 * otherwise freeing may miss some */
5564 done_pipe(pctx, PIPE_SEQ);
5565 debug_printf_clean("freeing list %p from ctx %p\n",
5566 pctx->list_head, pctx);
5567 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005568 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005569 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005570#if !BB_MMU
5571 o_free_unsafe(&pctx->as_string);
5572#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005573 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005574 if (pctx != &ctx) {
5575 free(pctx);
5576 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005577 IF_HAS_KEYWORDS(pctx = p2;)
5578 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005579
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005580 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005581#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005582 if (pstring)
5583 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005584#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005585 debug_leave();
5586 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005587 }
Eric Andersen25f27032001-04-26 23:22:31 +00005588}
5589
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005590
5591/*** Execution routines ***/
5592
5593/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005594#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005595#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005596 expand_string_to_string(str)
5597#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005598static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005599#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005600static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005601#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005602
5603/* expand_strvec_to_strvec() takes a list of strings, expands
5604 * all variable references within and returns a pointer to
5605 * a list of expanded strings, possibly with larger number
5606 * of strings. (Think VAR="a b"; echo $VAR).
5607 * This new list is allocated as a single malloc block.
5608 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005609 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005610 * Caller can deallocate entire list by single free(list). */
5611
Denys Vlasenko238081f2010-10-03 14:26:26 +02005612/* A horde of its helpers come first: */
5613
5614static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5615{
5616 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005617 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005618
Denys Vlasenko9e800222010-10-03 14:28:04 +02005619#if ENABLE_HUSH_BRACE_EXPANSION
5620 if (c == '{' || c == '}') {
5621 /* { -> \{, } -> \} */
5622 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005623 /* And now we want to add { or } and continue:
5624 * o_addchr(o, c);
5625 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005626 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005627 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005628 }
5629#endif
5630 o_addchr(o, c);
5631 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005632 /* \z -> \\\z; \<eol> -> \\<eol> */
5633 o_addchr(o, '\\');
5634 if (len) {
5635 len--;
5636 o_addchr(o, '\\');
5637 o_addchr(o, *str++);
5638 }
5639 }
5640 }
5641}
5642
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005643/* Store given string, finalizing the word and starting new one whenever
5644 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005645 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005646 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005647 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5648 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005649static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005650{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005651 int last_is_ifs = 0;
5652
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005653 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005654 int word_len;
5655
5656 if (!*str) /* EOL - do not finalize word */
5657 break;
5658 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005659 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005660 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005661 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005662 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005663 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005664 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005665 * Example: "v='\*'; echo b$v" prints "b\*"
5666 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005667 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005668 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005669 /*/ Why can't we do it easier? */
5670 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5671 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5672 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005673 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005674 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005675 if (!*str) /* EOL - do not finalize word */
5676 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005677 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005678
5679 /* We know str here points to at least one IFS char */
5680 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005681 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005682 if (!*str) /* EOL - do not finalize word */
5683 break;
5684
Denys Vlasenko96786362018-04-11 16:02:58 +02005685 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5686 && strchr(G.ifs, *str) /* the second check would fail */
5687 ) {
5688 /* This is a non-whitespace $IFS char */
5689 /* Skip it and IFS whitespace chars, start new word */
5690 str++;
5691 str += strspn(str, G.ifs_whitespace);
5692 goto new_word;
5693 }
5694
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005695 /* Start new word... but not always! */
5696 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005697 if (output->has_quoted_part
5698 /* Case "v=' a'; echo $v":
5699 * here nothing precedes the space in $v expansion,
5700 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005701 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005702 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005703 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005704 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005705 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005706 o_addchr(output, '\0');
5707 debug_print_list("expand_on_ifs", output, n);
5708 n = o_save_ptr(output, n);
5709 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005710 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005711
Denys Vlasenko168579a2018-07-19 13:45:54 +02005712 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005713 debug_print_list("expand_on_ifs[1]", output, n);
5714 return n;
5715}
5716
5717/* Helper to expand $((...)) and heredoc body. These act as if
5718 * they are in double quotes, with the exception that they are not :).
5719 * Just the rules are similar: "expand only $var and `cmd`"
5720 *
5721 * Returns malloced string.
5722 * As an optimization, we return NULL if expansion is not needed.
5723 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005724static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005725{
5726 char *exp_str;
5727 struct in_str input;
5728 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005729 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005730
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005731 cp = str;
5732 for (;;) {
5733 if (!*cp) return NULL; /* string has no special chars */
5734 if (*cp == '$') break;
5735 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005736#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005737 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005738#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005739 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005740 }
5741
5742 /* We need to expand. Example:
5743 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5744 */
5745 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005746 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005747//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005748 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005749 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005750 EXP_FLAG_ESC_GLOB_CHARS,
5751 /*unbackslash:*/ 1
5752 );
5753 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5754 o_free_unsafe(&dest);
5755 return exp_str;
5756}
5757
5758#if !BASH_PATTERN_SUBST
5759#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5760 encode_then_expand_vararg(str, handle_squotes)
5761#endif
5762static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5763{
5764#if !BASH_PATTERN_SUBST
5765 const int do_unbackslash = 0;
5766#endif
5767 char *exp_str;
5768 struct in_str input;
5769 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005770 const char *cp;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005771
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005772 cp = str;
5773 for (;;) {
5774 if (!*cp) return NULL; /* string has no special chars */
5775 if (*cp == '$') break;
5776 if (*cp == '\\') break;
5777 if (*cp == '\'') break;
5778 if (*cp == '"') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005779#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005780 if (*cp == '`') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005781#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005782 cp++;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005783 }
5784
5785 /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5786 * These can contain single- and double-quoted strings,
5787 * and treated as if the ARG string is initially unquoted. IOW:
5788 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5789 * a dquoted string: "${var#"zz"}"), the difference only comes later
5790 * (word splitting and globbing of the ${var...} result).
5791 */
5792
5793 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005794 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005795 exp_str = NULL;
5796
5797 for (;;) {
5798 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005799
5800 ch = i_getch(&input);
5801 if (ch == EOF) {
5802 if (dest.o_expflags) { /* EXP_FLAG_ESC_GLOB_CHARS set? */
5803 syntax_error_unterm_ch('"');
5804 goto ret; /* error */
5805 }
5806 break;
5807 }
5808 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5809 __func__, ch, ch, !!dest.o_expflags);
5810 if (ch == '\'' && handle_squotes && !dest.o_expflags) {
5811//quoting version of add_till_single_quote() (try to merge?):
5812 for (;;) {
5813 ch = i_getch(&input);
5814 if (ch == EOF) {
5815 syntax_error_unterm_ch('\'');
5816 goto ret; /* error */
5817 }
5818 if (ch == '\'')
5819 break;
5820 o_addqchr(&dest, ch);
5821 }
5822 continue;
5823 }
5824 if (ch == '"') {
5825 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5826 continue;
5827 }
5828 if (ch == '\\') {
5829 ch = i_getch(&input);
5830 if (ch == EOF) {
5831//example? error message? syntax_error_unterm_ch('"');
5832 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5833 goto ret;
5834 }
5835 o_addqchr(&dest, ch);
5836 continue;
5837 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02005838 if (ch == '$') {
5839 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5840 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5841 goto ret;
5842 }
5843 continue;
5844 }
5845#if ENABLE_HUSH_TICK
5846 if (ch == '`') {
5847 //unsigned pos = dest->length;
5848 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5849 o_addchr(&dest, 0x80 | '`');
5850 if (!add_till_backquote(&dest, &input,
5851 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5852 )
5853 ) {
5854 goto ret; /* error */
5855 }
5856 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5857 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5858 continue;
5859 }
5860#endif
5861 o_addQchr(&dest, ch);
5862 } /* for (;;) */
5863
5864 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5865 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02005866 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5867 do_unbackslash
5868 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02005869 ret:
5870 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005871 o_free_unsafe(&dest);
5872 return exp_str;
5873}
5874
Denys Vlasenko294eb462018-07-20 16:18:59 +02005875static int expand_vars_to_list(o_string *output, int n, char *arg);
5876
5877static int encode_then_append_var_plusminus(o_string *output, int n,
5878 const char *str, int dquoted)
5879{
5880 struct in_str input;
5881 o_string dest = NULL_O_STRING;
5882
5883#if 0 //todo?
5884 const char *cp;
5885 cp = str;
5886 for (;;) {
5887 if (!*cp) return NULL; /* string has no special chars */
5888 if (*cp == '$') break;
5889 if (*cp == '\\') break;
5890 if (*cp == '\'') break;
5891 if (*cp == '"') break;
5892#if ENABLE_HUSH_TICK
5893 if (*cp == '`') break;
5894#endif
5895 cp++;
5896 }
5897#endif
5898
5899 /* Expanding ARG in ${var+ARG}, ${var-ARG} */
5900
5901 setup_string_in_str(&input, str);
5902
5903 for (;;) {
5904 int ch;
5905
5906 ch = i_getch(&input);
5907 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
5908 __func__, ch, ch, dest.o_expflags);
5909
5910 if (!dest.o_expflags) {
5911 if (ch == EOF)
5912 break;
5913 if (!dquoted && strchr(G.ifs, ch)) {
5914 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
5915 * do not assume we are at the start of the word (PREFIX above).
5916 */
5917 if (dest.data) {
5918 n = expand_vars_to_list(output, n, dest.data);
5919 o_free(&dest);
5920 o_addchr(output, '\0');
5921 n = o_save_ptr(output, n); /* create next word */
5922 } else
5923 if (output->length != o_get_last_ptr(output, n)
5924 || output->has_quoted_part
5925 ) {
5926 /* For these cases:
5927 * f() { for i; do echo "|$i|"; done; }; x=x
5928 * f a${x:+ }b # 1st condition
5929 * |a|
5930 * |b|
5931 * f ""${x:+ }b # 2nd condition
5932 * ||
5933 * |b|
5934 */
5935 o_addchr(output, '\0');
5936 n = o_save_ptr(output, n); /* create next word */
5937 }
5938 continue;
5939 }
5940 if (!dquoted && ch == '\'') {
5941//quoting version of add_till_single_quote() (try to merge?):
5942 for (;;) {
5943 ch = i_getch(&input);
5944 if (ch == EOF) {
5945 syntax_error_unterm_ch('\'');
5946 goto ret; /* error */
5947 }
5948 if (ch == '\'')
5949 break;
5950 o_addqchr(&dest, ch);
5951 }
Denys Vlasenko83e434d2018-07-20 17:36:06 +02005952 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5953 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02005954 continue;
5955 }
5956 }
5957 if (ch == EOF) {
5958 syntax_error_unterm_ch('"');
5959 goto ret; /* error */
5960 }
5961 if (ch == '"') {
5962 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02005963 if (dest.o_expflags) {
5964 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5965 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5966 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02005967 continue;
5968 }
5969 if (ch == '\\') {
5970 ch = i_getch(&input);
5971 if (ch == EOF) {
5972//example? error message? syntax_error_unterm_ch('"');
5973 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5974 goto ret;
5975 }
5976 o_addqchr(&dest, ch);
5977 continue;
5978 }
5979 if (ch == '$') {
5980 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
5981 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5982 goto ret;
5983 }
5984 continue;
5985 }
5986#if ENABLE_HUSH_TICK
5987 if (ch == '`') {
5988 //unsigned pos = dest->length;
5989 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5990 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
5991 if (!add_till_backquote(&dest, &input,
5992 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5993 )
5994 ) {
5995 goto ret; /* error */
5996 }
5997 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5998 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5999 continue;
6000 }
6001#endif
6002 o_addQchr(&dest, ch);
6003 } /* for (;;) */
6004
6005 if (dest.data) {
6006 n = expand_vars_to_list(output, n, dest.data);
6007 }
6008 ret:
6009 o_free_unsafe(&dest);
6010 return n;
6011}
6012
Denys Vlasenko0b883582016-12-23 16:49:07 +01006013#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006014static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006015{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006016 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006017 arith_t res;
6018 char *exp_str;
6019
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006020 math_state.lookupvar = get_local_var_value;
6021 math_state.setvar = set_local_var_from_halves;
6022 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006023 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006024 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006025 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006026 if (errmsg_p)
6027 *errmsg_p = math_state.errmsg;
6028 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006029 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006030 return res;
6031}
6032#endif
6033
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006034#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006035/* ${var/[/]pattern[/repl]} helpers */
6036static char *strstr_pattern(char *val, const char *pattern, int *size)
6037{
6038 while (1) {
6039 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6040 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6041 if (end) {
6042 *size = end - val;
6043 return val;
6044 }
6045 if (*val == '\0')
6046 return NULL;
6047 /* Optimization: if "*pat" did not match the start of "string",
6048 * we know that "tring", "ring" etc will not match too:
6049 */
6050 if (pattern[0] == '*')
6051 return NULL;
6052 val++;
6053 }
6054}
6055static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6056{
6057 char *result = NULL;
6058 unsigned res_len = 0;
6059 unsigned repl_len = strlen(repl);
6060
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006061 /* Null pattern never matches, including if "var" is empty */
6062 if (!pattern[0])
6063 return result; /* NULL, no replaces happened */
6064
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006065 while (1) {
6066 int size;
6067 char *s = strstr_pattern(val, pattern, &size);
6068 if (!s)
6069 break;
6070
6071 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006072 strcpy(mempcpy(result + res_len, val, s - val), repl);
6073 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006074 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6075
6076 val = s + size;
6077 if (exp_op == '/')
6078 break;
6079 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006080 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006081 result = xrealloc(result, res_len + strlen(val) + 1);
6082 strcpy(result + res_len, val);
6083 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6084 }
6085 debug_printf_varexp("result:'%s'\n", result);
6086 return result;
6087}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006088#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006089
Denys Vlasenko168579a2018-07-19 13:45:54 +02006090static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006091 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006092{
6093 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6094 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6095 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6096 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006097 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006098 } else { /* quoted "$VAR" */
6099 output->has_quoted_part = 1;
6100 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6101 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6102 if (val && val[0])
6103 o_addQstr(output, val);
6104 }
6105 return n;
6106}
6107
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006108/* Helper:
6109 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
6110 */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006111static NOINLINE int expand_one_var(o_string *output,
Denys Vlasenko168579a2018-07-19 13:45:54 +02006112 int n, int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006113{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006114 const char *val;
6115 char *to_be_freed;
6116 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006117 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006118 char exp_op;
6119 char exp_save = exp_save; /* for compiler */
6120 char *exp_saveptr; /* points to expansion operator */
6121 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006122 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006123
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006124 val = NULL;
6125 to_be_freed = NULL;
6126 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006127 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006128 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006129 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006130 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006131 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006132 exp_op = 0;
6133
Denys Vlasenkob762c782018-07-17 14:21:38 +02006134 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006135 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6136 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6137 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006138 ) {
6139 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006140 var++;
6141 exp_op = 'L';
6142 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006143 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006144 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006145 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006146 ) {
6147 /* ${?:0}, ${#[:]%0} etc */
6148 exp_saveptr = var + 1;
6149 } else {
6150 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6151 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6152 }
6153 exp_op = exp_save = *exp_saveptr;
6154 if (exp_op) {
6155 exp_word = exp_saveptr + 1;
6156 if (exp_op == ':') {
6157 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006158//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006159 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006160 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006161 ) {
6162 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6163 exp_op = ':';
6164 exp_word--;
6165 }
6166 }
6167 *exp_saveptr = '\0';
6168 } /* else: it's not an expansion op, but bare ${var} */
6169 }
6170
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006171 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006172 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006173 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006174 int nn = xatoi_positive(var);
6175 if (nn < G.global_argc)
6176 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006177 /* else val remains NULL: $N with too big N */
6178 } else {
6179 switch (var[0]) {
6180 case '$': /* pid */
6181 val = utoa(G.root_pid);
6182 break;
6183 case '!': /* bg pid */
6184 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6185 break;
6186 case '?': /* exitcode */
6187 val = utoa(G.last_exitcode);
6188 break;
6189 case '#': /* argc */
6190 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6191 break;
6192 default:
6193 val = get_local_var_value(var);
6194 }
6195 }
6196
6197 /* Handle any expansions */
6198 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006199 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006200 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006201 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006202 debug_printf_expand("%s\n", val);
6203 } else if (exp_op) {
6204 if (exp_op == '%' || exp_op == '#') {
6205 /* Standard-mandated substring removal ops:
6206 * ${parameter%word} - remove smallest suffix pattern
6207 * ${parameter%%word} - remove largest suffix pattern
6208 * ${parameter#word} - remove smallest prefix pattern
6209 * ${parameter##word} - remove largest prefix pattern
6210 *
6211 * Word is expanded to produce a glob pattern.
6212 * Then var's value is matched to it and matching part removed.
6213 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006214//FIXME: ${x#...${...}...}
6215//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6216//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006217 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006218 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006219 char *exp_exp_word;
6220 char *loc;
6221 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006222 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006223 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006224 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006225 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006226 if (exp_exp_word)
6227 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006228 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6229 /*
6230 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006231 * G.global_argv and results of utoa and get_local_var_value
6232 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006233 * scan_and_match momentarily stores NULs there.
6234 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006235 t = (char*)val;
6236 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006237 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006238 free(exp_exp_word);
6239 if (loc) { /* match was found */
6240 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006241 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006242 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006243 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006244 }
6245 }
6246 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006247#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006248 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006249 /* It's ${var/[/]pattern[/repl]} thing.
6250 * Note that in encoded form it has TWO parts:
6251 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006252 * and if // is used, it is encoded as \:
6253 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006254 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006255 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006256 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006257 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006258 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006259 * >az >bz
6260 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6261 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6262 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6263 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006264 * (note that a*z _pattern_ is never globbed!)
6265 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006266 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006267 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006268 if (!pattern)
6269 pattern = xstrdup(exp_word);
6270 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6271 *p++ = SPECIAL_VAR_SYMBOL;
6272 exp_word = p;
6273 p = strchr(p, SPECIAL_VAR_SYMBOL);
6274 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006275 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006276 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6277 /* HACK ALERT. We depend here on the fact that
6278 * G.global_argv and results of utoa and get_local_var_value
6279 * are actually in writable memory:
6280 * replace_pattern momentarily stores NULs there. */
6281 t = (char*)val;
6282 to_be_freed = replace_pattern(t,
6283 pattern,
6284 (repl ? repl : exp_word),
6285 exp_op);
6286 if (to_be_freed) /* at least one replace happened */
6287 val = to_be_freed;
6288 free(pattern);
6289 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006290 } else {
6291 /* Empty variable always gives nothing */
6292 // "v=''; echo ${v/*/w}" prints "", not "w"
6293 /* Just skip "replace" part */
6294 *p++ = SPECIAL_VAR_SYMBOL;
6295 p = strchr(p, SPECIAL_VAR_SYMBOL);
6296 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006297 }
6298 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006299#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006300 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006301#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006302 /* It's ${var:N[:M]} bashism.
6303 * Note that in encoded form it has TWO parts:
6304 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6305 */
6306 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006307 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006308
Denys Vlasenko063847d2010-09-15 13:33:02 +02006309 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6310 if (errmsg)
6311 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006312 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6313 *p++ = SPECIAL_VAR_SYMBOL;
6314 exp_word = p;
6315 p = strchr(p, SPECIAL_VAR_SYMBOL);
6316 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006317 len = expand_and_evaluate_arith(exp_word, &errmsg);
6318 if (errmsg)
6319 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006320 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006321 if (beg < 0) {
6322 /* negative beg counts from the end */
6323 beg = (arith_t)strlen(val) + beg;
6324 if (beg < 0) /* ${v: -999999} is "" */
6325 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006326 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006327 debug_printf_varexp("from val:'%s'\n", val);
6328 if (len < 0) {
6329 /* in bash, len=-n means strlen()-n */
6330 len = (arith_t)strlen(val) - beg + len;
6331 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006332 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006333 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006334 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006335 arith_err:
6336 val = NULL;
6337 } else {
6338 /* Paranoia. What if user entered 9999999999999
6339 * which fits in arith_t but not int? */
6340 if (len >= INT_MAX)
6341 len = INT_MAX;
6342 val = to_be_freed = xstrndup(val + beg, len);
6343 }
6344 debug_printf_varexp("val:'%s'\n", val);
6345#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006346 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006347 val = NULL;
6348#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006349 } else { /* one of "-=+?" */
6350 /* Standard-mandated substitution ops:
6351 * ${var?word} - indicate error if unset
6352 * If var is unset, word (or a message indicating it is unset
6353 * if word is null) is written to standard error
6354 * and the shell exits with a non-zero exit status.
6355 * Otherwise, the value of var is substituted.
6356 * ${var-word} - use default value
6357 * If var is unset, word is substituted.
6358 * ${var=word} - assign and use default value
6359 * If var is unset, word is assigned to var.
6360 * In all cases, final value of var is substituted.
6361 * ${var+word} - use alternative value
6362 * If var is unset, null is substituted.
6363 * Otherwise, word is substituted.
6364 *
6365 * Word is subjected to tilde expansion, parameter expansion,
6366 * command substitution, and arithmetic expansion.
6367 * If word is not needed, it is not expanded.
6368 *
6369 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6370 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006371 *
6372 * Word-splitting and single quote behavior:
6373 *
6374 * $ f() { for i; do echo "|$i|"; done; };
6375 *
6376 * $ x=; f ${x:?'x y' z}
6377 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6378 * $ x=; f "${x:?'x y' z}"
6379 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6380 *
6381 * $ x=; f ${x:='x y' z}
6382 * |x|
6383 * |y|
6384 * |z|
6385 * $ x=; f "${x:='x y' z}"
6386 * |'x y' z|
6387 *
6388 * $ x=x; f ${x:+'x y' z}|
6389 * |x y|
6390 * |z|
6391 * $ x=x; f "${x:+'x y' z}"
6392 * |'x y' z|
6393 *
6394 * $ x=; f ${x:-'x y' z}
6395 * |x y|
6396 * |z|
6397 * $ x=; f "${x:-'x y' z}"
6398 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006399 */
6400 int use_word = (!val || ((exp_save == ':') && !val[0]));
6401 if (exp_op == '+')
6402 use_word = !use_word;
6403 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6404 (exp_save == ':') ? "true" : "false", use_word);
6405 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006406 if (exp_op == '+' || exp_op == '-') {
6407 /* ${var+word} - use alternative value */
6408 /* ${var-word} - use default value */
6409 n = encode_then_append_var_plusminus(output, n, exp_word,
6410 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006411 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006412 val = NULL;
6413 } else {
6414 /* ${var?word} - indicate error if unset */
6415 /* ${var=word} - assign and use default value */
6416 to_be_freed = encode_then_expand_vararg(exp_word,
6417 /*handle_squotes:*/ !(arg0 & 0x80),
6418 /*unbackslash:*/ 0
6419 );
6420 if (to_be_freed)
6421 exp_word = to_be_freed;
6422 if (exp_op == '?') {
6423 /* mimic bash message */
6424 msg_and_die_if_script("%s: %s",
6425 var,
6426 exp_word[0]
6427 ? exp_word
6428 : "parameter null or not set"
6429 /* ash has more specific messages, a-la: */
6430 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6431 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006432//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006433//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006434// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6435// bash: x: x y z
6436// $
6437// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006438 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006439 val = exp_word;
6440 }
6441 if (exp_op == '=') {
6442 /* ${var=[word]} or ${var:=[word]} */
6443 if (isdigit(var[0]) || var[0] == '#') {
6444 /* mimic bash message */
6445 msg_and_die_if_script("$%s: cannot assign in this way", var);
6446 val = NULL;
6447 } else {
6448 char *new_var = xasprintf("%s=%s", var, val);
6449 set_local_var(new_var, /*flag:*/ 0);
6450 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006451 }
6452 }
6453 }
6454 } /* one of "-=+?" */
6455
6456 *exp_saveptr = exp_save;
6457 } /* if (exp_op) */
6458
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006459 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006460 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006461
Denys Vlasenko168579a2018-07-19 13:45:54 +02006462 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006463
6464 free(to_be_freed);
6465 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006466}
6467
6468/* Expand all variable references in given string, adding words to list[]
6469 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6470 * to be filled). This routine is extremely tricky: has to deal with
6471 * variables/parameters with whitespace, $* and $@, and constructs like
6472 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006473static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006474{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006475 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006476 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006477 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006478 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006479 char *p;
6480
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006481 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6482 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006483 debug_print_list("expand_vars_to_list[0]", output, n);
6484
6485 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6486 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006487#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006488 char arith_buf[sizeof(arith_t)*3 + 2];
6489#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006490
Denys Vlasenko168579a2018-07-19 13:45:54 +02006491 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006492 o_addchr(output, '\0');
6493 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006494 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006495 }
6496
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006497 o_addblock(output, arg, p - arg);
6498 debug_print_list("expand_vars_to_list[1]", output, n);
6499 arg = ++p;
6500 p = strchr(p, SPECIAL_VAR_SYMBOL);
6501
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006502 /* Fetch special var name (if it is indeed one of them)
6503 * and quote bit, force the bit on if singleword expansion -
6504 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006505 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006506
6507 /* Is this variable quoted and thus expansion can't be null?
6508 * "$@" is special. Even if quoted, it can still
6509 * expand to nothing (not even an empty string),
6510 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006511 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006512 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006513
6514 switch (first_ch & 0x7f) {
6515 /* Highest bit in first_ch indicates that var is double-quoted */
6516 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006517 case '@': {
6518 int i;
6519 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006520 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006521 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006522 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006523 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006524 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006525 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006526 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6527 if (G.global_argv[i++][0] && G.global_argv[i]) {
6528 /* this argv[] is not empty and not last:
6529 * put terminating NUL, start new word */
6530 o_addchr(output, '\0');
6531 debug_print_list("expand_vars_to_list[2]", output, n);
6532 n = o_save_ptr(output, n);
6533 debug_print_list("expand_vars_to_list[3]", output, n);
6534 }
6535 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006536 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006537 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006538 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006539 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006540 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006541 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006542 while (1) {
6543 o_addQstr(output, G.global_argv[i]);
6544 if (++i >= G.global_argc)
6545 break;
6546 o_addchr(output, '\0');
6547 debug_print_list("expand_vars_to_list[4]", output, n);
6548 n = o_save_ptr(output, n);
6549 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006550 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006551 while (1) {
6552 o_addQstr(output, G.global_argv[i]);
6553 if (!G.global_argv[++i])
6554 break;
6555 if (G.ifs[0])
6556 o_addchr(output, G.ifs[0]);
6557 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006558 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006559 }
6560 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006561 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006562 case SPECIAL_VAR_SYMBOL: {
6563 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006564 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006565 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006566 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006567 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006568 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006569 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006570 case SPECIAL_VAR_QUOTED_SVS:
6571 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006572 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006573 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006574 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006575 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006576#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006577 case '`': {
6578 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006579 o_string subst_result = NULL_O_STRING;
6580
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006581 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006582 arg++;
6583 /* Can't just stuff it into output o_string,
6584 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006585 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006586 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6587 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006588 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006589 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006590 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006591 o_free_unsafe(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006592 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006593 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006594#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006595#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006596 case '+': {
6597 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006598 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006599
6600 arg++; /* skip '+' */
6601 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6602 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006603 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006604 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6605 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006606 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006607 break;
6608 }
6609#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006610 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006611 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006612 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006613 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006614 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6615
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006616 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6617 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006618 if (*p != SPECIAL_VAR_SYMBOL)
6619 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006620 arg = ++p;
6621 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6622
6623 if (arg[0]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006624 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006625 o_addchr(output, '\0');
6626 n = o_save_ptr(output, n);
6627 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006628 debug_print_list("expand_vars_to_list[a]", output, n);
6629 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006630 * if needed (much earlier), do not use o_addQstr here!
6631 */
6632 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006633 debug_print_list("expand_vars_to_list[b]", output, n);
6634 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006635 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6636 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006637 ) {
6638 n--;
6639 /* allow to reuse list[n] later without re-growth */
6640 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006641 }
6642
6643 return n;
6644}
6645
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006646static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006647{
6648 int n;
6649 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006650 o_string output = NULL_O_STRING;
6651
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006652 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006653
6654 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006655 for (;;) {
6656 /* go to next list[n] */
6657 output.ended_in_ifs = 0;
6658 n = o_save_ptr(&output, n);
6659
6660 if (!*argv)
6661 break;
6662
6663 /* expand argv[i] */
6664 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006665 /* if (!output->has_empty_slot) -- need this?? */
6666 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006667 }
6668 debug_print_list("expand_variables", &output, n);
6669
6670 /* output.data (malloced in one block) gets returned in "list" */
6671 list = o_finalize_list(&output, n);
6672 debug_print_strings("expand_variables[1]", list);
6673 return list;
6674}
6675
6676static char **expand_strvec_to_strvec(char **argv)
6677{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006678 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006679}
6680
Denys Vlasenko11752d42018-04-03 08:20:58 +02006681#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006682static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6683{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006684 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006685}
6686#endif
6687
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006688/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006689 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006690 *
6691 * NB: should NOT do globbing!
6692 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6693 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006694static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006695{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006696#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006697 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006698 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006699#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006700 char *argv[2], **list;
6701
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006702 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006703 /* This is generally an optimization, but it also
6704 * handles "", which otherwise trips over !list[0] check below.
6705 * (is this ever happens that we actually get str="" here?)
6706 */
6707 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6708 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006709 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006710 return xstrdup(str);
6711 }
6712
6713 argv[0] = (char*)str;
6714 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006715 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006716 if (!list[0]) {
6717 /* Example where it happens:
6718 * x=; echo ${x:-"$@"}
6719 */
6720 ((char*)list)[0] = '\0';
6721 } else {
6722 if (HUSH_DEBUG)
6723 if (list[1])
6724 bb_error_msg_and_die("BUG in varexp2");
6725 /* actually, just move string 2*sizeof(char*) bytes back */
6726 overlapping_strcpy((char*)list, list[0]);
6727 if (do_unbackslash)
6728 unbackslash((char*)list);
6729 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006730 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006731 return (char*)list;
6732}
6733
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006734#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006735static char* expand_strvec_to_string(char **argv)
6736{
6737 char **list;
6738
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006739 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006740 /* Convert all NULs to spaces */
6741 if (list[0]) {
6742 int n = 1;
6743 while (list[n]) {
6744 if (HUSH_DEBUG)
6745 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6746 bb_error_msg_and_die("BUG in varexp3");
6747 /* bash uses ' ' regardless of $IFS contents */
6748 list[n][-1] = ' ';
6749 n++;
6750 }
6751 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006752 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006753 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6754 return (char*)list;
6755}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006756#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006757
6758static char **expand_assignments(char **argv, int count)
6759{
6760 int i;
6761 char **p;
6762
6763 G.expanded_assignments = p = NULL;
6764 /* Expand assignments into one string each */
6765 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006766 p = add_string_to_strings(p,
6767 expand_string_to_string(argv[i],
6768 EXP_FLAG_ESC_GLOB_CHARS,
6769 /*unbackslash:*/ 1
6770 )
6771 );
6772 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006773 }
6774 G.expanded_assignments = NULL;
6775 return p;
6776}
6777
6778
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006779static void switch_off_special_sigs(unsigned mask)
6780{
6781 unsigned sig = 0;
6782 while ((mask >>= 1) != 0) {
6783 sig++;
6784 if (!(mask & 1))
6785 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006786#if ENABLE_HUSH_TRAP
6787 if (G_traps) {
6788 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006789 /* trap is '', has to remain SIG_IGN */
6790 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006791 free(G_traps[sig]);
6792 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006793 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006794#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006795 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006796 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006797 }
6798}
6799
Denys Vlasenkob347df92011-08-09 22:49:15 +02006800#if BB_MMU
6801/* never called */
6802void re_execute_shell(char ***to_free, const char *s,
6803 char *g_argv0, char **g_argv,
6804 char **builtin_argv) NORETURN;
6805
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006806static void reset_traps_to_defaults(void)
6807{
6808 /* This function is always called in a child shell
6809 * after fork (not vfork, NOMMU doesn't use this function).
6810 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006811 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006812 unsigned mask;
6813
6814 /* Child shells are not interactive.
6815 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6816 * Testcase: (while :; do :; done) + ^Z should background.
6817 * Same goes for SIGTERM, SIGHUP, SIGINT.
6818 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006819 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006820 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006821 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006822
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006823 /* Switch off special sigs */
6824 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006825# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006826 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006827# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006828 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006829 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6830 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006831
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006832# if ENABLE_HUSH_TRAP
6833 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006834 return;
6835
6836 /* Reset all sigs to default except ones with empty traps */
6837 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006838 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006839 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006840 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006841 continue; /* empty trap: has to remain SIG_IGN */
6842 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006843 free(G_traps[sig]);
6844 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006845 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006846 if (sig == 0)
6847 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006848 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006849 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006850# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006851}
6852
6853#else /* !BB_MMU */
6854
6855static void re_execute_shell(char ***to_free, const char *s,
6856 char *g_argv0, char **g_argv,
6857 char **builtin_argv) NORETURN;
6858static void re_execute_shell(char ***to_free, const char *s,
6859 char *g_argv0, char **g_argv,
6860 char **builtin_argv)
6861{
6862# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6863 /* delims + 2 * (number of bytes in printed hex numbers) */
6864 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6865 char *heredoc_argv[4];
6866 struct variable *cur;
6867# if ENABLE_HUSH_FUNCTIONS
6868 struct function *funcp;
6869# endif
6870 char **argv, **pp;
6871 unsigned cnt;
6872 unsigned long long empty_trap_mask;
6873
6874 if (!g_argv0) { /* heredoc */
6875 argv = heredoc_argv;
6876 argv[0] = (char *) G.argv0_for_re_execing;
6877 argv[1] = (char *) "-<";
6878 argv[2] = (char *) s;
6879 argv[3] = NULL;
6880 pp = &argv[3]; /* used as pointer to empty environment */
6881 goto do_exec;
6882 }
6883
6884 cnt = 0;
6885 pp = builtin_argv;
6886 if (pp) while (*pp++)
6887 cnt++;
6888
6889 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006890 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006891 int sig;
6892 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006893 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006894 empty_trap_mask |= 1LL << sig;
6895 }
6896 }
6897
6898 sprintf(param_buf, NOMMU_HACK_FMT
6899 , (unsigned) G.root_pid
6900 , (unsigned) G.root_ppid
6901 , (unsigned) G.last_bg_pid
6902 , (unsigned) G.last_exitcode
6903 , cnt
6904 , empty_trap_mask
6905 IF_HUSH_LOOPS(, G.depth_of_loop)
6906 );
6907# undef NOMMU_HACK_FMT
6908 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6909 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6910 */
6911 cnt += 6;
6912 for (cur = G.top_var; cur; cur = cur->next) {
6913 if (!cur->flg_export || cur->flg_read_only)
6914 cnt += 2;
6915 }
6916# if ENABLE_HUSH_FUNCTIONS
6917 for (funcp = G.top_func; funcp; funcp = funcp->next)
6918 cnt += 3;
6919# endif
6920 pp = g_argv;
6921 while (*pp++)
6922 cnt++;
6923 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6924 *pp++ = (char *) G.argv0_for_re_execing;
6925 *pp++ = param_buf;
6926 for (cur = G.top_var; cur; cur = cur->next) {
6927 if (strcmp(cur->varstr, hush_version_str) == 0)
6928 continue;
6929 if (cur->flg_read_only) {
6930 *pp++ = (char *) "-R";
6931 *pp++ = cur->varstr;
6932 } else if (!cur->flg_export) {
6933 *pp++ = (char *) "-V";
6934 *pp++ = cur->varstr;
6935 }
6936 }
6937# if ENABLE_HUSH_FUNCTIONS
6938 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6939 *pp++ = (char *) "-F";
6940 *pp++ = funcp->name;
6941 *pp++ = funcp->body_as_string;
6942 }
6943# endif
6944 /* We can pass activated traps here. Say, -Tnn:trap_string
6945 *
6946 * However, POSIX says that subshells reset signals with traps
6947 * to SIG_DFL.
6948 * I tested bash-3.2 and it not only does that with true subshells
6949 * of the form ( list ), but with any forked children shells.
6950 * I set trap "echo W" WINCH; and then tried:
6951 *
6952 * { echo 1; sleep 20; echo 2; } &
6953 * while true; do echo 1; sleep 20; echo 2; break; done &
6954 * true | { echo 1; sleep 20; echo 2; } | cat
6955 *
6956 * In all these cases sending SIGWINCH to the child shell
6957 * did not run the trap. If I add trap "echo V" WINCH;
6958 * _inside_ group (just before echo 1), it works.
6959 *
6960 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006961 */
6962 *pp++ = (char *) "-c";
6963 *pp++ = (char *) s;
6964 if (builtin_argv) {
6965 while (*++builtin_argv)
6966 *pp++ = *builtin_argv;
6967 *pp++ = (char *) "";
6968 }
6969 *pp++ = g_argv0;
6970 while (*g_argv)
6971 *pp++ = *g_argv++;
6972 /* *pp = NULL; - is already there */
6973 pp = environ;
6974
6975 do_exec:
6976 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006977 /* Don't propagate SIG_IGN to the child */
6978 if (SPECIAL_JOBSTOP_SIGS != 0)
6979 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006980 execve(bb_busybox_exec_path, argv, pp);
6981 /* Fallback. Useful for init=/bin/hush usage etc */
6982 if (argv[0][0] == '/')
6983 execve(argv[0], argv, pp);
6984 xfunc_error_retval = 127;
6985 bb_error_msg_and_die("can't re-execute the shell");
6986}
6987#endif /* !BB_MMU */
6988
6989
6990static int run_and_free_list(struct pipe *pi);
6991
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006992/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006993 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6994 * end_trigger controls how often we stop parsing
6995 * NUL: parse all, execute, return
6996 * ';': parse till ';' or newline, execute, repeat till EOF
6997 */
6998static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006999{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007000 /* Why we need empty flag?
7001 * An obscure corner case "false; ``; echo $?":
7002 * empty command in `` should still set $? to 0.
7003 * But we can't just set $? to 0 at the start,
7004 * this breaks "false; echo `echo $?`" case.
7005 */
7006 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007007 while (1) {
7008 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007009
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007010#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007011 if (end_trigger == ';') {
7012 G.promptmode = 0; /* PS1 */
7013 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7014 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007015#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007016 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007017 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7018 /* If we are in "big" script
7019 * (not in `cmd` or something similar)...
7020 */
7021 if (pipe_list == ERR_PTR && end_trigger == ';') {
7022 /* Discard cached input (rest of line) */
7023 int ch = inp->last_char;
7024 while (ch != EOF && ch != '\n') {
7025 //bb_error_msg("Discarded:'%c'", ch);
7026 ch = i_getch(inp);
7027 }
7028 /* Force prompt */
7029 inp->p = NULL;
7030 /* This stream isn't empty */
7031 empty = 0;
7032 continue;
7033 }
7034 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007035 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007036 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007037 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007038 debug_print_tree(pipe_list, 0);
7039 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7040 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007041 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007042 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007043 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007044 }
Eric Andersen25f27032001-04-26 23:22:31 +00007045}
7046
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007047static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007048{
7049 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007050 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7051
Eric Andersen25f27032001-04-26 23:22:31 +00007052 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007053 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007054 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007055}
7056
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007057static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00007058{
Eric Andersen25f27032001-04-26 23:22:31 +00007059 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007060 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007061
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007062 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01007063 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007064 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007065 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007066}
7067
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007068#if ENABLE_HUSH_TICK
7069static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
7070{
7071 pid_t pid;
7072 int channel[2];
7073# if !BB_MMU
7074 char **to_free = NULL;
7075# endif
7076
7077 xpipe(channel);
7078 pid = BB_MMU ? xfork() : xvfork();
7079 if (pid == 0) { /* child */
7080 disable_restore_tty_pgrp_on_exit();
7081 /* Process substitution is not considered to be usual
7082 * 'command execution'.
7083 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7084 */
7085 bb_signals(0
7086 + (1 << SIGTSTP)
7087 + (1 << SIGTTIN)
7088 + (1 << SIGTTOU)
7089 , SIG_IGN);
7090 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7091 close(channel[0]); /* NB: close _first_, then move fd! */
7092 xmove_fd(channel[1], 1);
7093 /* Prevent it from trying to handle ctrl-z etc */
7094 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007095# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007096 /* Awful hack for `trap` or $(trap).
7097 *
7098 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7099 * contains an example where "trap" is executed in a subshell:
7100 *
7101 * save_traps=$(trap)
7102 * ...
7103 * eval "$save_traps"
7104 *
7105 * Standard does not say that "trap" in subshell shall print
7106 * parent shell's traps. It only says that its output
7107 * must have suitable form, but then, in the above example
7108 * (which is not supposed to be normative), it implies that.
7109 *
7110 * bash (and probably other shell) does implement it
7111 * (traps are reset to defaults, but "trap" still shows them),
7112 * but as a result, "trap" logic is hopelessly messed up:
7113 *
7114 * # trap
7115 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7116 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7117 * # true | trap <--- trap is in subshell - no output (ditto)
7118 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7119 * trap -- 'echo Ho' SIGWINCH
7120 * # echo `(trap)` <--- in subshell in subshell - output
7121 * trap -- 'echo Ho' SIGWINCH
7122 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7123 * trap -- 'echo Ho' SIGWINCH
7124 *
7125 * The rules when to forget and when to not forget traps
7126 * get really complex and nonsensical.
7127 *
7128 * Our solution: ONLY bare $(trap) or `trap` is special.
7129 */
7130 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007131 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007132 && skip_whitespace(s + 4)[0] == '\0'
7133 ) {
7134 static const char *const argv[] = { NULL, NULL };
7135 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007136 fflush_all(); /* important */
7137 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007138 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007139# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007140# if BB_MMU
7141 reset_traps_to_defaults();
7142 parse_and_run_string(s);
7143 _exit(G.last_exitcode);
7144# else
7145 /* We re-execute after vfork on NOMMU. This makes this script safe:
7146 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7147 * huge=`cat BIG` # was blocking here forever
7148 * echo OK
7149 */
7150 re_execute_shell(&to_free,
7151 s,
7152 G.global_argv[0],
7153 G.global_argv + 1,
7154 NULL);
7155# endif
7156 }
7157
7158 /* parent */
7159 *pid_p = pid;
7160# if ENABLE_HUSH_FAST
7161 G.count_SIGCHLD++;
7162//bb_error_msg("[%d] fork in generate_stream_from_string:"
7163// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7164// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7165# endif
7166 enable_restore_tty_pgrp_on_exit();
7167# if !BB_MMU
7168 free(to_free);
7169# endif
7170 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007171 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007172}
7173
7174/* Return code is exit status of the process that is run. */
7175static int process_command_subs(o_string *dest, const char *s)
7176{
7177 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007178 pid_t pid;
7179 int status, ch, eol_cnt;
7180
7181 fp = generate_stream_from_string(s, &pid);
7182
7183 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007184 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007185 while ((ch = getc(fp)) != EOF) {
7186 if (ch == '\0')
7187 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007188 if (ch == '\n') {
7189 eol_cnt++;
7190 continue;
7191 }
7192 while (eol_cnt) {
7193 o_addchr(dest, '\n');
7194 eol_cnt--;
7195 }
7196 o_addQchr(dest, ch);
7197 }
7198
7199 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007200 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007201 /* We need to extract exitcode. Test case
7202 * "true; echo `sleep 1; false` $?"
7203 * should print 1 */
7204 safe_waitpid(pid, &status, 0);
7205 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7206 return WEXITSTATUS(status);
7207}
7208#endif /* ENABLE_HUSH_TICK */
7209
7210
7211static void setup_heredoc(struct redir_struct *redir)
7212{
7213 struct fd_pair pair;
7214 pid_t pid;
7215 int len, written;
7216 /* the _body_ of heredoc (misleading field name) */
7217 const char *heredoc = redir->rd_filename;
7218 char *expanded;
7219#if !BB_MMU
7220 char **to_free;
7221#endif
7222
7223 expanded = NULL;
7224 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007225 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007226 if (expanded)
7227 heredoc = expanded;
7228 }
7229 len = strlen(heredoc);
7230
7231 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7232 xpiped_pair(pair);
7233 xmove_fd(pair.rd, redir->rd_fd);
7234
7235 /* Try writing without forking. Newer kernels have
7236 * dynamically growing pipes. Must use non-blocking write! */
7237 ndelay_on(pair.wr);
7238 while (1) {
7239 written = write(pair.wr, heredoc, len);
7240 if (written <= 0)
7241 break;
7242 len -= written;
7243 if (len == 0) {
7244 close(pair.wr);
7245 free(expanded);
7246 return;
7247 }
7248 heredoc += written;
7249 }
7250 ndelay_off(pair.wr);
7251
7252 /* Okay, pipe buffer was not big enough */
7253 /* Note: we must not create a stray child (bastard? :)
7254 * for the unsuspecting parent process. Child creates a grandchild
7255 * and exits before parent execs the process which consumes heredoc
7256 * (that exec happens after we return from this function) */
7257#if !BB_MMU
7258 to_free = NULL;
7259#endif
7260 pid = xvfork();
7261 if (pid == 0) {
7262 /* child */
7263 disable_restore_tty_pgrp_on_exit();
7264 pid = BB_MMU ? xfork() : xvfork();
7265 if (pid != 0)
7266 _exit(0);
7267 /* grandchild */
7268 close(redir->rd_fd); /* read side of the pipe */
7269#if BB_MMU
7270 full_write(pair.wr, heredoc, len); /* may loop or block */
7271 _exit(0);
7272#else
7273 /* Delegate blocking writes to another process */
7274 xmove_fd(pair.wr, STDOUT_FILENO);
7275 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7276#endif
7277 }
7278 /* parent */
7279#if ENABLE_HUSH_FAST
7280 G.count_SIGCHLD++;
7281//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7282#endif
7283 enable_restore_tty_pgrp_on_exit();
7284#if !BB_MMU
7285 free(to_free);
7286#endif
7287 close(pair.wr);
7288 free(expanded);
7289 wait(NULL); /* wait till child has died */
7290}
7291
Denys Vlasenko2db74612017-07-07 22:07:28 +02007292struct squirrel {
7293 int orig_fd;
7294 int moved_to;
7295 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7296 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7297};
7298
Denys Vlasenko621fc502017-07-24 12:42:17 +02007299static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7300{
7301 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7302 sq[i].orig_fd = orig;
7303 sq[i].moved_to = moved;
7304 sq[i+1].orig_fd = -1; /* end marker */
7305 return sq;
7306}
7307
Denys Vlasenko2db74612017-07-07 22:07:28 +02007308static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7309{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007310 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007311 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007312
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007313 i = 0;
7314 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007315 /* If we collide with an already moved fd... */
7316 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007317 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007318 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7319 if (sq[i].moved_to < 0) /* what? */
7320 xfunc_die();
7321 return sq;
7322 }
7323 if (fd == sq[i].orig_fd) {
7324 /* Example: echo Hello >/dev/null 1>&2 */
7325 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7326 return sq;
7327 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007328 }
7329
Denys Vlasenko2db74612017-07-07 22:07:28 +02007330 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007331 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007332 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7333 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007334 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007335 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007336}
7337
Denys Vlasenko657e9002017-07-30 23:34:04 +02007338static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7339{
7340 int i;
7341
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007342 i = 0;
7343 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007344 /* If we collide with an already moved fd... */
7345 if (fd == sq[i].orig_fd) {
7346 /* Examples:
7347 * "echo 3>FILE 3>&- 3>FILE"
7348 * "echo 3>&- 3>FILE"
7349 * No need for last redirect to insert
7350 * another "need to close 3" indicator.
7351 */
7352 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7353 return sq;
7354 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007355 }
7356
7357 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7358 return append_squirrel(sq, i, fd, -1);
7359}
7360
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007361/* fd: redirect wants this fd to be used (e.g. 3>file).
7362 * Move all conflicting internally used fds,
7363 * and remember them so that we can restore them later.
7364 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007365static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007366{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007367 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7368 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007369
7370#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007371 if (fd == G.interactive_fd) {
7372 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007373 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007374 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7375 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007376 }
7377#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007378 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7379 * (1) Redirect in a forked child. No need to save FILEs' fds,
7380 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007381 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7382 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007383 * "fileno(fd) = new_fd" can't be done.
7384 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007385 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007386 return 0;
7387
Denys Vlasenko2db74612017-07-07 22:07:28 +02007388 /* If this one of script's fds? */
7389 if (save_FILEs_on_redirect(fd, avoid_fd))
7390 return 1; /* yes. "we closed fd" */
7391
7392 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7393 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7394 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007395}
7396
Denys Vlasenko2db74612017-07-07 22:07:28 +02007397static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007398{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007399 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007400 int i;
7401 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007402 if (sq[i].moved_to >= 0) {
7403 /* We simply die on error */
7404 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7405 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7406 } else {
7407 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7408 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7409 close(sq[i].orig_fd);
7410 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007411 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007412 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007413 }
7414
Denys Vlasenko2db74612017-07-07 22:07:28 +02007415 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007416
7417 restore_redirected_FILEs();
7418}
7419
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007420#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007421static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007422{
7423 if (G_interactive_fd)
7424 close(G_interactive_fd);
7425 close_all_FILE_list();
7426}
7427#endif
7428
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007429static int internally_opened_fd(int fd, struct squirrel *sq)
7430{
7431 int i;
7432
7433#if ENABLE_HUSH_INTERACTIVE
7434 if (fd == G.interactive_fd)
7435 return 1;
7436#endif
7437 /* If this one of script's fds? */
7438 if (fd_in_FILEs(fd))
7439 return 1;
7440
7441 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7442 if (fd == sq[i].moved_to)
7443 return 1;
7444 }
7445 return 0;
7446}
7447
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007448/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7449 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007450static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007451{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007452 struct redir_struct *redir;
7453
7454 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007455 int newfd;
7456 int closed;
7457
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007458 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007459 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007460 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007461 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7462 * of the heredoc */
7463 debug_printf_parse("set heredoc '%s'\n",
7464 redir->rd_filename);
7465 setup_heredoc(redir);
7466 continue;
7467 }
7468
7469 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007470 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007471 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007472 int mode;
7473
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007474 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007475 /*
7476 * Examples:
7477 * "cmd >" (no filename)
7478 * "cmd > <file" (2nd redirect starts too early)
7479 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007480 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007481 continue;
7482 }
7483 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007484 p = expand_string_to_string(redir->rd_filename,
7485 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007486 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007487 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007488 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007489 /* Error message from open_or_warn can be lost
7490 * if stderr has been redirected, but bash
7491 * and ash both lose it as well
7492 * (though zsh doesn't!)
7493 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007494 return 1;
7495 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007496 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007497 /* open() gave us precisely the fd we wanted.
7498 * This means that this fd was not busy
7499 * (not opened to anywhere).
7500 * Remember to close it on restore:
7501 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007502 *sqp = add_squirrel_closed(*sqp, newfd);
7503 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007504 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007505 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007506 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7507 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007508 }
7509
Denys Vlasenko657e9002017-07-30 23:34:04 +02007510 if (newfd == redir->rd_fd)
7511 continue;
7512
7513 /* if "N>FILE": move newfd to redir->rd_fd */
7514 /* if "N>&M": dup newfd to redir->rd_fd */
7515 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7516
7517 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7518 if (newfd == REDIRFD_CLOSE) {
7519 /* "N>&-" means "close me" */
7520 if (!closed) {
7521 /* ^^^ optimization: saving may already
7522 * have closed it. If not... */
7523 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007524 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007525 /* Sometimes we do another close on restore, getting EBADF.
7526 * Consider "echo 3>FILE 3>&-"
7527 * first redirect remembers "need to close 3",
7528 * and second redirect closes 3! Restore code then closes 3 again.
7529 */
7530 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007531 /* if newfd is a script fd or saved fd, simulate EBADF */
7532 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7533 //errno = EBADF;
7534 //bb_perror_msg_and_die("can't duplicate file descriptor");
7535 newfd = -1; /* same effect as code above */
7536 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007537 xdup2(newfd, redir->rd_fd);
7538 if (redir->rd_dup == REDIRFD_TO_FILE)
7539 /* "rd_fd > FILE" */
7540 close(newfd);
7541 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007542 }
7543 }
7544 return 0;
7545}
7546
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007547static char *find_in_path(const char *arg)
7548{
7549 char *ret = NULL;
7550 const char *PATH = get_local_var_value("PATH");
7551
7552 if (!PATH)
7553 return NULL;
7554
7555 while (1) {
7556 const char *end = strchrnul(PATH, ':');
7557 int sz = end - PATH; /* must be int! */
7558
7559 free(ret);
7560 if (sz != 0) {
7561 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7562 } else {
7563 /* We have xxx::yyyy in $PATH,
7564 * it means "use current dir" */
7565 ret = xstrdup(arg);
7566 }
7567 if (access(ret, F_OK) == 0)
7568 break;
7569
7570 if (*end == '\0') {
7571 free(ret);
7572 return NULL;
7573 }
7574 PATH = end + 1;
7575 }
7576
7577 return ret;
7578}
7579
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007580static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007581 const struct built_in_command *x,
7582 const struct built_in_command *end)
7583{
7584 while (x != end) {
7585 if (strcmp(name, x->b_cmd) != 0) {
7586 x++;
7587 continue;
7588 }
7589 debug_printf_exec("found builtin '%s'\n", name);
7590 return x;
7591 }
7592 return NULL;
7593}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007594static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007595{
7596 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7597}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007598static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007599{
7600 const struct built_in_command *x = find_builtin1(name);
7601 if (x)
7602 return x;
7603 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7604}
7605
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007606static void remove_nested_vars(void)
7607{
7608 struct variable *cur;
7609 struct variable **cur_pp;
7610
7611 cur_pp = &G.top_var;
7612 while ((cur = *cur_pp) != NULL) {
7613 if (cur->var_nest_level <= G.var_nest_level) {
7614 cur_pp = &cur->next;
7615 continue;
7616 }
7617 /* Unexport */
7618 if (cur->flg_export) {
7619 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7620 bb_unsetenv(cur->varstr);
7621 }
7622 /* Remove from global list */
7623 *cur_pp = cur->next;
7624 /* Free */
7625 if (!cur->max_len) {
7626 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7627 free(cur->varstr);
7628 }
7629 free(cur);
7630 }
7631}
7632
7633static void enter_var_nest_level(void)
7634{
7635 G.var_nest_level++;
7636 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7637
7638 /* Try: f() { echo -n .; f; }; f
7639 * struct variable::var_nest_level is uint16_t,
7640 * thus limiting recursion to < 2^16.
7641 * In any case, with 8 Mbyte stack SEGV happens
7642 * not too long after 2^16 recursions anyway.
7643 */
7644 if (G.var_nest_level > 0xff00)
7645 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7646}
7647
7648static void leave_var_nest_level(void)
7649{
7650 G.var_nest_level--;
7651 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7652 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7653 bb_error_msg_and_die("BUG: nesting underflow");
7654
7655 remove_nested_vars();
7656}
7657
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007658#if ENABLE_HUSH_FUNCTIONS
7659static struct function **find_function_slot(const char *name)
7660{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007661 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007662 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007663
7664 while ((funcp = *funcpp) != NULL) {
7665 if (strcmp(name, funcp->name) == 0) {
7666 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007667 break;
7668 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007669 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007670 }
7671 return funcpp;
7672}
7673
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007674static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007675{
7676 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007677 return funcp;
7678}
7679
7680/* Note: takes ownership on name ptr */
7681static struct function *new_function(char *name)
7682{
7683 struct function **funcpp = find_function_slot(name);
7684 struct function *funcp = *funcpp;
7685
7686 if (funcp != NULL) {
7687 struct command *cmd = funcp->parent_cmd;
7688 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7689 if (!cmd) {
7690 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7691 free(funcp->name);
7692 /* Note: if !funcp->body, do not free body_as_string!
7693 * This is a special case of "-F name body" function:
7694 * body_as_string was not malloced! */
7695 if (funcp->body) {
7696 free_pipe_list(funcp->body);
7697# if !BB_MMU
7698 free(funcp->body_as_string);
7699# endif
7700 }
7701 } else {
7702 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7703 cmd->argv[0] = funcp->name;
7704 cmd->group = funcp->body;
7705# if !BB_MMU
7706 cmd->group_as_string = funcp->body_as_string;
7707# endif
7708 }
7709 } else {
7710 debug_printf_exec("remembering new function '%s'\n", name);
7711 funcp = *funcpp = xzalloc(sizeof(*funcp));
7712 /*funcp->next = NULL;*/
7713 }
7714
7715 funcp->name = name;
7716 return funcp;
7717}
7718
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007719# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007720static void unset_func(const char *name)
7721{
7722 struct function **funcpp = find_function_slot(name);
7723 struct function *funcp = *funcpp;
7724
7725 if (funcp != NULL) {
7726 debug_printf_exec("freeing function '%s'\n", funcp->name);
7727 *funcpp = funcp->next;
7728 /* funcp is unlinked now, deleting it.
7729 * Note: if !funcp->body, the function was created by
7730 * "-F name body", do not free ->body_as_string
7731 * and ->name as they were not malloced. */
7732 if (funcp->body) {
7733 free_pipe_list(funcp->body);
7734 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007735# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007736 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007737# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007738 }
7739 free(funcp);
7740 }
7741}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007742# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007743
7744# if BB_MMU
7745#define exec_function(to_free, funcp, argv) \
7746 exec_function(funcp, argv)
7747# endif
7748static void exec_function(char ***to_free,
7749 const struct function *funcp,
7750 char **argv) NORETURN;
7751static void exec_function(char ***to_free,
7752 const struct function *funcp,
7753 char **argv)
7754{
7755# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007756 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007757
7758 argv[0] = G.global_argv[0];
7759 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007760 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007761
7762// Example when we are here: "cmd | func"
7763// func will run with saved-redirect fds open.
7764// $ f() { echo /proc/self/fd/*; }
7765// $ true | f
7766// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7767// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7768// Same in script:
7769// $ . ./SCRIPT
7770// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7771// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7772// They are CLOEXEC so external programs won't see them, but
7773// for "more correctness" we might want to close those extra fds here:
7774//? close_saved_fds_and_FILE_fds();
7775
Denys Vlasenko332e4112018-04-04 22:32:59 +02007776 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007777 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007778 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007779 IF_HUSH_LOCAL(G.func_nest_level++;)
7780
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007781 /* On MMU, funcp->body is always non-NULL */
7782 n = run_list(funcp->body);
7783 fflush_all();
7784 _exit(n);
7785# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007786//? close_saved_fds_and_FILE_fds();
7787
7788//TODO: check whether "true | func_with_return" works
7789
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007790 re_execute_shell(to_free,
7791 funcp->body_as_string,
7792 G.global_argv[0],
7793 argv + 1,
7794 NULL);
7795# endif
7796}
7797
7798static int run_function(const struct function *funcp, char **argv)
7799{
7800 int rc;
7801 save_arg_t sv;
7802 smallint sv_flg;
7803
7804 save_and_replace_G_args(&sv, argv);
7805
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007806 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007807 sv_flg = G_flag_return_in_progress;
7808 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007809
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007810 /* Make "local" variables properly shadow previous ones */
7811 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007812 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007813
7814 /* On MMU, funcp->body is always non-NULL */
7815# if !BB_MMU
7816 if (!funcp->body) {
7817 /* Function defined by -F */
7818 parse_and_run_string(funcp->body_as_string);
7819 rc = G.last_exitcode;
7820 } else
7821# endif
7822 {
7823 rc = run_list(funcp->body);
7824 }
7825
Denys Vlasenko332e4112018-04-04 22:32:59 +02007826 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007827 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007828
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007829 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007830
7831 restore_G_args(&sv, argv);
7832
7833 return rc;
7834}
7835#endif /* ENABLE_HUSH_FUNCTIONS */
7836
7837
7838#if BB_MMU
7839#define exec_builtin(to_free, x, argv) \
7840 exec_builtin(x, argv)
7841#else
7842#define exec_builtin(to_free, x, argv) \
7843 exec_builtin(to_free, argv)
7844#endif
7845static void exec_builtin(char ***to_free,
7846 const struct built_in_command *x,
7847 char **argv) NORETURN;
7848static void exec_builtin(char ***to_free,
7849 const struct built_in_command *x,
7850 char **argv)
7851{
7852#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007853 int rcode;
7854 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007855//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007856 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007857 fflush_all();
7858 _exit(rcode);
7859#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007860 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007861 /* On NOMMU, we must never block!
7862 * Example: { sleep 99 | read line; } & echo Ok
7863 */
7864 re_execute_shell(to_free,
7865 argv[0],
7866 G.global_argv[0],
7867 G.global_argv + 1,
7868 argv);
7869#endif
7870}
7871
7872
7873static void execvp_or_die(char **argv) NORETURN;
7874static void execvp_or_die(char **argv)
7875{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007876 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007877 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007878 /* Don't propagate SIG_IGN to the child */
7879 if (SPECIAL_JOBSTOP_SIGS != 0)
7880 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007881 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007882 e = 2;
7883 if (errno == EACCES) e = 126;
7884 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007885 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007886 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007887}
7888
7889#if ENABLE_HUSH_MODE_X
7890static void dump_cmd_in_x_mode(char **argv)
7891{
7892 if (G_x_mode && argv) {
7893 /* We want to output the line in one write op */
7894 char *buf, *p;
7895 int len;
7896 int n;
7897
7898 len = 3;
7899 n = 0;
7900 while (argv[n])
7901 len += strlen(argv[n++]) + 1;
7902 buf = xmalloc(len);
7903 buf[0] = '+';
7904 p = buf + 1;
7905 n = 0;
7906 while (argv[n])
7907 p += sprintf(p, " %s", argv[n++]);
7908 *p++ = '\n';
7909 *p = '\0';
7910 fputs(buf, stderr);
7911 free(buf);
7912 }
7913}
7914#else
7915# define dump_cmd_in_x_mode(argv) ((void)0)
7916#endif
7917
Denys Vlasenko57000292018-01-12 14:41:45 +01007918#if ENABLE_HUSH_COMMAND
7919static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7920{
7921 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007922
Denys Vlasenko57000292018-01-12 14:41:45 +01007923 if (!opt_vV)
7924 return;
7925
7926 to_free = NULL;
7927 if (!explanation) {
7928 char *path = getenv("PATH");
7929 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007930 if (!explanation)
7931 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007932 if (opt_vV != 'V')
7933 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7934 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007935 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007936 free(to_free);
7937 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007938 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007939}
7940#else
7941# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7942#endif
7943
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007944#if BB_MMU
7945#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7946 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7947#define pseudo_exec(nommu_save, command, argv_expanded) \
7948 pseudo_exec(command, argv_expanded)
7949#endif
7950
7951/* Called after [v]fork() in run_pipe, or from builtin_exec.
7952 * Never returns.
7953 * Don't exit() here. If you don't exec, use _exit instead.
7954 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007955 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007956 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007957static void pseudo_exec_argv(nommu_save_t *nommu_save,
7958 char **argv, int assignment_cnt,
7959 char **argv_expanded) NORETURN;
7960static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7961 char **argv, int assignment_cnt,
7962 char **argv_expanded)
7963{
Denys Vlasenko57000292018-01-12 14:41:45 +01007964 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007965 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007966 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007967 IF_HUSH_COMMAND(char opt_vV = 0;)
7968 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007969
7970 new_env = expand_assignments(argv, assignment_cnt);
7971 dump_cmd_in_x_mode(new_env);
7972
7973 if (!argv[assignment_cnt]) {
7974 /* Case when we are here: ... | var=val | ...
7975 * (note that we do not exit early, i.e., do not optimize out
7976 * expand_assignments(): think about ... | var=`sleep 1` | ...
7977 */
7978 free_strings(new_env);
7979 _exit(EXIT_SUCCESS);
7980 }
7981
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007982 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007983#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007984 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007985#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007986 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007987 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007988#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007989 set_vars_and_save_old(new_env);
7990 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007991
7992 if (argv_expanded) {
7993 argv = argv_expanded;
7994 } else {
7995 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7996#if !BB_MMU
7997 nommu_save->argv = argv;
7998#endif
7999 }
8000 dump_cmd_in_x_mode(argv);
8001
8002#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8003 if (strchr(argv[0], '/') != NULL)
8004 goto skip;
8005#endif
8006
Denys Vlasenko75481d32017-07-31 05:27:09 +02008007#if ENABLE_HUSH_FUNCTIONS
8008 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008009 funcp = find_function(argv[0]);
8010 if (funcp)
8011 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008012#endif
8013
Denys Vlasenko57000292018-01-12 14:41:45 +01008014#if ENABLE_HUSH_COMMAND
8015 /* "command BAR": run BAR without looking it up among functions
8016 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8017 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8018 */
8019 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8020 char *p;
8021
8022 argv++;
8023 p = *argv;
8024 if (p[0] != '-' || !p[1])
8025 continue; /* bash allows "command command command [-OPT] BAR" */
8026
8027 for (;;) {
8028 p++;
8029 switch (*p) {
8030 case '\0':
8031 argv++;
8032 p = *argv;
8033 if (p[0] != '-' || !p[1])
8034 goto after_opts;
8035 continue; /* next arg is also -opts, process it too */
8036 case 'v':
8037 case 'V':
8038 opt_vV = *p;
8039 continue;
8040 default:
8041 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8042 }
8043 }
8044 }
8045 after_opts:
8046# if ENABLE_HUSH_FUNCTIONS
8047 if (opt_vV && find_function(argv[0]))
8048 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8049# endif
8050#endif
8051
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008052 /* Check if the command matches any of the builtins.
8053 * Depending on context, this might be redundant. But it's
8054 * easier to waste a few CPU cycles than it is to figure out
8055 * if this is one of those cases.
8056 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008057 /* Why "BB_MMU ? :" difference in logic? -
8058 * On NOMMU, it is more expensive to re-execute shell
8059 * just in order to run echo or test builtin.
8060 * It's better to skip it here and run corresponding
8061 * non-builtin later. */
8062 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8063 if (x) {
8064 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8065 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008066 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008067
8068#if ENABLE_FEATURE_SH_STANDALONE
8069 /* Check if the command matches any busybox applets */
8070 {
8071 int a = find_applet_by_name(argv[0]);
8072 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008073 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008074# if BB_MMU /* see above why on NOMMU it is not allowed */
8075 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008076 /* Do not leak open fds from opened script files etc.
8077 * Testcase: interactive "ls -l /proc/self/fd"
8078 * should not show tty fd open.
8079 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008080 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008081//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008082//This casuses test failures in
8083//redir_children_should_not_see_saved_fd_2.tests
8084//redir_children_should_not_see_saved_fd_3.tests
8085//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008086 /* Without this, "rm -i FILE" can't be ^C'ed: */
8087 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008088 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008089 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008090 }
8091# endif
8092 /* Re-exec ourselves */
8093 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008094 /* Don't propagate SIG_IGN to the child */
8095 if (SPECIAL_JOBSTOP_SIGS != 0)
8096 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008097 execv(bb_busybox_exec_path, argv);
8098 /* If they called chroot or otherwise made the binary no longer
8099 * executable, fall through */
8100 }
8101 }
8102#endif
8103
8104#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8105 skip:
8106#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008107 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008108 execvp_or_die(argv);
8109}
8110
8111/* Called after [v]fork() in run_pipe
8112 */
8113static void pseudo_exec(nommu_save_t *nommu_save,
8114 struct command *command,
8115 char **argv_expanded) NORETURN;
8116static void pseudo_exec(nommu_save_t *nommu_save,
8117 struct command *command,
8118 char **argv_expanded)
8119{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008120#if ENABLE_HUSH_FUNCTIONS
8121 if (command->cmd_type == CMD_FUNCDEF) {
8122 /* Ignore funcdefs in pipes:
8123 * true | f() { cmd }
8124 */
8125 _exit(0);
8126 }
8127#endif
8128
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008129 if (command->argv) {
8130 pseudo_exec_argv(nommu_save, command->argv,
8131 command->assignment_cnt, argv_expanded);
8132 }
8133
8134 if (command->group) {
8135 /* Cases when we are here:
8136 * ( list )
8137 * { list } &
8138 * ... | ( list ) | ...
8139 * ... | { list } | ...
8140 */
8141#if BB_MMU
8142 int rcode;
8143 debug_printf_exec("pseudo_exec: run_list\n");
8144 reset_traps_to_defaults();
8145 rcode = run_list(command->group);
8146 /* OK to leak memory by not calling free_pipe_list,
8147 * since this process is about to exit */
8148 _exit(rcode);
8149#else
8150 re_execute_shell(&nommu_save->argv_from_re_execing,
8151 command->group_as_string,
8152 G.global_argv[0],
8153 G.global_argv + 1,
8154 NULL);
8155#endif
8156 }
8157
8158 /* Case when we are here: ... | >file */
8159 debug_printf_exec("pseudo_exec'ed null command\n");
8160 _exit(EXIT_SUCCESS);
8161}
8162
8163#if ENABLE_HUSH_JOB
8164static const char *get_cmdtext(struct pipe *pi)
8165{
8166 char **argv;
8167 char *p;
8168 int len;
8169
8170 /* This is subtle. ->cmdtext is created only on first backgrounding.
8171 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8172 * On subsequent bg argv is trashed, but we won't use it */
8173 if (pi->cmdtext)
8174 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008175
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008176 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008177 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008178 pi->cmdtext = xzalloc(1);
8179 return pi->cmdtext;
8180 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008181 len = 0;
8182 do {
8183 len += strlen(*argv) + 1;
8184 } while (*++argv);
8185 p = xmalloc(len);
8186 pi->cmdtext = p;
8187 argv = pi->cmds[0].argv;
8188 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008189 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008190 *p++ = ' ';
8191 } while (*++argv);
8192 p[-1] = '\0';
8193 return pi->cmdtext;
8194}
8195
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008196static void remove_job_from_table(struct pipe *pi)
8197{
8198 struct pipe *prev_pipe;
8199
8200 if (pi == G.job_list) {
8201 G.job_list = pi->next;
8202 } else {
8203 prev_pipe = G.job_list;
8204 while (prev_pipe->next != pi)
8205 prev_pipe = prev_pipe->next;
8206 prev_pipe->next = pi->next;
8207 }
8208 G.last_jobid = 0;
8209 if (G.job_list)
8210 G.last_jobid = G.job_list->jobid;
8211}
8212
8213static void delete_finished_job(struct pipe *pi)
8214{
8215 remove_job_from_table(pi);
8216 free_pipe(pi);
8217}
8218
8219static void clean_up_last_dead_job(void)
8220{
8221 if (G.job_list && !G.job_list->alive_cmds)
8222 delete_finished_job(G.job_list);
8223}
8224
Denys Vlasenko16096292017-07-10 10:00:28 +02008225static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008226{
8227 struct pipe *job, **jobp;
8228 int i;
8229
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008230 clean_up_last_dead_job();
8231
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008232 /* Find the end of the list, and find next job ID to use */
8233 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008234 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008235 while ((job = *jobp) != NULL) {
8236 if (job->jobid > i)
8237 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008238 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008239 }
8240 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008241
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008242 /* Create a new job struct at the end */
8243 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008244 job->next = NULL;
8245 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8246 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8247 for (i = 0; i < pi->num_cmds; i++) {
8248 job->cmds[i].pid = pi->cmds[i].pid;
8249 /* all other fields are not used and stay zero */
8250 }
8251 job->cmdtext = xstrdup(get_cmdtext(pi));
8252
8253 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008254 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008255 G.last_jobid = job->jobid;
8256}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008257#endif /* JOB */
8258
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008259static int job_exited_or_stopped(struct pipe *pi)
8260{
8261 int rcode, i;
8262
8263 if (pi->alive_cmds != pi->stopped_cmds)
8264 return -1;
8265
8266 /* All processes in fg pipe have exited or stopped */
8267 rcode = 0;
8268 i = pi->num_cmds;
8269 while (--i >= 0) {
8270 rcode = pi->cmds[i].cmd_exitcode;
8271 /* usually last process gives overall exitstatus,
8272 * but with "set -o pipefail", last *failed* process does */
8273 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8274 break;
8275 }
8276 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8277 return rcode;
8278}
8279
Denys Vlasenko7e675362016-10-28 21:57:31 +02008280static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008281{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008282#if ENABLE_HUSH_JOB
8283 struct pipe *pi;
8284#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008285 int i, dead;
8286
8287 dead = WIFEXITED(status) || WIFSIGNALED(status);
8288
8289#if DEBUG_JOBS
8290 if (WIFSTOPPED(status))
8291 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8292 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8293 if (WIFSIGNALED(status))
8294 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8295 childpid, WTERMSIG(status), WEXITSTATUS(status));
8296 if (WIFEXITED(status))
8297 debug_printf_jobs("pid %d exited, exitcode %d\n",
8298 childpid, WEXITSTATUS(status));
8299#endif
8300 /* Were we asked to wait for a fg pipe? */
8301 if (fg_pipe) {
8302 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008303
Denys Vlasenko7e675362016-10-28 21:57:31 +02008304 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008305 int rcode;
8306
Denys Vlasenko7e675362016-10-28 21:57:31 +02008307 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8308 if (fg_pipe->cmds[i].pid != childpid)
8309 continue;
8310 if (dead) {
8311 int ex;
8312 fg_pipe->cmds[i].pid = 0;
8313 fg_pipe->alive_cmds--;
8314 ex = WEXITSTATUS(status);
8315 /* bash prints killer signal's name for *last*
8316 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8317 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8318 */
8319 if (WIFSIGNALED(status)) {
8320 int sig = WTERMSIG(status);
8321 if (i == fg_pipe->num_cmds-1)
8322 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8323 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8324 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8325 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8326 * Maybe we need to use sig | 128? */
8327 ex = sig + 128;
8328 }
8329 fg_pipe->cmds[i].cmd_exitcode = ex;
8330 } else {
8331 fg_pipe->stopped_cmds++;
8332 }
8333 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8334 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008335 rcode = job_exited_or_stopped(fg_pipe);
8336 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008337/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8338 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8339 * and "killall -STOP cat" */
8340 if (G_interactive_fd) {
8341#if ENABLE_HUSH_JOB
8342 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008343 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008344#endif
8345 return rcode;
8346 }
8347 if (fg_pipe->alive_cmds == 0)
8348 return rcode;
8349 }
8350 /* There are still running processes in the fg_pipe */
8351 return -1;
8352 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008353 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008354 }
8355
8356#if ENABLE_HUSH_JOB
8357 /* We were asked to wait for bg or orphaned children */
8358 /* No need to remember exitcode in this case */
8359 for (pi = G.job_list; pi; pi = pi->next) {
8360 for (i = 0; i < pi->num_cmds; i++) {
8361 if (pi->cmds[i].pid == childpid)
8362 goto found_pi_and_prognum;
8363 }
8364 }
8365 /* Happens when shell is used as init process (init=/bin/sh) */
8366 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8367 return -1; /* this wasn't a process from fg_pipe */
8368
8369 found_pi_and_prognum:
8370 if (dead) {
8371 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008372 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008373 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008374 rcode = 128 + WTERMSIG(status);
8375 pi->cmds[i].cmd_exitcode = rcode;
8376 if (G.last_bg_pid == pi->cmds[i].pid)
8377 G.last_bg_pid_exitcode = rcode;
8378 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008379 pi->alive_cmds--;
8380 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008381 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008382 printf(JOB_STATUS_FORMAT, pi->jobid,
8383 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008384 delete_finished_job(pi);
8385 } else {
8386/*
8387 * bash deletes finished jobs from job table only in interactive mode,
8388 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8389 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8390 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8391 * We only retain one "dead" job, if it's the single job on the list.
8392 * This covers most of real-world scenarios where this is useful.
8393 */
8394 if (pi != G.job_list)
8395 delete_finished_job(pi);
8396 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008397 }
8398 } else {
8399 /* child stopped */
8400 pi->stopped_cmds++;
8401 }
8402#endif
8403 return -1; /* this wasn't a process from fg_pipe */
8404}
8405
8406/* Check to see if any processes have exited -- if they have,
8407 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008408 *
8409 * If non-NULL fg_pipe: wait for its completion or stop.
8410 * Return its exitcode or zero if stopped.
8411 *
8412 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8413 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8414 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8415 * or 0 if no children changed status.
8416 *
8417 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8418 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8419 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008420 */
8421static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8422{
8423 int attributes;
8424 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008425 int rcode = 0;
8426
8427 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8428
8429 attributes = WUNTRACED;
8430 if (fg_pipe == NULL)
8431 attributes |= WNOHANG;
8432
8433 errno = 0;
8434#if ENABLE_HUSH_FAST
8435 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8436//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8437//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8438 /* There was neither fork nor SIGCHLD since last waitpid */
8439 /* Avoid doing waitpid syscall if possible */
8440 if (!G.we_have_children) {
8441 errno = ECHILD;
8442 return -1;
8443 }
8444 if (fg_pipe == NULL) { /* is WNOHANG set? */
8445 /* We have children, but they did not exit
8446 * or stop yet (we saw no SIGCHLD) */
8447 return 0;
8448 }
8449 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8450 }
8451#endif
8452
8453/* Do we do this right?
8454 * bash-3.00# sleep 20 | false
8455 * <ctrl-Z pressed>
8456 * [3]+ Stopped sleep 20 | false
8457 * bash-3.00# echo $?
8458 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8459 * [hush 1.14.0: yes we do it right]
8460 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008461 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008462 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008463#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008464 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008465 i = G.count_SIGCHLD;
8466#endif
8467 childpid = waitpid(-1, &status, attributes);
8468 if (childpid <= 0) {
8469 if (childpid && errno != ECHILD)
8470 bb_perror_msg("waitpid");
8471#if ENABLE_HUSH_FAST
8472 else { /* Until next SIGCHLD, waitpid's are useless */
8473 G.we_have_children = (childpid == 0);
8474 G.handled_SIGCHLD = i;
8475//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8476 }
8477#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008478 /* ECHILD (no children), or 0 (no change in children status) */
8479 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008480 break;
8481 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008482 rcode = process_wait_result(fg_pipe, childpid, status);
8483 if (rcode >= 0) {
8484 /* fg_pipe exited or stopped */
8485 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008486 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008487 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008488 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008489 rcode = WEXITSTATUS(status);
8490 if (WIFSIGNALED(status))
8491 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008492 if (WIFSTOPPED(status))
8493 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8494 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008495 rcode++;
8496 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008497 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008498 /* This wasn't one of our processes, or */
8499 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008500 } /* while (waitpid succeeds)... */
8501
8502 return rcode;
8503}
8504
8505#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008506static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008507{
8508 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008509 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008510 if (G_saved_tty_pgrp) {
8511 /* Job finished, move the shell to the foreground */
8512 p = getpgrp(); /* our process group id */
8513 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8514 tcsetpgrp(G_interactive_fd, p);
8515 }
8516 return rcode;
8517}
8518#endif
8519
8520/* Start all the jobs, but don't wait for anything to finish.
8521 * See checkjobs().
8522 *
8523 * Return code is normally -1, when the caller has to wait for children
8524 * to finish to determine the exit status of the pipe. If the pipe
8525 * is a simple builtin command, however, the action is done by the
8526 * time run_pipe returns, and the exit code is provided as the
8527 * return value.
8528 *
8529 * Returns -1 only if started some children. IOW: we have to
8530 * mask out retvals of builtins etc with 0xff!
8531 *
8532 * The only case when we do not need to [v]fork is when the pipe
8533 * is single, non-backgrounded, non-subshell command. Examples:
8534 * cmd ; ... { list } ; ...
8535 * cmd && ... { list } && ...
8536 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008537 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008538 * or (if SH_STANDALONE) an applet, and we can run the { list }
8539 * with run_list. If it isn't one of these, we fork and exec cmd.
8540 *
8541 * Cases when we must fork:
8542 * non-single: cmd | cmd
8543 * backgrounded: cmd & { list } &
8544 * subshell: ( list ) [&]
8545 */
8546#if !ENABLE_HUSH_MODE_X
Denys Vlasenkoc96bb2c2018-06-26 15:43:56 +02008547#define redirect_and_varexp_helper(command, squirrel, argv_expanded) \
8548 redirect_and_varexp_helper(command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008549#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008550static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008551 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008552 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008553 char **argv_expanded)
8554{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008555 /* Assignments occur before redirects. Try:
8556 * a=`sleep 1` sleep 2 3>/qwe/rty
8557 */
8558
8559 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8560 dump_cmd_in_x_mode(new_env);
8561 dump_cmd_in_x_mode(argv_expanded);
8562 /* this takes ownership of new_env[i] elements, and frees new_env: */
8563 set_vars_and_save_old(new_env);
8564
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008565 /* setup_redirects acts on file descriptors, not FILEs.
8566 * This is perfect for work that comes after exec().
8567 * Is it really safe for inline use? Experimentally,
8568 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008569 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008570}
8571static NOINLINE int run_pipe(struct pipe *pi)
8572{
8573 static const char *const null_ptr = NULL;
8574
8575 int cmd_no;
8576 int next_infd;
8577 struct command *command;
8578 char **argv_expanded;
8579 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008580 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008581 int rcode;
8582
8583 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8584 debug_enter();
8585
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008586 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8587 * Result should be 3 lines: q w e, qwe, q w e
8588 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008589 if (G.ifs_whitespace != G.ifs)
8590 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008591 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008592 if (G.ifs) {
8593 char *p;
8594 G.ifs_whitespace = (char*)G.ifs;
8595 p = skip_whitespace(G.ifs);
8596 if (*p) {
8597 /* Not all $IFS is whitespace */
8598 char *d;
8599 int len = p - G.ifs;
8600 p = skip_non_whitespace(p);
8601 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8602 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8603 while (*p) {
8604 if (isspace(*p))
8605 *d++ = *p;
8606 p++;
8607 }
8608 *d = '\0';
8609 }
8610 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008611 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008612 G.ifs_whitespace = (char*)G.ifs;
8613 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008614
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008615 IF_HUSH_JOB(pi->pgrp = -1;)
8616 pi->stopped_cmds = 0;
8617 command = &pi->cmds[0];
8618 argv_expanded = NULL;
8619
8620 if (pi->num_cmds != 1
8621 || pi->followup == PIPE_BG
8622 || command->cmd_type == CMD_SUBSHELL
8623 ) {
8624 goto must_fork;
8625 }
8626
8627 pi->alive_cmds = 1;
8628
8629 debug_printf_exec(": group:%p argv:'%s'\n",
8630 command->group, command->argv ? command->argv[0] : "NONE");
8631
8632 if (command->group) {
8633#if ENABLE_HUSH_FUNCTIONS
8634 if (command->cmd_type == CMD_FUNCDEF) {
8635 /* "executing" func () { list } */
8636 struct function *funcp;
8637
8638 funcp = new_function(command->argv[0]);
8639 /* funcp->name is already set to argv[0] */
8640 funcp->body = command->group;
8641# if !BB_MMU
8642 funcp->body_as_string = command->group_as_string;
8643 command->group_as_string = NULL;
8644# endif
8645 command->group = NULL;
8646 command->argv[0] = NULL;
8647 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8648 funcp->parent_cmd = command;
8649 command->child_func = funcp;
8650
8651 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8652 debug_leave();
8653 return EXIT_SUCCESS;
8654 }
8655#endif
8656 /* { list } */
8657 debug_printf("non-subshell group\n");
8658 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008659 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008660 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008661//FIXME: we need to pass squirrel down into run_list()
8662//for SH_STANDALONE case, or else this construct:
8663// { find /proc/self/fd; true; } >FILE; cmd2
8664//has no way of closing saved fd#1 for "find",
8665//and in SH_STANDALONE mode, "find" is not execed,
8666//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008667 rcode = run_list(command->group) & 0xff;
8668 }
8669 restore_redirects(squirrel);
8670 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8671 debug_leave();
8672 debug_printf_exec("run_pipe: return %d\n", rcode);
8673 return rcode;
8674 }
8675
8676 argv = command->argv ? command->argv : (char **) &null_ptr;
8677 {
8678 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008679 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8680 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008681 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008682 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008683
Denys Vlasenko5807e182018-02-08 19:19:04 +01008684#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008685 if (G.lineno_var)
8686 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8687#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008688
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008689 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008690 /* Assignments, but no command.
8691 * Ensure redirects take effect (that is, create files).
8692 * Try "a=t >file"
8693 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008694 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008695 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008696 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008697 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008698 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008699
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008700 /* Set shell variables */
8701 if (G_x_mode)
8702 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008703 i = 0;
8704 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008705 char *p = expand_string_to_string(argv[i],
8706 EXP_FLAG_ESC_GLOB_CHARS,
8707 /*unbackslash:*/ 1
8708 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008709 if (G_x_mode)
8710 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008711 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008712 if (set_local_var(p, /*flag:*/ 0)) {
8713 /* assignment to readonly var / putenv error? */
8714 rcode = 1;
8715 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008716 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008717 }
8718 if (G_x_mode)
8719 bb_putchar_stderr('\n');
8720 /* Redirect error sets $? to 1. Otherwise,
8721 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008722 * Else, clear $?:
8723 * false; q=`exit 2`; echo $? - should print 2
8724 * false; x=1; echo $? - should print 0
8725 * Because of the 2nd case, we can't just use G.last_exitcode.
8726 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008727 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008728 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008729 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8730 debug_leave();
8731 debug_printf_exec("run_pipe: return %d\n", rcode);
8732 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008733 }
8734
8735 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008736#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008737 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008738 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008739 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008740#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008741 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008742
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008743 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008744 if (!argv_expanded[0]) {
8745 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008746 /* `false` still has to set exitcode 1 */
8747 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008748 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008749 }
8750
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008751 old_vars = NULL;
8752 sv_shadowed = G.shadowed_vars_pp;
8753
Denys Vlasenko75481d32017-07-31 05:27:09 +02008754 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008755 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8756 IF_HUSH_FUNCTIONS(x = NULL;)
8757 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008758 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008759 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008760 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8761 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008762 /*
8763 * Variable assignments are executed, but then "forgotten":
8764 * a=`sleep 1;echo A` exec 3>&-; echo $a
8765 * sleeps, but prints nothing.
8766 */
8767 enter_var_nest_level();
8768 G.shadowed_vars_pp = &old_vars;
8769 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8770 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008771 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008772
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008773 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008774 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008775
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008776 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008777 * a=b true; env | grep ^a=
8778 */
8779 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008780 /* Collect all variables "shadowed" by helper
8781 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8782 * into old_vars list:
8783 */
8784 G.shadowed_vars_pp = &old_vars;
8785 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008786 if (rcode == 0) {
8787 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008788 /* Do not collect *to old_vars list* vars shadowed
8789 * by e.g. "local VAR" builtin (collect them
8790 * in the previously nested list instead):
8791 * don't want them to be restored immediately
8792 * after "local" completes.
8793 */
8794 G.shadowed_vars_pp = sv_shadowed;
8795
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008796 debug_printf_exec(": builtin '%s' '%s'...\n",
8797 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008798 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008799 rcode = x->b_function(argv_expanded) & 0xff;
8800 fflush_all();
8801 }
8802#if ENABLE_HUSH_FUNCTIONS
8803 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008804 debug_printf_exec(": function '%s' '%s'...\n",
8805 funcp->name, argv_expanded[1]);
8806 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008807 /*
8808 * But do collect *to old_vars list* vars shadowed
8809 * within function execution. To that end, restore
8810 * this pointer _after_ function run:
8811 */
8812 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008813 }
8814#endif
8815 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008816 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008817 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008818 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008819 if (n < 0 || !APPLET_IS_NOFORK(n))
8820 goto must_fork;
8821
8822 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008823 /* Collect all variables "shadowed" by helper into old_vars list */
8824 G.shadowed_vars_pp = &old_vars;
8825 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8826 G.shadowed_vars_pp = sv_shadowed;
8827
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008828 if (rcode == 0) {
8829 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8830 argv_expanded[0], argv_expanded[1]);
8831 /*
8832 * Note: signals (^C) can't interrupt here.
8833 * We remember them and they will be acted upon
8834 * after applet returns.
8835 * This makes applets which can run for a long time
8836 * and/or wait for user input ineligible for NOFORK:
8837 * for example, "yes" or "rm" (rm -i waits for input).
8838 */
8839 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008840 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008841 } else
8842 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008843
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008844 restore_redirects(squirrel);
8845 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008846 leave_var_nest_level();
8847 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008848
8849 /*
8850 * Try "usleep 99999999" + ^C + "echo $?"
8851 * with FEATURE_SH_NOFORK=y.
8852 */
8853 if (!funcp) {
8854 /* It was builtin or nofork.
8855 * if this would be a real fork/execed program,
8856 * it should have died if a fatal sig was received.
8857 * But OTOH, there was no separate process,
8858 * the sig was sent to _shell_, not to non-existing
8859 * child.
8860 * Let's just handle ^C only, this one is obvious:
8861 * we aren't ok with exitcode 0 when ^C was pressed
8862 * during builtin/nofork.
8863 */
8864 if (sigismember(&G.pending_set, SIGINT))
8865 rcode = 128 + SIGINT;
8866 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008867 free(argv_expanded);
8868 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8869 debug_leave();
8870 debug_printf_exec("run_pipe return %d\n", rcode);
8871 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008872 }
8873
8874 must_fork:
8875 /* NB: argv_expanded may already be created, and that
8876 * might include `cmd` runs! Do not rerun it! We *must*
8877 * use argv_expanded if it's non-NULL */
8878
8879 /* Going to fork a child per each pipe member */
8880 pi->alive_cmds = 0;
8881 next_infd = 0;
8882
8883 cmd_no = 0;
8884 while (cmd_no < pi->num_cmds) {
8885 struct fd_pair pipefds;
8886#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008887 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008888 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008889 nommu_save.old_vars = NULL;
8890 nommu_save.argv = NULL;
8891 nommu_save.argv_from_re_execing = NULL;
8892#endif
8893 command = &pi->cmds[cmd_no];
8894 cmd_no++;
8895 if (command->argv) {
8896 debug_printf_exec(": pipe member '%s' '%s'...\n",
8897 command->argv[0], command->argv[1]);
8898 } else {
8899 debug_printf_exec(": pipe member with no argv\n");
8900 }
8901
8902 /* pipes are inserted between pairs of commands */
8903 pipefds.rd = 0;
8904 pipefds.wr = 1;
8905 if (cmd_no < pi->num_cmds)
8906 xpiped_pair(pipefds);
8907
Denys Vlasenko5807e182018-02-08 19:19:04 +01008908#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008909 if (G.lineno_var)
8910 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8911#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008912
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008913 command->pid = BB_MMU ? fork() : vfork();
8914 if (!command->pid) { /* child */
8915#if ENABLE_HUSH_JOB
8916 disable_restore_tty_pgrp_on_exit();
8917 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8918
8919 /* Every child adds itself to new process group
8920 * with pgid == pid_of_first_child_in_pipe */
8921 if (G.run_list_level == 1 && G_interactive_fd) {
8922 pid_t pgrp;
8923 pgrp = pi->pgrp;
8924 if (pgrp < 0) /* true for 1st process only */
8925 pgrp = getpid();
8926 if (setpgid(0, pgrp) == 0
8927 && pi->followup != PIPE_BG
8928 && G_saved_tty_pgrp /* we have ctty */
8929 ) {
8930 /* We do it in *every* child, not just first,
8931 * to avoid races */
8932 tcsetpgrp(G_interactive_fd, pgrp);
8933 }
8934 }
8935#endif
8936 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8937 /* 1st cmd in backgrounded pipe
8938 * should have its stdin /dev/null'ed */
8939 close(0);
8940 if (open(bb_dev_null, O_RDONLY))
8941 xopen("/", O_RDONLY);
8942 } else {
8943 xmove_fd(next_infd, 0);
8944 }
8945 xmove_fd(pipefds.wr, 1);
8946 if (pipefds.rd > 1)
8947 close(pipefds.rd);
8948 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008949 * and the pipe fd (fd#1) is available for dup'ing:
8950 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8951 * of cmd1 goes into pipe.
8952 */
8953 if (setup_redirects(command, NULL)) {
8954 /* Happens when redir file can't be opened:
8955 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8956 * FOO
8957 * hush: can't open '/qwe/rty': No such file or directory
8958 * BAZ
8959 * (echo BAR is not executed, it hits _exit(1) below)
8960 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008961 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008962 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008963
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008964 /* Stores to nommu_save list of env vars putenv'ed
8965 * (NOMMU, on MMU we don't need that) */
8966 /* cast away volatility... */
8967 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8968 /* pseudo_exec() does not return */
8969 }
8970
8971 /* parent or error */
8972#if ENABLE_HUSH_FAST
8973 G.count_SIGCHLD++;
8974//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8975#endif
8976 enable_restore_tty_pgrp_on_exit();
8977#if !BB_MMU
8978 /* Clean up after vforked child */
8979 free(nommu_save.argv);
8980 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008981 G.var_nest_level = sv_var_nest_level;
8982 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008983 add_vars(nommu_save.old_vars);
8984#endif
8985 free(argv_expanded);
8986 argv_expanded = NULL;
8987 if (command->pid < 0) { /* [v]fork failed */
8988 /* Clearly indicate, was it fork or vfork */
8989 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8990 } else {
8991 pi->alive_cmds++;
8992#if ENABLE_HUSH_JOB
8993 /* Second and next children need to know pid of first one */
8994 if (pi->pgrp < 0)
8995 pi->pgrp = command->pid;
8996#endif
8997 }
8998
8999 if (cmd_no > 1)
9000 close(next_infd);
9001 if (cmd_no < pi->num_cmds)
9002 close(pipefds.wr);
9003 /* Pass read (output) pipe end to next iteration */
9004 next_infd = pipefds.rd;
9005 }
9006
9007 if (!pi->alive_cmds) {
9008 debug_leave();
9009 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9010 return 1;
9011 }
9012
9013 debug_leave();
9014 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9015 return -1;
9016}
9017
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009018/* NB: called by pseudo_exec, and therefore must not modify any
9019 * global data until exec/_exit (we can be a child after vfork!) */
9020static int run_list(struct pipe *pi)
9021{
9022#if ENABLE_HUSH_CASE
9023 char *case_word = NULL;
9024#endif
9025#if ENABLE_HUSH_LOOPS
9026 struct pipe *loop_top = NULL;
9027 char **for_lcur = NULL;
9028 char **for_list = NULL;
9029#endif
9030 smallint last_followup;
9031 smalluint rcode;
9032#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9033 smalluint cond_code = 0;
9034#else
9035 enum { cond_code = 0 };
9036#endif
9037#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009038 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009039 smallint last_rword; /* ditto */
9040#endif
9041
9042 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9043 debug_enter();
9044
9045#if ENABLE_HUSH_LOOPS
9046 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009047 {
9048 struct pipe *cpipe;
9049 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9050 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9051 continue;
9052 /* current word is FOR or IN (BOLD in comments below) */
9053 if (cpipe->next == NULL) {
9054 syntax_error("malformed for");
9055 debug_leave();
9056 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9057 return 1;
9058 }
9059 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9060 if (cpipe->next->res_word == RES_DO)
9061 continue;
9062 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9063 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9064 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9065 ) {
9066 syntax_error("malformed for");
9067 debug_leave();
9068 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9069 return 1;
9070 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009071 }
9072 }
9073#endif
9074
9075 /* Past this point, all code paths should jump to ret: label
9076 * in order to return, no direct "return" statements please.
9077 * This helps to ensure that no memory is leaked. */
9078
9079#if ENABLE_HUSH_JOB
9080 G.run_list_level++;
9081#endif
9082
9083#if HAS_KEYWORDS
9084 rword = RES_NONE;
9085 last_rword = RES_XXXX;
9086#endif
9087 last_followup = PIPE_SEQ;
9088 rcode = G.last_exitcode;
9089
9090 /* Go through list of pipes, (maybe) executing them. */
9091 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009092 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009093 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009094
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009095 if (G.flag_SIGINT)
9096 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009097 if (G_flag_return_in_progress == 1)
9098 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009099
9100 IF_HAS_KEYWORDS(rword = pi->res_word;)
9101 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9102 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009103
9104 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009105 if (
9106#if ENABLE_HUSH_IF
9107 rword == RES_IF || rword == RES_ELIF ||
9108#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009109 pi->followup != PIPE_SEQ
9110 ) {
9111 G.errexit_depth++;
9112 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009113#if ENABLE_HUSH_LOOPS
9114 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9115 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9116 ) {
9117 /* start of a loop: remember where loop starts */
9118 loop_top = pi;
9119 G.depth_of_loop++;
9120 }
9121#endif
9122 /* Still in the same "if...", "then..." or "do..." branch? */
9123 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9124 if ((rcode == 0 && last_followup == PIPE_OR)
9125 || (rcode != 0 && last_followup == PIPE_AND)
9126 ) {
9127 /* It is "<true> || CMD" or "<false> && CMD"
9128 * and we should not execute CMD */
9129 debug_printf_exec("skipped cmd because of || or &&\n");
9130 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009131 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009132 }
9133 }
9134 last_followup = pi->followup;
9135 IF_HAS_KEYWORDS(last_rword = rword;)
9136#if ENABLE_HUSH_IF
9137 if (cond_code) {
9138 if (rword == RES_THEN) {
9139 /* if false; then ... fi has exitcode 0! */
9140 G.last_exitcode = rcode = EXIT_SUCCESS;
9141 /* "if <false> THEN cmd": skip cmd */
9142 continue;
9143 }
9144 } else {
9145 if (rword == RES_ELSE || rword == RES_ELIF) {
9146 /* "if <true> then ... ELSE/ELIF cmd":
9147 * skip cmd and all following ones */
9148 break;
9149 }
9150 }
9151#endif
9152#if ENABLE_HUSH_LOOPS
9153 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9154 if (!for_lcur) {
9155 /* first loop through for */
9156
9157 static const char encoded_dollar_at[] ALIGN1 = {
9158 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9159 }; /* encoded representation of "$@" */
9160 static const char *const encoded_dollar_at_argv[] = {
9161 encoded_dollar_at, NULL
9162 }; /* argv list with one element: "$@" */
9163 char **vals;
9164
9165 vals = (char**)encoded_dollar_at_argv;
9166 if (pi->next->res_word == RES_IN) {
9167 /* if no variable values after "in" we skip "for" */
9168 if (!pi->next->cmds[0].argv) {
9169 G.last_exitcode = rcode = EXIT_SUCCESS;
9170 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9171 break;
9172 }
9173 vals = pi->next->cmds[0].argv;
9174 } /* else: "for var; do..." -> assume "$@" list */
9175 /* create list of variable values */
9176 debug_print_strings("for_list made from", vals);
9177 for_list = expand_strvec_to_strvec(vals);
9178 for_lcur = for_list;
9179 debug_print_strings("for_list", for_list);
9180 }
9181 if (!*for_lcur) {
9182 /* "for" loop is over, clean up */
9183 free(for_list);
9184 for_list = NULL;
9185 for_lcur = NULL;
9186 break;
9187 }
9188 /* Insert next value from for_lcur */
9189 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009190 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009191 continue;
9192 }
9193 if (rword == RES_IN) {
9194 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9195 }
9196 if (rword == RES_DONE) {
9197 continue; /* "done" has no cmds too */
9198 }
9199#endif
9200#if ENABLE_HUSH_CASE
9201 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009202 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009203 case_word = expand_string_to_string(pi->cmds->argv[0],
9204 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009205 debug_printf_exec("CASE word1:'%s'\n", case_word);
9206 //unbackslash(case_word);
9207 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009208 continue;
9209 }
9210 if (rword == RES_MATCH) {
9211 char **argv;
9212
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009213 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009214 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9215 break;
9216 /* all prev words didn't match, does this one match? */
9217 argv = pi->cmds->argv;
9218 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009219 char *pattern;
9220 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9221 pattern = expand_string_to_string(*argv,
9222 EXP_FLAG_ESC_GLOB_CHARS,
9223 /*unbackslash:*/ 0
9224 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009225 /* TODO: which FNM_xxx flags to use? */
9226 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009227 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9228 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009229 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009230 if (cond_code == 0) {
9231 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009232 free(case_word);
9233 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009234 break;
9235 }
9236 argv++;
9237 }
9238 continue;
9239 }
9240 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009241 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009242 if (cond_code != 0)
9243 continue; /* not matched yet, skip this pipe */
9244 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009245 if (rword == RES_ESAC) {
9246 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9247 if (case_word) {
9248 /* "case" did not match anything: still set $? (to 0) */
9249 G.last_exitcode = rcode = EXIT_SUCCESS;
9250 }
9251 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009252#endif
9253 /* Just pressing <enter> in shell should check for jobs.
9254 * OTOH, in non-interactive shell this is useless
9255 * and only leads to extra job checks */
9256 if (pi->num_cmds == 0) {
9257 if (G_interactive_fd)
9258 goto check_jobs_and_continue;
9259 continue;
9260 }
9261
9262 /* After analyzing all keywords and conditions, we decided
9263 * to execute this pipe. NB: have to do checkjobs(NULL)
9264 * after run_pipe to collect any background children,
9265 * even if list execution is to be stopped. */
9266 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009267#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009268 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009269#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009270 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9271 if (r != -1) {
9272 /* We ran a builtin, function, or group.
9273 * rcode is already known
9274 * and we don't need to wait for anything. */
9275 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9276 G.last_exitcode = rcode;
9277 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009278#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009279 /* Was it "break" or "continue"? */
9280 if (G.flag_break_continue) {
9281 smallint fbc = G.flag_break_continue;
9282 /* We might fall into outer *loop*,
9283 * don't want to break it too */
9284 if (loop_top) {
9285 G.depth_break_continue--;
9286 if (G.depth_break_continue == 0)
9287 G.flag_break_continue = 0;
9288 /* else: e.g. "continue 2" should *break* once, *then* continue */
9289 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9290 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009291 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009292 break;
9293 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009294 /* "continue": simulate end of loop */
9295 rword = RES_DONE;
9296 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009297 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009298#endif
9299 if (G_flag_return_in_progress == 1) {
9300 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9301 break;
9302 }
9303 } else if (pi->followup == PIPE_BG) {
9304 /* What does bash do with attempts to background builtins? */
9305 /* even bash 3.2 doesn't do that well with nested bg:
9306 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9307 * I'm NOT treating inner &'s as jobs */
9308#if ENABLE_HUSH_JOB
9309 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009310 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009311#endif
9312 /* Last command's pid goes to $! */
9313 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009314 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009315 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009316/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009317 rcode = EXIT_SUCCESS;
9318 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009319 } else {
9320#if ENABLE_HUSH_JOB
9321 if (G.run_list_level == 1 && G_interactive_fd) {
9322 /* Waits for completion, then fg's main shell */
9323 rcode = checkjobs_and_fg_shell(pi);
9324 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009325 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009326 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009327#endif
9328 /* This one just waits for completion */
9329 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9330 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9331 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009332 G.last_exitcode = rcode;
9333 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009334 }
9335
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009336 /* Handle "set -e" */
9337 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9338 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9339 if (G.errexit_depth == 0)
9340 hush_exit(rcode);
9341 }
9342 G.errexit_depth = sv_errexit_depth;
9343
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009344 /* Analyze how result affects subsequent commands */
9345#if ENABLE_HUSH_IF
9346 if (rword == RES_IF || rword == RES_ELIF)
9347 cond_code = rcode;
9348#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009349 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009350 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009351 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009352#if ENABLE_HUSH_LOOPS
9353 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009354 if (pi->next
9355 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009356 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009357 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009358 if (rword == RES_WHILE) {
9359 if (rcode) {
9360 /* "while false; do...done" - exitcode 0 */
9361 G.last_exitcode = rcode = EXIT_SUCCESS;
9362 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009363 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009364 }
9365 }
9366 if (rword == RES_UNTIL) {
9367 if (!rcode) {
9368 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009369 break;
9370 }
9371 }
9372 }
9373#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009374 } /* for (pi) */
9375
9376#if ENABLE_HUSH_JOB
9377 G.run_list_level--;
9378#endif
9379#if ENABLE_HUSH_LOOPS
9380 if (loop_top)
9381 G.depth_of_loop--;
9382 free(for_list);
9383#endif
9384#if ENABLE_HUSH_CASE
9385 free(case_word);
9386#endif
9387 debug_leave();
9388 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9389 return rcode;
9390}
9391
9392/* Select which version we will use */
9393static int run_and_free_list(struct pipe *pi)
9394{
9395 int rcode = 0;
9396 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009397 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009398 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9399 rcode = run_list(pi);
9400 }
9401 /* free_pipe_list has the side effect of clearing memory.
9402 * In the long run that function can be merged with run_list,
9403 * but doing that now would hobble the debugging effort. */
9404 free_pipe_list(pi);
9405 debug_printf_exec("run_and_free_list return %d\n", rcode);
9406 return rcode;
9407}
9408
9409
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009410static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009411{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009412 sighandler_t old_handler;
9413 unsigned sig = 0;
9414 while ((mask >>= 1) != 0) {
9415 sig++;
9416 if (!(mask & 1))
9417 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009418 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009419 /* POSIX allows shell to re-enable SIGCHLD
9420 * even if it was SIG_IGN on entry.
9421 * Therefore we skip IGN check for it:
9422 */
9423 if (sig == SIGCHLD)
9424 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009425 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9426 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9427 */
9428 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009429 if (old_handler == SIG_IGN) {
9430 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009431 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009432#if ENABLE_HUSH_TRAP
9433 if (!G_traps)
9434 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9435 free(G_traps[sig]);
9436 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9437#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009438 }
9439 }
9440}
9441
9442/* Called a few times only (or even once if "sh -c") */
9443static void install_special_sighandlers(void)
9444{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009445 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009446
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009447 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009448 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009449 if (G_interactive_fd) {
9450 mask |= SPECIAL_INTERACTIVE_SIGS;
9451 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009452 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009453 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009454 /* Careful, do not re-install handlers we already installed */
9455 if (G.special_sig_mask != mask) {
9456 unsigned diff = mask & ~G.special_sig_mask;
9457 G.special_sig_mask = mask;
9458 install_sighandlers(diff);
9459 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009460}
9461
9462#if ENABLE_HUSH_JOB
9463/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009464/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009465static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009466{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009467 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009468
9469 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009470 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009471 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9472 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009473 + (1 << SIGBUS ) * HUSH_DEBUG
9474 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009475 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009476 + (1 << SIGABRT)
9477 /* bash 3.2 seems to handle these just like 'fatal' ones */
9478 + (1 << SIGPIPE)
9479 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009480 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009481 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009482 * we never want to restore pgrp on exit, and this fn is not called
9483 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009484 /*+ (1 << SIGHUP )*/
9485 /*+ (1 << SIGTERM)*/
9486 /*+ (1 << SIGINT )*/
9487 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009488 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009489
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009490 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009491}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009492#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009493
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009494static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009495{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009496 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009497 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009498 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009499 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009500 break;
9501 case 'x':
9502 IF_HUSH_MODE_X(G_x_mode = state;)
9503 break;
9504 case 'o':
9505 if (!o_opt) {
9506 /* "set -+o" without parameter.
9507 * in bash, set -o produces this output:
9508 * pipefail off
9509 * and set +o:
9510 * set +o pipefail
9511 * We always use the second form.
9512 */
9513 const char *p = o_opt_strings;
9514 idx = 0;
9515 while (*p) {
9516 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9517 idx++;
9518 p += strlen(p) + 1;
9519 }
9520 break;
9521 }
9522 idx = index_in_strings(o_opt_strings, o_opt);
9523 if (idx >= 0) {
9524 G.o_opt[idx] = state;
9525 break;
9526 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009527 case 'e':
9528 G.o_opt[OPT_O_ERREXIT] = state;
9529 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009530 default:
9531 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009532 }
9533 return EXIT_SUCCESS;
9534}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009535
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009536int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009537int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009538{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009539 enum {
9540 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009541 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009542 };
9543 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009544 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009545 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009546 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009547 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009548
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009549 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009550 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009551 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009552
Denys Vlasenko10c01312011-05-11 11:49:21 +02009553#if ENABLE_HUSH_FAST
9554 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9555#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009556#if !BB_MMU
9557 G.argv0_for_re_execing = argv[0];
9558#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009559
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009560 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009561 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9562 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009563 shell_ver = xzalloc(sizeof(*shell_ver));
9564 shell_ver->flg_export = 1;
9565 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009566 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009567 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009568 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009569
Denys Vlasenko605067b2010-09-06 12:10:51 +02009570 /* Create shell local variables from the values
9571 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009572 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009573 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009574 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009575 if (e) while (*e) {
9576 char *value = strchr(*e, '=');
9577 if (value) { /* paranoia */
9578 cur_var->next = xzalloc(sizeof(*cur_var));
9579 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009580 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009581 cur_var->max_len = strlen(*e);
9582 cur_var->flg_export = 1;
9583 }
9584 e++;
9585 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009586 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009587 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9588 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009589
9590 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009591 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009592
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009593#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9594 /* Set (but not export) PS1/2 unless already set */
9595 if (!get_local_var_value("PS1"))
9596 set_local_var_from_halves("PS1", "\\w \\$ ");
9597 if (!get_local_var_value("PS2"))
9598 set_local_var_from_halves("PS2", "> ");
9599#endif
9600
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009601#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009602 /* Set (but not export) HOSTNAME unless already set */
9603 if (!get_local_var_value("HOSTNAME")) {
9604 struct utsname uts;
9605 uname(&uts);
9606 set_local_var_from_halves("HOSTNAME", uts.nodename);
9607 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009608 /* bash also exports SHLVL and _,
9609 * and sets (but doesn't export) the following variables:
9610 * BASH=/bin/bash
9611 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9612 * BASH_VERSION='3.2.0(1)-release'
9613 * HOSTTYPE=i386
9614 * MACHTYPE=i386-pc-linux-gnu
9615 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009616 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009617 * EUID=<NNNNN>
9618 * UID=<NNNNN>
9619 * GROUPS=()
9620 * LINES=<NNN>
9621 * COLUMNS=<NNN>
9622 * BASH_ARGC=()
9623 * BASH_ARGV=()
9624 * BASH_LINENO=()
9625 * BASH_SOURCE=()
9626 * DIRSTACK=()
9627 * PIPESTATUS=([0]="0")
9628 * HISTFILE=/<xxx>/.bash_history
9629 * HISTFILESIZE=500
9630 * HISTSIZE=500
9631 * MAILCHECK=60
9632 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9633 * SHELL=/bin/bash
9634 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9635 * TERM=dumb
9636 * OPTERR=1
9637 * OPTIND=1
9638 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009639 * PS4='+ '
9640 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009641#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009642
Denys Vlasenko5807e182018-02-08 19:19:04 +01009643#if ENABLE_HUSH_LINENO_VAR
9644 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009645 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9646 set_local_var(p, /*flags*/ 0);
9647 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9648 }
9649#endif
9650
Denis Vlasenko38f63192007-01-22 09:03:07 +00009651#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009652 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009653#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009654
Eric Andersen94ac2442001-05-22 19:05:18 +00009655 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009656 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009657
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009658 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009659
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009660 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009661 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009662 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009663 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009664 * in order to intercept (more) signals.
9665 */
9666
9667 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009668 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009669 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009670 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009671 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009672 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009673#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009674 "<:$:R:V:"
9675# if ENABLE_HUSH_FUNCTIONS
9676 "F:"
9677# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009678#endif
9679 );
9680 if (opt <= 0)
9681 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009682 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009683 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009684 /* Possibilities:
9685 * sh ... -c 'script'
9686 * sh ... -c 'script' ARG0 [ARG1...]
9687 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009688 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009689 * "" needs to be replaced with NULL
9690 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009691 * Note: the form without ARG0 never happens:
9692 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009693 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009694 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009695 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009696 G.root_ppid = getppid();
9697 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009698 G.global_argv = argv + optind;
9699 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009700 if (builtin_argc) {
9701 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9702 const struct built_in_command *x;
9703
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009704 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009705 x = find_builtin(optarg);
9706 if (x) { /* paranoia */
9707 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9708 G.global_argv += builtin_argc;
9709 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009710 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009711 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009712 }
9713 goto final_return;
9714 }
9715 if (!G.global_argv[0]) {
9716 /* -c 'script' (no params): prevent empty $0 */
9717 G.global_argv--; /* points to argv[i] of 'script' */
9718 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009719 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009720 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009721 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009722 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009723 goto final_return;
9724 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009725 /* Well, we cannot just declare interactiveness,
9726 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009727 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009728 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009729 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009730 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009731 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009732 case 'l':
9733 flags |= OPT_login;
9734 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009735#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009736 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009737 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009738 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009739 case '$': {
9740 unsigned long long empty_trap_mask;
9741
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009742 G.root_pid = bb_strtou(optarg, &optarg, 16);
9743 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009744 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9745 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009746 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9747 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009748 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009749 optarg++;
9750 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009751 optarg++;
9752 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9753 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009754 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009755 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009756# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009757 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009758 for (sig = 1; sig < NSIG; sig++) {
9759 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009760 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009761 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009762 }
9763 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009764# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009765 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009766# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009767 optarg++;
9768 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009769# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009770# if ENABLE_HUSH_FUNCTIONS
9771 /* nommu uses re-exec trick for "... | func | ...",
9772 * should allow "return".
9773 * This accidentally allows returns in subshells.
9774 */
9775 G_flag_return_in_progress = -1;
9776# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009777 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009778 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009779 case 'R':
9780 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009781 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009782 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009783# if ENABLE_HUSH_FUNCTIONS
9784 case 'F': {
9785 struct function *funcp = new_function(optarg);
9786 /* funcp->name is already set to optarg */
9787 /* funcp->body is set to NULL. It's a special case. */
9788 funcp->body_as_string = argv[optind];
9789 optind++;
9790 break;
9791 }
9792# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009793#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009794 case 'n':
9795 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009796 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009797 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009798 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009799 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009800#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009801 fprintf(stderr, "Usage: sh [FILE]...\n"
9802 " or: sh -c command [args]...\n\n");
9803 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009804#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009805 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009806#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009807 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009808 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009809
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009810 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9811 G.global_argc = argc - (optind - 1);
9812 G.global_argv = argv + (optind - 1);
9813 G.global_argv[0] = argv[0];
9814
Denys Vlasenkodea47882009-10-09 15:40:49 +02009815 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009816 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009817 G.root_ppid = getppid();
9818 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009819
9820 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009821 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009822 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009823 debug_printf("sourcing /etc/profile\n");
9824 input = fopen_for_read("/etc/profile");
9825 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009826 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009827 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009828 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009829 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009830 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009831 /* bash: after sourcing /etc/profile,
9832 * tries to source (in the given order):
9833 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009834 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009835 * bash also sources ~/.bash_logout on exit.
9836 * If called as sh, skips .bash_XXX files.
9837 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009838 }
9839
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009840 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9841 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009842 FILE *input;
9843 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009844 * "bash <script>" (which is never interactive (unless -i?))
9845 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009846 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009847 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009848 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009849 G.global_argc--;
9850 G.global_argv++;
9851 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009852 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009853 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009854 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009855 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009856 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009857 parse_and_run_file(input);
9858#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009859 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009860#endif
9861 goto final_return;
9862 }
9863
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009864 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009865 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009866 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009867
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009868 /* A shell is interactive if the '-i' flag was given,
9869 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009870 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009871 * no arguments remaining or the -s flag given
9872 * standard input is a terminal
9873 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009874 * Refer to Posix.2, the description of the 'sh' utility.
9875 */
9876#if ENABLE_HUSH_JOB
9877 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009878 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9879 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9880 if (G_saved_tty_pgrp < 0)
9881 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009882
9883 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009884 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009885 if (G_interactive_fd < 0) {
9886 /* try to dup to any fd */
9887 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009888 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009889 /* give up */
9890 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009891 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009892 }
9893 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009894// TODO: track & disallow any attempts of user
9895// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009896 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009897 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009898 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009899 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009900
Mike Frysinger38478a62009-05-20 04:48:06 -04009901 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009902 /* If we were run as 'hush &', sleep until we are
9903 * in the foreground (tty pgrp == our pgrp).
9904 * If we get started under a job aware app (like bash),
9905 * make sure we are now in charge so we don't fight over
9906 * who gets the foreground */
9907 while (1) {
9908 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009909 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9910 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009911 break;
9912 /* send TTIN to ourself (should stop us) */
9913 kill(- shell_pgrp, SIGTTIN);
9914 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009915 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009916
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009917 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009918 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009919
Mike Frysinger38478a62009-05-20 04:48:06 -04009920 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009921 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009922 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009923 /* Put ourselves in our own process group
9924 * (bash, too, does this only if ctty is available) */
9925 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9926 /* Grab control of the terminal */
9927 tcsetpgrp(G_interactive_fd, getpid());
9928 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009929 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009930
9931# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9932 {
9933 const char *hp = get_local_var_value("HISTFILE");
9934 if (!hp) {
9935 hp = get_local_var_value("HOME");
9936 if (hp)
9937 hp = concat_path_file(hp, ".hush_history");
9938 } else {
9939 hp = xstrdup(hp);
9940 }
9941 if (hp) {
9942 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009943 //set_local_var(xasprintf("HISTFILE=%s", ...));
9944 }
9945# if ENABLE_FEATURE_SH_HISTFILESIZE
9946 hp = get_local_var_value("HISTFILESIZE");
9947 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9948# endif
9949 }
9950# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009951 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009952 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009953 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009954#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009955 /* No job control compiled in, only prompt/line editing */
9956 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009957 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009958 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009959 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +02009960 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009961 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009962 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009963 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009964 }
9965 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009966 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009967 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009968 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009969 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009970#else
9971 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009972 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009973#endif
9974 /* bash:
9975 * if interactive but not a login shell, sources ~/.bashrc
9976 * (--norc turns this off, --rcfile <file> overrides)
9977 */
9978
9979 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009980 /* note: ash and hush share this string */
9981 printf("\n\n%s %s\n"
9982 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9983 "\n",
9984 bb_banner,
9985 "hush - the humble shell"
9986 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009987 }
9988
Denis Vlasenkof9375282009-04-05 19:13:39 +00009989 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009990
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009991 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009992 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009993}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009994
9995
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009996/*
9997 * Built-ins
9998 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009999static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010000{
10001 return 0;
10002}
10003
Denys Vlasenko265062d2017-01-10 15:13:30 +010010004#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010005static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010006{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010007 int argc = string_array_len(argv);
10008 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010009}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010010#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010011#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010012static int FAST_FUNC builtin_test(char **argv)
10013{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010014 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010015}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010016#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010017#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010018static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010019{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010020 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010021}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010022#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010023#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010024static int FAST_FUNC builtin_printf(char **argv)
10025{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010026 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010027}
10028#endif
10029
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010030#if ENABLE_HUSH_HELP
10031static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10032{
10033 const struct built_in_command *x;
10034
10035 printf(
10036 "Built-in commands:\n"
10037 "------------------\n");
10038 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10039 if (x->b_descr)
10040 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10041 }
10042 return EXIT_SUCCESS;
10043}
10044#endif
10045
10046#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10047static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10048{
10049 show_history(G.line_input_state);
10050 return EXIT_SUCCESS;
10051}
10052#endif
10053
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010054static char **skip_dash_dash(char **argv)
10055{
10056 argv++;
10057 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10058 argv++;
10059 return argv;
10060}
10061
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010062static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010063{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010064 const char *newdir;
10065
10066 argv = skip_dash_dash(argv);
10067 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010068 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010069 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010070 * bash says "bash: cd: HOME not set" and does nothing
10071 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010072 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010073 const char *home = get_local_var_value("HOME");
10074 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010075 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010076 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010077 /* Mimic bash message exactly */
10078 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010079 return EXIT_FAILURE;
10080 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010081 /* Read current dir (get_cwd(1) is inside) and set PWD.
10082 * Note: do not enforce exporting. If PWD was unset or unexported,
10083 * set it again, but do not export. bash does the same.
10084 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010085 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010086 return EXIT_SUCCESS;
10087}
10088
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010089static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10090{
10091 puts(get_cwd(0));
10092 return EXIT_SUCCESS;
10093}
10094
10095static int FAST_FUNC builtin_eval(char **argv)
10096{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010097 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010098
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010099 if (!argv[0])
10100 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010101
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010102 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010103 /* bash:
10104 * eval "echo Hi; done" ("done" is syntax error):
10105 * "echo Hi" will not execute too.
10106 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010107 parse_and_run_string(argv[0]);
10108 } else {
10109 /* "The eval utility shall construct a command by
10110 * concatenating arguments together, separating
10111 * each with a <space> character."
10112 */
10113 char *str, *p;
10114 unsigned len = 0;
10115 char **pp = argv;
10116 do
10117 len += strlen(*pp) + 1;
10118 while (*++pp);
10119 str = p = xmalloc(len);
10120 pp = argv;
10121 for (;;) {
10122 p = stpcpy(p, *pp);
10123 pp++;
10124 if (!*pp)
10125 break;
10126 *p++ = ' ';
10127 }
10128 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010129 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010130 }
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010131 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010132}
10133
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010134static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010135{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010136 argv = skip_dash_dash(argv);
10137 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010138 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010139
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010140 /* Careful: we can end up here after [v]fork. Do not restore
10141 * tty pgrp then, only top-level shell process does that */
10142 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10143 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10144
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010145 /* Saved-redirect fds, script fds and G_interactive_fd are still
10146 * open here. However, they are all CLOEXEC, and execv below
10147 * closes them. Try interactive "exec ls -l /proc/self/fd",
10148 * it should show no extra open fds in the "ls" process.
10149 * If we'd try to run builtins/NOEXECs, this would need improving.
10150 */
10151 //close_saved_fds_and_FILE_fds();
10152
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010153 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010154 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010155 * and tcsetpgrp, and this is inherently racy.
10156 */
10157 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010158}
10159
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010160static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010161{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010162 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010163
10164 /* interactive bash:
10165 * # trap "echo EEE" EXIT
10166 * # exit
10167 * exit
10168 * There are stopped jobs.
10169 * (if there are _stopped_ jobs, running ones don't count)
10170 * # exit
10171 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010172 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010173 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010174 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010175 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010176
10177 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010178 argv = skip_dash_dash(argv);
10179 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010180 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010181 /* mimic bash: exit 123abc == exit 255 + error msg */
10182 xfunc_error_retval = 255;
10183 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010184 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010185}
10186
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010187#if ENABLE_HUSH_TYPE
10188/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10189static int FAST_FUNC builtin_type(char **argv)
10190{
10191 int ret = EXIT_SUCCESS;
10192
10193 while (*++argv) {
10194 const char *type;
10195 char *path = NULL;
10196
10197 if (0) {} /* make conditional compile easier below */
10198 /*else if (find_alias(*argv))
10199 type = "an alias";*/
10200#if ENABLE_HUSH_FUNCTIONS
10201 else if (find_function(*argv))
10202 type = "a function";
10203#endif
10204 else if (find_builtin(*argv))
10205 type = "a shell builtin";
10206 else if ((path = find_in_path(*argv)) != NULL)
10207 type = path;
10208 else {
10209 bb_error_msg("type: %s: not found", *argv);
10210 ret = EXIT_FAILURE;
10211 continue;
10212 }
10213
10214 printf("%s is %s\n", *argv, type);
10215 free(path);
10216 }
10217
10218 return ret;
10219}
10220#endif
10221
10222#if ENABLE_HUSH_READ
10223/* Interruptibility of read builtin in bash
10224 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10225 *
10226 * Empty trap makes read ignore corresponding signal, for any signal.
10227 *
10228 * SIGINT:
10229 * - terminates non-interactive shell;
10230 * - interrupts read in interactive shell;
10231 * if it has non-empty trap:
10232 * - executes trap and returns to command prompt in interactive shell;
10233 * - executes trap and returns to read in non-interactive shell;
10234 * SIGTERM:
10235 * - is ignored (does not interrupt) read in interactive shell;
10236 * - terminates non-interactive shell;
10237 * if it has non-empty trap:
10238 * - executes trap and returns to read;
10239 * SIGHUP:
10240 * - terminates shell (regardless of interactivity);
10241 * if it has non-empty trap:
10242 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010243 * SIGCHLD from children:
10244 * - does not interrupt read regardless of interactivity:
10245 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010246 */
10247static int FAST_FUNC builtin_read(char **argv)
10248{
10249 const char *r;
10250 char *opt_n = NULL;
10251 char *opt_p = NULL;
10252 char *opt_t = NULL;
10253 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010254 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010255 const char *ifs;
10256 int read_flags;
10257
10258 /* "!": do not abort on errors.
10259 * Option string must start with "sr" to match BUILTIN_READ_xxx
10260 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010261 read_flags = getopt32(argv,
10262#if BASH_READ_D
10263 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10264#else
10265 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10266#endif
10267 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010268 if (read_flags == (uint32_t)-1)
10269 return EXIT_FAILURE;
10270 argv += optind;
10271 ifs = get_local_var_value("IFS"); /* can be NULL */
10272
10273 again:
10274 r = shell_builtin_read(set_local_var_from_halves,
10275 argv,
10276 ifs,
10277 read_flags,
10278 opt_n,
10279 opt_p,
10280 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010281 opt_u,
10282 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010283 );
10284
10285 if ((uintptr_t)r == 1 && errno == EINTR) {
10286 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010287 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010288 goto again;
10289 }
10290
10291 if ((uintptr_t)r > 1) {
10292 bb_error_msg("%s", r);
10293 r = (char*)(uintptr_t)1;
10294 }
10295
10296 return (uintptr_t)r;
10297}
10298#endif
10299
10300#if ENABLE_HUSH_UMASK
10301static int FAST_FUNC builtin_umask(char **argv)
10302{
10303 int rc;
10304 mode_t mask;
10305
10306 rc = 1;
10307 mask = umask(0);
10308 argv = skip_dash_dash(argv);
10309 if (argv[0]) {
10310 mode_t old_mask = mask;
10311
10312 /* numeric umasks are taken as-is */
10313 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10314 if (!isdigit(argv[0][0]))
10315 mask ^= 0777;
10316 mask = bb_parse_mode(argv[0], mask);
10317 if (!isdigit(argv[0][0]))
10318 mask ^= 0777;
10319 if ((unsigned)mask > 0777) {
10320 mask = old_mask;
10321 /* bash messages:
10322 * bash: umask: 'q': invalid symbolic mode operator
10323 * bash: umask: 999: octal number out of range
10324 */
10325 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10326 rc = 0;
10327 }
10328 } else {
10329 /* Mimic bash */
10330 printf("%04o\n", (unsigned) mask);
10331 /* fall through and restore mask which we set to 0 */
10332 }
10333 umask(mask);
10334
10335 return !rc; /* rc != 0 - success */
10336}
10337#endif
10338
Denys Vlasenko41ade052017-01-08 18:56:24 +010010339#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010340static void print_escaped(const char *s)
10341{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010342 if (*s == '\'')
10343 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010344 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010345 const char *p = strchrnul(s, '\'');
10346 /* print 'xxxx', possibly just '' */
10347 printf("'%.*s'", (int)(p - s), s);
10348 if (*p == '\0')
10349 break;
10350 s = p;
10351 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010352 /* s points to '; print "'''...'''" */
10353 putchar('"');
10354 do putchar('\''); while (*++s == '\'');
10355 putchar('"');
10356 } while (*s);
10357}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010358#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010359
Denys Vlasenko1e660422017-07-17 21:10:50 +020010360#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010361static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010362{
10363 do {
10364 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010365 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010366
10367 /* So far we do not check that name is valid (TODO?) */
10368
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010369 if (*name_end == '\0') {
10370 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010371
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010372 vpp = get_ptr_to_local_var(name, name_end - name);
10373 var = vpp ? *vpp : NULL;
10374
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010375 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010376 /* export -n NAME (without =VALUE) */
10377 if (var) {
10378 var->flg_export = 0;
10379 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10380 unsetenv(name);
10381 } /* else: export -n NOT_EXISTING_VAR: no-op */
10382 continue;
10383 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010384 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010385 /* export NAME (without =VALUE) */
10386 if (var) {
10387 var->flg_export = 1;
10388 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10389 putenv(var->varstr);
10390 continue;
10391 }
10392 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010393 if (flags & SETFLAG_MAKE_RO) {
10394 /* readonly NAME (without =VALUE) */
10395 if (var) {
10396 var->flg_read_only = 1;
10397 continue;
10398 }
10399 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010400# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010401 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010402 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010403 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10404 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010405 /* "local x=abc; ...; local x" - ignore second local decl */
10406 continue;
10407 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010408 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010409# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010410 /* Exporting non-existing variable.
10411 * bash does not put it in environment,
10412 * but remembers that it is exported,
10413 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010414 * We just set it to "" and export.
10415 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010416 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010417 * bash sets the value to "".
10418 */
10419 /* Or, it's "readonly NAME" (without =VALUE).
10420 * bash remembers NAME and disallows its creation
10421 * in the future.
10422 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010423 name = xasprintf("%s=", name);
10424 } else {
10425 /* (Un)exporting/making local NAME=VALUE */
10426 name = xstrdup(name);
10427 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010428 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010429 if (set_local_var(name, flags))
10430 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010431 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010432 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010433}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010434#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010435
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010436#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010437static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010438{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010439 unsigned opt_unexport;
10440
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010441#if ENABLE_HUSH_EXPORT_N
10442 /* "!": do not abort on errors */
10443 opt_unexport = getopt32(argv, "!n");
10444 if (opt_unexport == (uint32_t)-1)
10445 return EXIT_FAILURE;
10446 argv += optind;
10447#else
10448 opt_unexport = 0;
10449 argv++;
10450#endif
10451
10452 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010453 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010454 if (e) {
10455 while (*e) {
10456#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010457 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010458#else
10459 /* ash emits: export VAR='VAL'
10460 * bash: declare -x VAR="VAL"
10461 * we follow ash example */
10462 const char *s = *e++;
10463 const char *p = strchr(s, '=');
10464
10465 if (!p) /* wtf? take next variable */
10466 continue;
10467 /* export var= */
10468 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010469 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010470 putchar('\n');
10471#endif
10472 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010473 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010474 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010475 return EXIT_SUCCESS;
10476 }
10477
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010478 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010479}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010480#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010481
Denys Vlasenko295fef82009-06-03 12:47:26 +020010482#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010483static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010484{
10485 if (G.func_nest_level == 0) {
10486 bb_error_msg("%s: not in a function", argv[0]);
10487 return EXIT_FAILURE; /* bash compat */
10488 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010489 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010490 /* Since all builtins run in a nested variable level,
10491 * need to use level - 1 here. Or else the variable will be removed at once
10492 * after builtin returns.
10493 */
10494 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010495}
10496#endif
10497
Denys Vlasenko1e660422017-07-17 21:10:50 +020010498#if ENABLE_HUSH_READONLY
10499static int FAST_FUNC builtin_readonly(char **argv)
10500{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010501 argv++;
10502 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010503 /* bash: readonly [-p]: list all readonly VARs
10504 * (-p has no effect in bash)
10505 */
10506 struct variable *e;
10507 for (e = G.top_var; e; e = e->next) {
10508 if (e->flg_read_only) {
10509//TODO: quote value: readonly VAR='VAL'
10510 printf("readonly %s\n", e->varstr);
10511 }
10512 }
10513 return EXIT_SUCCESS;
10514 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010515 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010516}
10517#endif
10518
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010519#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010520/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10521static int FAST_FUNC builtin_unset(char **argv)
10522{
10523 int ret;
10524 unsigned opts;
10525
10526 /* "!": do not abort on errors */
10527 /* "+": stop at 1st non-option */
10528 opts = getopt32(argv, "!+vf");
10529 if (opts == (unsigned)-1)
10530 return EXIT_FAILURE;
10531 if (opts == 3) {
10532 bb_error_msg("unset: -v and -f are exclusive");
10533 return EXIT_FAILURE;
10534 }
10535 argv += optind;
10536
10537 ret = EXIT_SUCCESS;
10538 while (*argv) {
10539 if (!(opts & 2)) { /* not -f */
10540 if (unset_local_var(*argv)) {
10541 /* unset <nonexistent_var> doesn't fail.
10542 * Error is when one tries to unset RO var.
10543 * Message was printed by unset_local_var. */
10544 ret = EXIT_FAILURE;
10545 }
10546 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010547# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010548 else {
10549 unset_func(*argv);
10550 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010551# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010552 argv++;
10553 }
10554 return ret;
10555}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010556#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010557
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010558#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010559/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10560 * built-in 'set' handler
10561 * SUSv3 says:
10562 * set [-abCefhmnuvx] [-o option] [argument...]
10563 * set [+abCefhmnuvx] [+o option] [argument...]
10564 * set -- [argument...]
10565 * set -o
10566 * set +o
10567 * Implementations shall support the options in both their hyphen and
10568 * plus-sign forms. These options can also be specified as options to sh.
10569 * Examples:
10570 * Write out all variables and their values: set
10571 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10572 * Turn on the -x and -v options: set -xv
10573 * Unset all positional parameters: set --
10574 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10575 * Set the positional parameters to the expansion of x, even if x expands
10576 * with a leading '-' or '+': set -- $x
10577 *
10578 * So far, we only support "set -- [argument...]" and some of the short names.
10579 */
10580static int FAST_FUNC builtin_set(char **argv)
10581{
10582 int n;
10583 char **pp, **g_argv;
10584 char *arg = *++argv;
10585
10586 if (arg == NULL) {
10587 struct variable *e;
10588 for (e = G.top_var; e; e = e->next)
10589 puts(e->varstr);
10590 return EXIT_SUCCESS;
10591 }
10592
10593 do {
10594 if (strcmp(arg, "--") == 0) {
10595 ++argv;
10596 goto set_argv;
10597 }
10598 if (arg[0] != '+' && arg[0] != '-')
10599 break;
10600 for (n = 1; arg[n]; ++n) {
10601 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10602 goto error;
10603 if (arg[n] == 'o' && argv[1])
10604 argv++;
10605 }
10606 } while ((arg = *++argv) != NULL);
10607 /* Now argv[0] is 1st argument */
10608
10609 if (arg == NULL)
10610 return EXIT_SUCCESS;
10611 set_argv:
10612
10613 /* NB: G.global_argv[0] ($0) is never freed/changed */
10614 g_argv = G.global_argv;
10615 if (G.global_args_malloced) {
10616 pp = g_argv;
10617 while (*++pp)
10618 free(*pp);
10619 g_argv[1] = NULL;
10620 } else {
10621 G.global_args_malloced = 1;
10622 pp = xzalloc(sizeof(pp[0]) * 2);
10623 pp[0] = g_argv[0]; /* retain $0 */
10624 g_argv = pp;
10625 }
10626 /* This realloc's G.global_argv */
10627 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10628
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010629 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010630
10631 return EXIT_SUCCESS;
10632
10633 /* Nothing known, so abort */
10634 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010635 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010636 return EXIT_FAILURE;
10637}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010638#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010639
10640static int FAST_FUNC builtin_shift(char **argv)
10641{
10642 int n = 1;
10643 argv = skip_dash_dash(argv);
10644 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010645 n = bb_strtou(argv[0], NULL, 10);
10646 if (errno || n < 0) {
10647 /* shared string with ash.c */
10648 bb_error_msg("Illegal number: %s", argv[0]);
10649 /*
10650 * ash aborts in this case.
10651 * bash prints error message and set $? to 1.
10652 * Interestingly, for "shift 99999" bash does not
10653 * print error message, but does set $? to 1
10654 * (and does no shifting at all).
10655 */
10656 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010657 }
10658 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010659 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010660 int m = 1;
10661 while (m <= n)
10662 free(G.global_argv[m++]);
10663 }
10664 G.global_argc -= n;
10665 memmove(&G.global_argv[1], &G.global_argv[n+1],
10666 G.global_argc * sizeof(G.global_argv[0]));
10667 return EXIT_SUCCESS;
10668 }
10669 return EXIT_FAILURE;
10670}
10671
Denys Vlasenko74d40582017-08-11 01:32:46 +020010672#if ENABLE_HUSH_GETOPTS
10673static int FAST_FUNC builtin_getopts(char **argv)
10674{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010675/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10676
Denys Vlasenko74d40582017-08-11 01:32:46 +020010677TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010678If a required argument is not found, and getopts is not silent,
10679a question mark (?) is placed in VAR, OPTARG is unset, and a
10680diagnostic message is printed. If getopts is silent, then a
10681colon (:) is placed in VAR and OPTARG is set to the option
10682character found.
10683
10684Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010685
10686"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010687*/
10688 char cbuf[2];
10689 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010690 int c, n, exitcode, my_opterr;
10691 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010692
10693 optstring = *++argv;
10694 if (!optstring || !(var = *++argv)) {
10695 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10696 return EXIT_FAILURE;
10697 }
10698
Denys Vlasenko238ff982017-08-29 13:38:30 +020010699 if (argv[1])
10700 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10701 else
10702 argv = G.global_argv;
10703 cbuf[1] = '\0';
10704
10705 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010706 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010707 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010708 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010709 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010710 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010711
10712 /* getopts stops on first non-option. Add "+" to force that */
10713 /*if (optstring[0] != '+')*/ {
10714 char *s = alloca(strlen(optstring) + 2);
10715 sprintf(s, "+%s", optstring);
10716 optstring = s;
10717 }
10718
Denys Vlasenko238ff982017-08-29 13:38:30 +020010719 /* Naively, now we should just
10720 * cp = get_local_var_value("OPTIND");
10721 * optind = cp ? atoi(cp) : 0;
10722 * optarg = NULL;
10723 * opterr = my_opterr;
10724 * c = getopt(string_array_len(argv), argv, optstring);
10725 * and be done? Not so fast...
10726 * Unlike normal getopt() usage in C programs, here
10727 * each successive call will (usually) have the same argv[] CONTENTS,
10728 * but not the ADDRESSES. Worse yet, it's possible that between
10729 * invocations of "getopts", there will be calls to shell builtins
10730 * which use getopt() internally. Example:
10731 * while getopts "abc" RES -a -bc -abc de; do
10732 * unset -ff func
10733 * done
10734 * This would not work correctly: getopt() call inside "unset"
10735 * modifies internal libc state which is tracking position in
10736 * multi-option strings ("-abc"). At best, it can skip options
10737 * or return the same option infinitely. With glibc implementation
10738 * of getopt(), it would use outright invalid pointers and return
10739 * garbage even _without_ "unset" mangling internal state.
10740 *
10741 * We resort to resetting getopt() state and calling it N times,
10742 * until we get Nth result (or failure).
10743 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10744 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010745 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010746 count = 0;
10747 n = string_array_len(argv);
10748 do {
10749 optarg = NULL;
10750 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10751 c = getopt(n, argv, optstring);
10752 if (c < 0)
10753 break;
10754 count++;
10755 } while (count <= G.getopt_count);
10756
10757 /* Set OPTIND. Prevent resetting of the magic counter! */
10758 set_local_var_from_halves("OPTIND", utoa(optind));
10759 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010760 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010761
10762 /* Set OPTARG */
10763 /* Always set or unset, never left as-is, even on exit/error:
10764 * "If no option was found, or if the option that was found
10765 * does not have an option-argument, OPTARG shall be unset."
10766 */
10767 cp = optarg;
10768 if (c == '?') {
10769 /* If ":optstring" and unknown option is seen,
10770 * it is stored to OPTARG.
10771 */
10772 if (optstring[1] == ':') {
10773 cbuf[0] = optopt;
10774 cp = cbuf;
10775 }
10776 }
10777 if (cp)
10778 set_local_var_from_halves("OPTARG", cp);
10779 else
10780 unset_local_var("OPTARG");
10781
10782 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010783 exitcode = EXIT_SUCCESS;
10784 if (c < 0) { /* -1: end of options */
10785 exitcode = EXIT_FAILURE;
10786 c = '?';
10787 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010788
Denys Vlasenko238ff982017-08-29 13:38:30 +020010789 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010790 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010791 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010792
Denys Vlasenko74d40582017-08-11 01:32:46 +020010793 return exitcode;
10794}
10795#endif
10796
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010797static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010798{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010799 char *arg_path, *filename;
10800 FILE *input;
10801 save_arg_t sv;
10802 char *args_need_save;
10803#if ENABLE_HUSH_FUNCTIONS
10804 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010805#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010806
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010807 argv = skip_dash_dash(argv);
10808 filename = argv[0];
10809 if (!filename) {
10810 /* bash says: "bash: .: filename argument required" */
10811 return 2; /* bash compat */
10812 }
10813 arg_path = NULL;
10814 if (!strchr(filename, '/')) {
10815 arg_path = find_in_path(filename);
10816 if (arg_path)
10817 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010818 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010819 errno = ENOENT;
10820 bb_simple_perror_msg(filename);
10821 return EXIT_FAILURE;
10822 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010823 }
10824 input = remember_FILE(fopen_or_warn(filename, "r"));
10825 free(arg_path);
10826 if (!input) {
10827 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10828 /* POSIX: non-interactive shell should abort here,
10829 * not merely fail. So far no one complained :)
10830 */
10831 return EXIT_FAILURE;
10832 }
10833
10834#if ENABLE_HUSH_FUNCTIONS
10835 sv_flg = G_flag_return_in_progress;
10836 /* "we are inside sourced file, ok to use return" */
10837 G_flag_return_in_progress = -1;
10838#endif
10839 args_need_save = argv[1]; /* used as a boolean variable */
10840 if (args_need_save)
10841 save_and_replace_G_args(&sv, argv);
10842
10843 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10844 G.last_exitcode = 0;
10845 parse_and_run_file(input);
10846 fclose_and_forget(input);
10847
10848 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10849 restore_G_args(&sv, argv);
10850#if ENABLE_HUSH_FUNCTIONS
10851 G_flag_return_in_progress = sv_flg;
10852#endif
10853
10854 return G.last_exitcode;
10855}
10856
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010857#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010858static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010859{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010860 int sig;
10861 char *new_cmd;
10862
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010863 if (!G_traps)
10864 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010865
10866 argv++;
10867 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010868 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010869 /* No args: print all trapped */
10870 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010871 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010872 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010873 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010874 /* note: bash adds "SIG", but only if invoked
10875 * as "bash". If called as "sh", or if set -o posix,
10876 * then it prints short signal names.
10877 * We are printing short names: */
10878 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010879 }
10880 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010881 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010882 return EXIT_SUCCESS;
10883 }
10884
10885 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010886 /* If first arg is a number: reset all specified signals */
10887 sig = bb_strtou(*argv, NULL, 10);
10888 if (errno == 0) {
10889 int ret;
10890 process_sig_list:
10891 ret = EXIT_SUCCESS;
10892 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010893 sighandler_t handler;
10894
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010895 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010896 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010897 ret = EXIT_FAILURE;
10898 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010899 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010900 continue;
10901 }
10902
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010903 free(G_traps[sig]);
10904 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010905
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010906 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010907 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010908
10909 /* There is no signal for 0 (EXIT) */
10910 if (sig == 0)
10911 continue;
10912
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010913 if (new_cmd)
10914 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10915 else
10916 /* We are removing trap handler */
10917 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010918 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010919 }
10920 return ret;
10921 }
10922
10923 if (!argv[1]) { /* no second arg */
10924 bb_error_msg("trap: invalid arguments");
10925 return EXIT_FAILURE;
10926 }
10927
10928 /* First arg is "-": reset all specified to default */
10929 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10930 /* Everything else: set arg as signal handler
10931 * (includes "" case, which ignores signal) */
10932 if (argv[0][0] == '-') {
10933 if (argv[0][1] == '\0') { /* "-" */
10934 /* new_cmd remains NULL: "reset these sigs" */
10935 goto reset_traps;
10936 }
10937 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10938 argv++;
10939 }
10940 /* else: "-something", no special meaning */
10941 }
10942 new_cmd = *argv;
10943 reset_traps:
10944 argv++;
10945 goto process_sig_list;
10946}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010947#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010948
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010949#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010950static struct pipe *parse_jobspec(const char *str)
10951{
10952 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010953 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010954
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010955 if (sscanf(str, "%%%u", &jobnum) != 1) {
10956 if (str[0] != '%'
10957 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10958 ) {
10959 bb_error_msg("bad argument '%s'", str);
10960 return NULL;
10961 }
10962 /* It is "%%", "%+" or "%" - current job */
10963 jobnum = G.last_jobid;
10964 if (jobnum == 0) {
10965 bb_error_msg("no current job");
10966 return NULL;
10967 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010968 }
10969 for (pi = G.job_list; pi; pi = pi->next) {
10970 if (pi->jobid == jobnum) {
10971 return pi;
10972 }
10973 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010974 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010975 return NULL;
10976}
10977
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010978static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10979{
10980 struct pipe *job;
10981 const char *status_string;
10982
10983 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10984 for (job = G.job_list; job; job = job->next) {
10985 if (job->alive_cmds == job->stopped_cmds)
10986 status_string = "Stopped";
10987 else
10988 status_string = "Running";
10989
10990 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10991 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010992
10993 clean_up_last_dead_job();
10994
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010995 return EXIT_SUCCESS;
10996}
10997
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010998/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010999static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011000{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011001 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011002 struct pipe *pi;
11003
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011004 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011005 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011006
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011007 /* If they gave us no args, assume they want the last backgrounded task */
11008 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011009 for (pi = G.job_list; pi; pi = pi->next) {
11010 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011011 goto found;
11012 }
11013 }
11014 bb_error_msg("%s: no current job", argv[0]);
11015 return EXIT_FAILURE;
11016 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011017
11018 pi = parse_jobspec(argv[1]);
11019 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011020 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011021 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011022 /* TODO: bash prints a string representation
11023 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011024 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011025 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011026 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011027 }
11028
11029 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011030 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11031 for (i = 0; i < pi->num_cmds; i++) {
11032 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011033 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011034 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011035
11036 i = kill(- pi->pgrp, SIGCONT);
11037 if (i < 0) {
11038 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011039 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011040 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011041 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011042 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011043 }
11044
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011045 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011046 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011047 return checkjobs_and_fg_shell(pi);
11048 }
11049 return EXIT_SUCCESS;
11050}
11051#endif
11052
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011053#if ENABLE_HUSH_KILL
11054static int FAST_FUNC builtin_kill(char **argv)
11055{
11056 int ret = 0;
11057
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011058# if ENABLE_HUSH_JOB
11059 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11060 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011061
11062 do {
11063 struct pipe *pi;
11064 char *dst;
11065 int j, n;
11066
11067 if (argv[i][0] != '%')
11068 continue;
11069 /*
11070 * "kill %N" - job kill
11071 * Converting to pgrp / pid kill
11072 */
11073 pi = parse_jobspec(argv[i]);
11074 if (!pi) {
11075 /* Eat bad jobspec */
11076 j = i;
11077 do {
11078 j++;
11079 argv[j - 1] = argv[j];
11080 } while (argv[j]);
11081 ret = 1;
11082 i--;
11083 continue;
11084 }
11085 /*
11086 * In jobs started under job control, we signal
11087 * entire process group by kill -PGRP_ID.
11088 * This happens, f.e., in interactive shell.
11089 *
11090 * Otherwise, we signal each child via
11091 * kill PID1 PID2 PID3.
11092 * Testcases:
11093 * sh -c 'sleep 1|sleep 1 & kill %1'
11094 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11095 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11096 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011097 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011098 dst = alloca(n * sizeof(int)*4);
11099 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011100 if (G_interactive_fd)
11101 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011102 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011103 struct command *cmd = &pi->cmds[j];
11104 /* Skip exited members of the job */
11105 if (cmd->pid == 0)
11106 continue;
11107 /*
11108 * kill_main has matching code to expect
11109 * leading space. Needed to not confuse
11110 * negative pids with "kill -SIGNAL_NO" syntax
11111 */
11112 dst += sprintf(dst, " %u", (int)cmd->pid);
11113 }
11114 *dst = '\0';
11115 } while (argv[++i]);
11116 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011117# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011118
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011119 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011120 ret = run_applet_main(argv, kill_main);
11121 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011122 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011123 return ret;
11124}
11125#endif
11126
11127#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011128/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011129#if !ENABLE_HUSH_JOB
11130# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11131#endif
11132static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011133{
11134 int ret = 0;
11135 for (;;) {
11136 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011137 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011138
Denys Vlasenko830ea352016-11-08 04:59:11 +010011139 if (!sigisemptyset(&G.pending_set))
11140 goto check_sig;
11141
Denys Vlasenko7e675362016-10-28 21:57:31 +020011142 /* waitpid is not interruptible by SA_RESTARTed
11143 * signals which we use. Thus, this ugly dance:
11144 */
11145
11146 /* Make sure possible SIGCHLD is stored in kernel's
11147 * pending signal mask before we call waitpid.
11148 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011149 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011150 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011151 sigfillset(&oldset); /* block all signals, remember old set */
11152 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011153
11154 if (!sigisemptyset(&G.pending_set)) {
11155 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011156 goto restore;
11157 }
11158
11159 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011160/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011161 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011162 debug_printf_exec("checkjobs:%d\n", ret);
11163#if ENABLE_HUSH_JOB
11164 if (waitfor_pipe) {
11165 int rcode = job_exited_or_stopped(waitfor_pipe);
11166 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11167 if (rcode >= 0) {
11168 ret = rcode;
11169 sigprocmask(SIG_SETMASK, &oldset, NULL);
11170 break;
11171 }
11172 }
11173#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011174 /* if ECHILD, there are no children (ret is -1 or 0) */
11175 /* if ret == 0, no children changed state */
11176 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011177 if (errno == ECHILD || ret) {
11178 ret--;
11179 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011180 ret = 0;
11181 sigprocmask(SIG_SETMASK, &oldset, NULL);
11182 break;
11183 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011184 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011185 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11186 /* Note: sigsuspend invokes signal handler */
11187 sigsuspend(&oldset);
11188 restore:
11189 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011190 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011191 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011192 sig = check_and_run_traps();
11193 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011194 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011195 ret = 128 + sig;
11196 break;
11197 }
11198 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11199 }
11200 return ret;
11201}
11202
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011203static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011204{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011205 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011206 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011207
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011208 argv = skip_dash_dash(argv);
11209 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011210 /* Don't care about wait results */
11211 /* Note 1: must wait until there are no more children */
11212 /* Note 2: must be interruptible */
11213 /* Examples:
11214 * $ sleep 3 & sleep 6 & wait
11215 * [1] 30934 sleep 3
11216 * [2] 30935 sleep 6
11217 * [1] Done sleep 3
11218 * [2] Done sleep 6
11219 * $ sleep 3 & sleep 6 & wait
11220 * [1] 30936 sleep 3
11221 * [2] 30937 sleep 6
11222 * [1] Done sleep 3
11223 * ^C <-- after ~4 sec from keyboard
11224 * $
11225 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011226 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011227 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011228
Denys Vlasenko7e675362016-10-28 21:57:31 +020011229 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011230 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011231 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011232#if ENABLE_HUSH_JOB
11233 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011234 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011235 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011236 wait_pipe = parse_jobspec(*argv);
11237 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011238 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011239 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011240 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011241 } else {
11242 /* waiting on "last dead job" removes it */
11243 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011244 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011245 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011246 /* else: parse_jobspec() already emitted error msg */
11247 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011248 }
11249#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011250 /* mimic bash message */
11251 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011252 ret = EXIT_FAILURE;
11253 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011254 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011255
Denys Vlasenko7e675362016-10-28 21:57:31 +020011256 /* Do we have such child? */
11257 ret = waitpid(pid, &status, WNOHANG);
11258 if (ret < 0) {
11259 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011260 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011261 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011262 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011263 /* "wait $!" but last bg task has already exited. Try:
11264 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11265 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011266 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011267 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011268 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011269 } else {
11270 /* Example: "wait 1". mimic bash message */
11271 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011272 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011273 } else {
11274 /* ??? */
11275 bb_perror_msg("wait %s", *argv);
11276 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011277 continue; /* bash checks all argv[] */
11278 }
11279 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011280 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011281 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011282 } else {
11283 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011284 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011285 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011286 if (WIFSIGNALED(status))
11287 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011288 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011289 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011290
11291 return ret;
11292}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011293#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011294
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011295#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11296static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11297{
11298 if (argv[1]) {
11299 def = bb_strtou(argv[1], NULL, 10);
11300 if (errno || def < def_min || argv[2]) {
11301 bb_error_msg("%s: bad arguments", argv[0]);
11302 def = UINT_MAX;
11303 }
11304 }
11305 return def;
11306}
11307#endif
11308
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011309#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011310static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011311{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011312 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011313 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011314 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011315 /* if we came from builtin_continue(), need to undo "= 1" */
11316 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011317 return EXIT_SUCCESS; /* bash compat */
11318 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011319 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011320
11321 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11322 if (depth == UINT_MAX)
11323 G.flag_break_continue = BC_BREAK;
11324 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011325 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011326
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011327 return EXIT_SUCCESS;
11328}
11329
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011330static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011331{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011332 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11333 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011334}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011335#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011336
11337#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011338static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011339{
11340 int rc;
11341
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011342 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011343 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11344 return EXIT_FAILURE; /* bash compat */
11345 }
11346
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011347 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011348
11349 /* bash:
11350 * out of range: wraps around at 256, does not error out
11351 * non-numeric param:
11352 * f() { false; return qwe; }; f; echo $?
11353 * bash: return: qwe: numeric argument required <== we do this
11354 * 255 <== we also do this
11355 */
11356 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11357 return rc;
11358}
11359#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011360
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011361#if ENABLE_HUSH_TIMES
11362static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11363{
11364 static const uint8_t times_tbl[] ALIGN1 = {
11365 ' ', offsetof(struct tms, tms_utime),
11366 '\n', offsetof(struct tms, tms_stime),
11367 ' ', offsetof(struct tms, tms_cutime),
11368 '\n', offsetof(struct tms, tms_cstime),
11369 0
11370 };
11371 const uint8_t *p;
11372 unsigned clk_tck;
11373 struct tms buf;
11374
11375 clk_tck = bb_clk_tck();
11376
11377 times(&buf);
11378 p = times_tbl;
11379 do {
11380 unsigned sec, frac;
11381 unsigned long t;
11382 t = *(clock_t *)(((char *) &buf) + p[1]);
11383 sec = t / clk_tck;
11384 frac = t % clk_tck;
11385 printf("%um%u.%03us%c",
11386 sec / 60, sec % 60,
11387 (frac * 1000) / clk_tck,
11388 p[0]);
11389 p += 2;
11390 } while (*p);
11391
11392 return EXIT_SUCCESS;
11393}
11394#endif
11395
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011396#if ENABLE_HUSH_MEMLEAK
11397static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11398{
11399 void *p;
11400 unsigned long l;
11401
11402# ifdef M_TRIM_THRESHOLD
11403 /* Optional. Reduces probability of false positives */
11404 malloc_trim(0);
11405# endif
11406 /* Crude attempt to find where "free memory" starts,
11407 * sans fragmentation. */
11408 p = malloc(240);
11409 l = (unsigned long)p;
11410 free(p);
11411 p = malloc(3400);
11412 if (l < (unsigned long)p) l = (unsigned long)p;
11413 free(p);
11414
11415
11416# if 0 /* debug */
11417 {
11418 struct mallinfo mi = mallinfo();
11419 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11420 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11421 }
11422# endif
11423
11424 if (!G.memleak_value)
11425 G.memleak_value = l;
11426
11427 l -= G.memleak_value;
11428 if ((long)l < 0)
11429 l = 0;
11430 l /= 1024;
11431 if (l > 127)
11432 l = 127;
11433
11434 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11435 return l;
11436}
11437#endif