blob: 7a1513c2489d61d5fca58f758ff6773ee8cc4a09 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * TODO:
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//config: hush is a small shell. It handles the normal flow control
100//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101//config: case/esac. Redirections, here documents, $((arithmetic))
102//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//config:config HUSH_BASH_SOURCE_CURDIR
127//config: bool "'source' and '.' builtins search current directory after $PATH"
128//config: default n # do not encourage non-standard behavior
129//config: depends on HUSH_BASH_COMPAT
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//config: Enable interactive mode (prompt and command editing).
139//config: Without this, hush simply reads and executes commands
140//config: from stdin just like a shell script from a file.
141//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154//config: command (not entire shell), fg/bg builtins work. Without this option,
155//config: "cmd &" still works by simply spawning a process and immediately
156//config: prompting for next command (or executing next command in a script),
157//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200360#ifndef O_CLOEXEC
361# define O_CLOEXEC 0
362#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100363#ifndef F_DUPFD_CLOEXEC
364# define F_DUPFD_CLOEXEC F_DUPFD
365#endif
366#ifndef PIPE_BUF
367# define PIPE_BUF 4096 /* amount of buffering in a pipe */
368#endif
369
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000370
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100371/* So far, all bash compat is controlled by one config option */
372/* Separate defines document which part of code implements what */
373#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
374#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100375#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
376#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200377#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200378#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100379
380
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200381/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000382#define LEAK_HUNTING 0
383#define BUILD_AS_NOMMU 0
384/* Enable/disable sanity checks. Ok to enable in production,
385 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
386 * Keeping 1 for now even in released versions.
387 */
388#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200389/* Slightly bigger (+200 bytes), but faster hush.
390 * So far it only enables a trick with counting SIGCHLDs and forks,
391 * which allows us to do fewer waitpid's.
392 * (we can detect a case where neither forks were done nor SIGCHLDs happened
393 * and therefore waitpid will return the same result as last time)
394 */
395#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200396/* TODO: implement simplified code for users which do not need ${var%...} ops
397 * So far ${var%...} ops are always enabled:
398 */
399#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000400
401
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000402#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000403# undef BB_MMU
404# undef USE_FOR_NOMMU
405# undef USE_FOR_MMU
406# define BB_MMU 0
407# define USE_FOR_NOMMU(...) __VA_ARGS__
408# define USE_FOR_MMU(...)
409#endif
410
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200411#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100412#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000413/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000414# undef CONFIG_FEATURE_SH_STANDALONE
415# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100417# undef IF_NOT_FEATURE_SH_STANDALONE
418# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000419# define IF_FEATURE_SH_STANDALONE(...)
420# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000421#endif
422
Denis Vlasenko05743d72008-02-10 12:10:08 +0000423#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000424# undef ENABLE_FEATURE_EDITING
425# define ENABLE_FEATURE_EDITING 0
426# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
427# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200428# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
429# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000430#endif
431
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000432/* Do we support ANY keywords? */
433#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000434# define HAS_KEYWORDS 1
435# define IF_HAS_KEYWORDS(...) __VA_ARGS__
436# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000437#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000438# define HAS_KEYWORDS 0
439# define IF_HAS_KEYWORDS(...)
440# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000441#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000442
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000443/* If you comment out one of these below, it will be #defined later
444 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200445#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000446/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200447#define debug_printf_parse(...) do {} while (0)
448#define debug_printf_heredoc(...) do {} while (0)
449#define debug_print_tree(a, b) do {} while (0)
450#define debug_printf_exec(...) do {} while (0)
451#define debug_printf_env(...) do {} while (0)
452#define debug_printf_jobs(...) do {} while (0)
453#define debug_printf_expand(...) do {} while (0)
454#define debug_printf_varexp(...) do {} while (0)
455#define debug_printf_glob(...) do {} while (0)
456#define debug_printf_redir(...) do {} while (0)
457#define debug_printf_list(...) do {} while (0)
458#define debug_printf_subst(...) do {} while (0)
459#define debug_printf_prompt(...) do {} while (0)
460#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000461
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000462#define ERR_PTR ((void*)(long)1)
463
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100464#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000465
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200466#define _SPECIAL_VARS_STR "_*@$!?#"
467#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
468#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100469#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200470/* Support / and // replace ops */
471/* Note that // is stored as \ in "encoded" string representation */
472# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
473# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
474# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
475#else
476# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
477# define VAR_SUBST_OPS "%#:-=+?"
478# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
479#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200480
Denys Vlasenko932b9972018-01-11 12:39:48 +0100481#define SPECIAL_VAR_SYMBOL_STR "\3"
482#define SPECIAL_VAR_SYMBOL 3
483/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
484#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000485
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200486struct variable;
487
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000488static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
489
490/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000491 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000492 */
493#if !BB_MMU
494typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200495 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000496 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000497 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000498} nommu_save_t;
499#endif
500
Denys Vlasenko9b782552010-09-08 13:33:26 +0200501enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000502 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000503#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000504 RES_IF ,
505 RES_THEN ,
506 RES_ELIF ,
507 RES_ELSE ,
508 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000509#endif
510#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000511 RES_FOR ,
512 RES_WHILE ,
513 RES_UNTIL ,
514 RES_DO ,
515 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000516#endif
517#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000518 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000519#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000520#if ENABLE_HUSH_CASE
521 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200522 /* three pseudo-keywords support contrived "case" syntax: */
523 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
524 RES_MATCH , /* "word)" */
525 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000526 RES_ESAC ,
527#endif
528 RES_XXXX ,
529 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200530};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000531
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000532typedef struct o_string {
533 char *data;
534 int length; /* position where data is appended */
535 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200536 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000537 /* At least some part of the string was inside '' or "",
538 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200539 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000540 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200541 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000542} o_string;
543enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200544 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
545 EXP_FLAG_GLOB = 0x2,
546 /* Protect newly added chars against globbing
547 * by prepending \ to *, ?, [, \ */
548 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
549};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000550/* Used for initialization: o_string foo = NULL_O_STRING; */
551#define NULL_O_STRING { NULL }
552
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200553#ifndef debug_printf_parse
554static const char *const assignment_flag[] = {
555 "MAYBE_ASSIGNMENT",
556 "DEFINITELY_ASSIGNMENT",
557 "NOT_ASSIGNMENT",
558 "WORD_IS_KEYWORD",
559};
560#endif
561
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200562/* We almost can use standard FILE api, but we need an ability to move
563 * its fd when redirects coincide with it. No api exists for that
564 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
565 * HFILE is our internal alternative. Only supports reading.
566 * Since we now can, we incorporate linked list of all opened HFILEs
567 * into the struct (used to be a separate mini-list).
568 */
569typedef struct HFILE {
570 char *cur;
571 char *end;
572 struct HFILE *next_hfile;
573 int is_stdin;
574 int fd;
575 char buf[1024];
576} HFILE;
577
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000578typedef struct in_str {
579 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200580 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200581 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200582 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000583} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000584
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200585/* The descrip member of this structure is only used to make
586 * debugging output pretty */
587static const struct {
588 int mode;
589 signed char default_fd;
590 char descrip[3];
591} redir_table[] = {
592 { O_RDONLY, 0, "<" },
593 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
594 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
595 { O_CREAT|O_RDWR, 1, "<>" },
596 { O_RDONLY, 0, "<<" },
597/* Should not be needed. Bogus default_fd helps in debugging */
598/* { O_RDONLY, 77, "<<" }, */
599};
600
Eric Andersen25f27032001-04-26 23:22:31 +0000601struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000602 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000603 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000604 int rd_fd; /* fd to redirect */
605 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
606 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000607 smallint rd_type; /* (enum redir_type) */
608 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000609 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200610 * bit 0: do we need to trim leading tabs?
611 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000612 */
Eric Andersen25f27032001-04-26 23:22:31 +0000613};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000614typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200615 REDIRECT_INPUT = 0,
616 REDIRECT_OVERWRITE = 1,
617 REDIRECT_APPEND = 2,
618 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000619 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200620 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000621
622 REDIRFD_CLOSE = -3,
623 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000624 REDIRFD_TO_FILE = -1,
625 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000626
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000627 HEREDOC_SKIPTABS = 1,
628 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000629} redir_type;
630
Eric Andersen25f27032001-04-26 23:22:31 +0000631
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000632struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000633 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200634 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100635#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100636 unsigned lineno;
637#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200638 smallint cmd_type; /* CMD_xxx */
639#define CMD_NORMAL 0
640#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200641#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
642/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
643 * "export v=t*"
644 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200645# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000646#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200647#if ENABLE_HUSH_FUNCTIONS
648# define CMD_FUNCDEF 3
649#endif
650
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100651 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200652 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
653 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000654#if !BB_MMU
655 char *group_as_string;
656#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000657#if ENABLE_HUSH_FUNCTIONS
658 struct function *child_func;
659/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200660 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000661 * When we execute "f1() {a;}" cmd, we create new function and clear
662 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200663 * When we execute "f1() {b;}", we notice that f1 exists,
664 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000665 * we put those fields back into cmd->xxx
666 * (struct function has ->parent_cmd ptr to facilitate that).
667 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
668 * Without this trick, loop would execute a;b;b;b;...
669 * instead of correct sequence a;b;a;b;...
670 * When command is freed, it severs the link
671 * (sets ->child_func->parent_cmd to NULL).
672 */
673#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000674 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000675/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
676 * and on execution these are substituted with their values.
677 * Substitution can make _several_ words out of one argv[n]!
678 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000679 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000680 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000681 struct redir_struct *redirects; /* I/O redirections */
682};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000683/* Is there anything in this command at all? */
684#define IS_NULL_CMD(cmd) \
685 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
686
Eric Andersen25f27032001-04-26 23:22:31 +0000687struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000688 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000689 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000690 int alive_cmds; /* number of commands running (not exited) */
691 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000692#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100693 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000694 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000695 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000696#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000697 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000698 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000699 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
700 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000701};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000702typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100703 PIPE_SEQ = 0,
704 PIPE_AND = 1,
705 PIPE_OR = 2,
706 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000707} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000708/* Is there anything in this pipe at all? */
709#define IS_NULL_PIPE(pi) \
710 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000711
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000712/* This holds pointers to the various results of parsing */
713struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000714 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000715 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000716 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000717 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000718 /* last command in pipe (being constructed right now) */
719 struct command *command;
720 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000721 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200722 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000723#if !BB_MMU
724 o_string as_string;
725#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200726 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000727#if HAS_KEYWORDS
728 smallint ctx_res_w;
729 smallint ctx_inverted; /* "! cmd | cmd" */
730#if ENABLE_HUSH_CASE
731 smallint ctx_dsemicolon; /* ";;" seen */
732#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000733 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
734 int old_flag;
735 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000736 * example: "if pipe1; pipe2; then pipe3; fi"
737 * when we see "if" or "then", we malloc and copy current context,
738 * and make ->stack point to it. then we parse pipeN.
739 * when closing "then" / fi" / whatever is found,
740 * we move list_head into ->stack->command->group,
741 * copy ->stack into current context, and delete ->stack.
742 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000743 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000744 struct parse_context *stack;
745#endif
746};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200747enum {
748 MAYBE_ASSIGNMENT = 0,
749 DEFINITELY_ASSIGNMENT = 1,
750 NOT_ASSIGNMENT = 2,
751 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
752 WORD_IS_KEYWORD = 3,
753};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000754
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000755/* On program start, environ points to initial environment.
756 * putenv adds new pointers into it, unsetenv removes them.
757 * Neither of these (de)allocates the strings.
758 * setenv allocates new strings in malloc space and does putenv,
759 * and thus setenv is unusable (leaky) for shell's purposes */
760#define setenv(...) setenv_is_leaky_dont_use()
761struct variable {
762 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000763 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000764 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200765 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000766 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000767 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000768};
769
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000770enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000771 BC_BREAK = 1,
772 BC_CONTINUE = 2,
773};
774
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000775#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000776struct function {
777 struct function *next;
778 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000779 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000780 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200781# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000782 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200783# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000784};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000785#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000786
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000787
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100788/* set -/+o OPT support. (TODO: make it optional)
789 * bash supports the following opts:
790 * allexport off
791 * braceexpand on
792 * emacs on
793 * errexit off
794 * errtrace off
795 * functrace off
796 * hashall on
797 * histexpand off
798 * history on
799 * ignoreeof off
800 * interactive-comments on
801 * keyword off
802 * monitor on
803 * noclobber off
804 * noexec off
805 * noglob off
806 * nolog off
807 * notify off
808 * nounset off
809 * onecmd off
810 * physical off
811 * pipefail off
812 * posix off
813 * privileged off
814 * verbose off
815 * vi off
816 * xtrace off
817 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800818static const char o_opt_strings[] ALIGN1 =
819 "pipefail\0"
820 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200821 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800822#if ENABLE_HUSH_MODE_X
823 "xtrace\0"
824#endif
825 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100826enum {
827 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800828 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200829 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800830#if ENABLE_HUSH_MODE_X
831 OPT_O_XTRACE,
832#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100833 NUM_OPT_O
834};
835
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000836/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000837/* Sorted roughly by size (smaller offsets == smaller code) */
838struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000839 /* interactive_fd != 0 means we are an interactive shell.
840 * If we are, then saved_tty_pgrp can also be != 0, meaning
841 * that controlling tty is available. With saved_tty_pgrp == 0,
842 * job control still works, but terminal signals
843 * (^C, ^Z, ^Y, ^\) won't work at all, and background
844 * process groups can only be created with "cmd &".
845 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
846 * to give tty to the foreground process group,
847 * and will take it back when the group is stopped (^Z)
848 * or killed (^C).
849 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850#if ENABLE_HUSH_INTERACTIVE
851 /* 'interactive_fd' is a fd# open to ctty, if we have one
852 * _AND_ if we decided to act interactively */
853 int interactive_fd;
854 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200855 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000856# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000857#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000858# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000859#endif
860#if ENABLE_FEATURE_EDITING
861 line_input_t *line_input_state;
862#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000863 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200864 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000865 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200866#if ENABLE_HUSH_RANDOM_SUPPORT
867 random_t random_gen;
868#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000869#if ENABLE_HUSH_JOB
870 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100871 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000872 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000873 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400874# define G_saved_tty_pgrp (G.saved_tty_pgrp)
875#else
876# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000877#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200878 /* How deeply are we in context where "set -e" is ignored */
879 int errexit_depth;
880 /* "set -e" rules (do we follow them correctly?):
881 * Exit if pipe, list, or compound command exits with a non-zero status.
882 * Shell does not exit if failed command is part of condition in
883 * if/while, part of && or || list except the last command, any command
884 * in a pipe but the last, or if the command's return value is being
885 * inverted with !. If a compound command other than a subshell returns a
886 * non-zero status because a command failed while -e was being ignored, the
887 * shell does not exit. A trap on ERR, if set, is executed before the shell
888 * exits [ERR is a bashism].
889 *
890 * If a compound command or function executes in a context where -e is
891 * ignored, none of the commands executed within are affected by the -e
892 * setting. If a compound command or function sets -e while executing in a
893 * context where -e is ignored, that setting does not have any effect until
894 * the compound command or the command containing the function call completes.
895 */
896
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100897 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100898#if ENABLE_HUSH_MODE_X
899# define G_x_mode (G.o_opt[OPT_O_XTRACE])
900#else
901# define G_x_mode 0
902#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200903#if ENABLE_HUSH_INTERACTIVE
904 smallint promptmode; /* 0: PS1, 1: PS2 */
905#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000906 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000907#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000908 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000909#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000910#if ENABLE_HUSH_FUNCTIONS
911 /* 0: outside of a function (or sourced file)
912 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000913 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000914 */
915 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200916# define G_flag_return_in_progress (G.flag_return_in_progress)
917#else
918# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000919#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000920 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200921 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000922 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200923 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200924 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100925#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000926 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000927 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100928# define G_global_args_malloced (G.global_args_malloced)
929#else
930# define G_global_args_malloced 0
931#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000932 /* how many non-NULL argv's we have. NB: $# + 1 */
933 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000934 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000935#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000936 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000937#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000938#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000939 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000940 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000941#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200942#if ENABLE_HUSH_GETOPTS
943 unsigned getopt_count;
944#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000945 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200946 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000947 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200948 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200949 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200950 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200951 unsigned var_nest_level;
952#if ENABLE_HUSH_FUNCTIONS
953# if ENABLE_HUSH_LOCAL
954 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200955# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200956 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000957#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000958 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200959#if ENABLE_HUSH_FAST
960 unsigned count_SIGCHLD;
961 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200962 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200963#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100964#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100965 unsigned lineno;
966 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100967#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200968 HFILE *HFILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200969 /* Which signals have non-DFL handler (even with no traps set)?
970 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200971 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200972 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200973 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200974 * Other than these two times, never modified.
975 */
976 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200977#if ENABLE_HUSH_JOB
978 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100979# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200980#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200981# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200982#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100983#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000984 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100985# define G_traps G.traps
986#else
987# define G_traps ((char**)NULL)
988#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200989 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100990#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000991 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100992#endif
993#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000994 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000995#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200996 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200997#if ENABLE_FEATURE_EDITING
998 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
999#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001000};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001001#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001002/* Not #defining name to G.name - this quickly gets unwieldy
1003 * (too many defines). Also, I actually prefer to see when a variable
1004 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001005#define INIT_G() do { \
1006 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001007 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1008 sigfillset(&G.sa.sa_mask); \
1009 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001010} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001011
1012
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001013/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001014static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001015#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001016static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001017#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001018static int builtin_eval(char **argv) FAST_FUNC;
1019static int builtin_exec(char **argv) FAST_FUNC;
1020static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001021#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001022static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001023#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001024#if ENABLE_HUSH_READONLY
1025static int builtin_readonly(char **argv) FAST_FUNC;
1026#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001027#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001028static int builtin_fg_bg(char **argv) FAST_FUNC;
1029static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001030#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001031#if ENABLE_HUSH_GETOPTS
1032static int builtin_getopts(char **argv) FAST_FUNC;
1033#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001034#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001035static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001036#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001037#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001038static int builtin_history(char **argv) FAST_FUNC;
1039#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001040#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001041static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001042#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001043#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001044static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001045#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001046#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001047static int builtin_printf(char **argv) FAST_FUNC;
1048#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001049static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001050#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001051static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001052#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001053#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001055#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001056static int builtin_shift(char **argv) FAST_FUNC;
1057static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001058#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001060#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001061#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001062static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001063#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001064#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001065static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001066#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001067#if ENABLE_HUSH_TIMES
1068static int builtin_times(char **argv) FAST_FUNC;
1069#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001070static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001071#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001072static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001073#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001074#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001075static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001076#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001077#if ENABLE_HUSH_KILL
1078static int builtin_kill(char **argv) FAST_FUNC;
1079#endif
1080#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001081static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001082#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001083#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001084static int builtin_break(char **argv) FAST_FUNC;
1085static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001086#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001087#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001088static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001089#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001090
1091/* Table of built-in functions. They can be forked or not, depending on
1092 * context: within pipes, they fork. As simple commands, they do not.
1093 * When used in non-forking context, they can change global variables
1094 * in the parent shell process. If forked, of course they cannot.
1095 * For example, 'unset foo | whatever' will parse and run, but foo will
1096 * still be set at the end. */
1097struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001098 const char *b_cmd;
1099 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001100#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001101 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001102# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001103#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001104# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001105#endif
1106};
1107
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001108static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001109 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001110 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001111#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001112 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001113#endif
1114#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001115 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001116#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001117 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001118#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001119 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001120#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001121 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1122 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001123 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001124#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001125 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001126#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001127#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001128 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001129#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001130#if ENABLE_HUSH_GETOPTS
1131 BLTIN("getopts" , builtin_getopts , NULL),
1132#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001133#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001134 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001135#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001136#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001137 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001138#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001139#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001140 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001141#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001142#if ENABLE_HUSH_KILL
1143 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1144#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001145#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001146 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001147#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001148#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001149 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001150#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001151#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001152 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001153#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001154#if ENABLE_HUSH_READONLY
1155 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1156#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001157#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001158 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001159#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001160#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001161 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001162#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001163 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001164#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001165 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001166#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001167#if ENABLE_HUSH_TIMES
1168 BLTIN("times" , builtin_times , NULL),
1169#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001170#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001171 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001172#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001173 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001174#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001175 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001176#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001177#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001178 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001179#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001180#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001181 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001182#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001183#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001184 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001185#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001186#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001187 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001188#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001189};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001190/* These builtins won't be used if we are on NOMMU and need to re-exec
1191 * (it's cheaper to run an external program in this case):
1192 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001193static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001194#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001195 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001196#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001197#if BASH_TEST2
1198 BLTIN("[[" , builtin_test , NULL),
1199#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001200#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001201 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001202#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001203#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001204 BLTIN("printf" , builtin_printf , NULL),
1205#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001206 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001207#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001208 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001209#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001210};
1211
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001212
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001213/* Debug printouts.
1214 */
1215#if HUSH_DEBUG
1216/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001217# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001218# define debug_enter() (G.debug_indent++)
1219# define debug_leave() (G.debug_indent--)
1220#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001221# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001222# define debug_enter() ((void)0)
1223# define debug_leave() ((void)0)
1224#endif
1225
1226#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001227# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001228#endif
1229
1230#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001231# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001232#endif
1233
Denys Vlasenko3675c372018-07-23 16:31:21 +02001234#ifndef debug_printf_heredoc
1235# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1236#endif
1237
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001238#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001239#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001240#endif
1241
1242#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001243# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001244#endif
1245
1246#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001247# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001248# define DEBUG_JOBS 1
1249#else
1250# define DEBUG_JOBS 0
1251#endif
1252
1253#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001254# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001255# define DEBUG_EXPAND 1
1256#else
1257# define DEBUG_EXPAND 0
1258#endif
1259
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001260#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001261# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001262#endif
1263
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001264#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001265# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001266# define DEBUG_GLOB 1
1267#else
1268# define DEBUG_GLOB 0
1269#endif
1270
Denys Vlasenko2db74612017-07-07 22:07:28 +02001271#ifndef debug_printf_redir
1272# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1273#endif
1274
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001275#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001276# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001277#endif
1278
1279#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001280# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001281#endif
1282
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001283#ifndef debug_printf_prompt
1284# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1285#endif
1286
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001287#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001288# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001289# define DEBUG_CLEAN 1
1290#else
1291# define DEBUG_CLEAN 0
1292#endif
1293
1294#if DEBUG_EXPAND
1295static void debug_print_strings(const char *prefix, char **vv)
1296{
1297 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001298 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001299 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001300 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001301}
1302#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001303# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001304#endif
1305
1306
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001307/* Leak hunting. Use hush_leaktool.sh for post-processing.
1308 */
1309#if LEAK_HUNTING
1310static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001311{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001312 void *ptr = xmalloc((size + 0xff) & ~0xff);
1313 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1314 return ptr;
1315}
1316static void *xxrealloc(int lineno, void *ptr, size_t size)
1317{
1318 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1319 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1320 return ptr;
1321}
1322static char *xxstrdup(int lineno, const char *str)
1323{
1324 char *ptr = xstrdup(str);
1325 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1326 return ptr;
1327}
1328static void xxfree(void *ptr)
1329{
1330 fdprintf(2, "free %p\n", ptr);
1331 free(ptr);
1332}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001333# define xmalloc(s) xxmalloc(__LINE__, s)
1334# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1335# define xstrdup(s) xxstrdup(__LINE__, s)
1336# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001337#endif
1338
1339
1340/* Syntax and runtime errors. They always abort scripts.
1341 * In interactive use they usually discard unparsed and/or unexecuted commands
1342 * and return to the prompt.
1343 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1344 */
1345#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001346# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001347# define syntax_error(lineno, msg) syntax_error(msg)
1348# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1349# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1350# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1351# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001352#endif
1353
Denys Vlasenko39701202017-08-02 19:44:05 +02001354static void die_if_script(void)
1355{
1356 if (!G_interactive_fd) {
1357 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1358 xfunc_error_retval = G.last_exitcode;
1359 xfunc_die();
1360 }
1361}
1362
1363static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001364{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001365 va_list p;
1366
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001367#if HUSH_DEBUG >= 2
1368 bb_error_msg("hush.c:%u", lineno);
1369#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001370 va_start(p, fmt);
1371 bb_verror_msg(fmt, p, NULL);
1372 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001373 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001374}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001375
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001376static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001377{
1378 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001379 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001380 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001381 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001382 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001383}
1384
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001385static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001386{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001387 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001388 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001389}
1390
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001391static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001392{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001393 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001394//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1395// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001396}
1397
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001398static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001399{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001400 char msg[2] = { ch, '\0' };
1401 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001402}
1403
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001404static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001405{
1406 char msg[2];
1407 msg[0] = ch;
1408 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001409#if HUSH_DEBUG >= 2
1410 bb_error_msg("hush.c:%u", lineno);
1411#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001412 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001413 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001414}
1415
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001416#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001417# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001418# undef syntax_error
1419# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001420# undef syntax_error_unterm_ch
1421# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001422# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001423#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001424# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001425# define syntax_error(msg) syntax_error(__LINE__, msg)
1426# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1427# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1428# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1429# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001430#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001431
Denis Vlasenko552433b2009-04-04 19:29:21 +00001432
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001433#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001434static void cmdedit_update_prompt(void);
1435#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001436# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001437#endif
1438
1439
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001440/* Utility functions
1441 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001442/* Replace each \x with x in place, return ptr past NUL. */
1443static char *unbackslash(char *src)
1444{
Denys Vlasenko71885402009-09-24 01:44:13 +02001445 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001446 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001447 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001448 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001449 if (*src != '\0') {
1450 /* \x -> x */
1451 *dst++ = *src++;
1452 continue;
1453 }
1454 /* else: "\<nul>". Do not delete this backslash.
1455 * Testcase: eval 'echo ok\'
1456 */
1457 *dst++ = '\\';
1458 /* fallthrough */
1459 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001460 if ((*dst++ = *src++) == '\0')
1461 break;
1462 }
1463 return dst;
1464}
1465
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001466static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001467{
1468 int i;
1469 unsigned count1;
1470 unsigned count2;
1471 char **v;
1472
1473 v = strings;
1474 count1 = 0;
1475 if (v) {
1476 while (*v) {
1477 count1++;
1478 v++;
1479 }
1480 }
1481 count2 = 0;
1482 v = add;
1483 while (*v) {
1484 count2++;
1485 v++;
1486 }
1487 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1488 v[count1 + count2] = NULL;
1489 i = count2;
1490 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001491 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001492 return v;
1493}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001494#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001495static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1496{
1497 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1498 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1499 return ptr;
1500}
1501#define add_strings_to_strings(strings, add, need_to_dup) \
1502 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1503#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001504
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001505/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001506static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001507{
1508 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001509 v[0] = add;
1510 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001511 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001512}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001513#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001514static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1515{
1516 char **ptr = add_string_to_strings(strings, add);
1517 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1518 return ptr;
1519}
1520#define add_string_to_strings(strings, add) \
1521 xx_add_string_to_strings(__LINE__, strings, add)
1522#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001523
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001524static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001525{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001526 char **v;
1527
1528 if (!strings)
1529 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001530 v = strings;
1531 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001532 free(*v);
1533 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001534 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001535 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001536}
1537
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001538static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001539{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001540 int newfd;
1541 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001542 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1543 if (newfd >= 0) {
1544 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1545 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1546 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001547 if (errno == EBUSY)
1548 goto repeat;
1549 if (errno == EINTR)
1550 goto repeat;
1551 }
1552 return newfd;
1553}
1554
Denys Vlasenko657e9002017-07-30 23:34:04 +02001555static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001556{
1557 int newfd;
1558 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001559 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001560 if (newfd < 0) {
1561 if (errno == EBUSY)
1562 goto repeat;
1563 if (errno == EINTR)
1564 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001565 /* fd was not open? */
1566 if (errno == EBADF)
1567 return fd;
1568 xfunc_die();
1569 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001570 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1571 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001572 close(fd);
1573 return newfd;
1574}
1575
1576
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001577/* Manipulating HFILEs */
1578static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001579{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001580 HFILE *fp;
1581 int fd;
1582
1583 fd = STDIN_FILENO;
1584 if (name) {
1585 fd = open(name, O_RDONLY | O_CLOEXEC);
1586 if (fd < 0)
1587 return NULL;
1588 if (O_CLOEXEC == 0) /* ancient libc */
1589 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001590 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001591
1592 fp = xmalloc(sizeof(*fp));
1593 fp->is_stdin = (name == NULL);
1594 fp->fd = fd;
1595 fp->cur = fp->end = fp->buf;
1596 fp->next_hfile = G.HFILE_list;
1597 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001598 return fp;
1599}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001600static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001601{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001602 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001603 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001604 HFILE *cur = *pp;
1605 if (cur == fp) {
1606 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001607 break;
1608 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001609 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001610 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001611 if (fp->fd >= 0)
1612 close(fp->fd);
1613 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001614}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001615static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001616{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001617 int n;
1618
1619 if (fp->fd < 0) {
1620 /* Already saw EOF */
1621 return EOF;
1622 }
1623 /* Try to buffer more input */
1624 fp->cur = fp->buf;
1625 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1626 if (n < 0) {
1627 bb_perror_msg("read error");
1628 n = 0;
1629 }
1630 fp->end = fp->buf + n;
1631 if (n == 0) {
1632 /* EOF/error */
1633 close(fp->fd);
1634 fp->fd = -1;
1635 return EOF;
1636 }
1637 return (unsigned char)(*fp->cur++);
1638}
1639/* Inlined for common case of non-empty buffer.
1640 */
1641static ALWAYS_INLINE int hfgetc(HFILE *fp)
1642{
1643 if (fp->cur < fp->end)
1644 return (unsigned char)(*fp->cur++);
1645 /* Buffer empty */
1646 return refill_HFILE_and_getc(fp);
1647}
1648static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1649{
1650 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001651 while (fl) {
1652 if (fd == fl->fd) {
1653 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001654 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001655 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001656 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001657 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001658 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001659 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001660 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001661}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001662#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001663static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001664{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001665 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001666 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001667 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001668 * It is disastrous if we share memory with a vforked parent.
1669 * I'm not sure we never come here after vfork.
1670 * Therefore just close fd, nothing more.
1671 */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001672 /*hfclose(fl); - unsafe */
1673 if (fl->fd >= 0)
1674 close(fl->fd);
1675 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001676 }
1677}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001678#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001679static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001680{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001681 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001682 while (fl) {
1683 if (fl->fd == fd)
1684 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001685 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001686 }
1687 return 0;
1688}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001689
1690
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001691/* Helpers for setting new $n and restoring them back
1692 */
1693typedef struct save_arg_t {
1694 char *sv_argv0;
1695 char **sv_g_argv;
1696 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001697 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001698} save_arg_t;
1699
1700static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1701{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001702 sv->sv_argv0 = argv[0];
1703 sv->sv_g_argv = G.global_argv;
1704 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001705 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001706
1707 argv[0] = G.global_argv[0]; /* retain $0 */
1708 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001709 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001710
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001711 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001712}
1713
1714static void restore_G_args(save_arg_t *sv, char **argv)
1715{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001716#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001717 if (G.global_args_malloced) {
1718 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001719 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001720 while (*++pp) /* note: does not free $0 */
1721 free(*pp);
1722 free(G.global_argv);
1723 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001724#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001725 argv[0] = sv->sv_argv0;
1726 G.global_argv = sv->sv_g_argv;
1727 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001728 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001729}
1730
1731
Denis Vlasenkod5762932009-03-31 11:22:57 +00001732/* Basic theory of signal handling in shell
1733 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001734 * This does not describe what hush does, rather, it is current understanding
1735 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001736 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1737 *
1738 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1739 * is finished or backgrounded. It is the same in interactive and
1740 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001741 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001742 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001743 * backgrounds (i.e. stops) or kills all members of currently running
1744 * pipe.
1745 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001746 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001747 * or by SIGINT in interactive shell.
1748 *
1749 * Trap handlers will execute even within trap handlers. (right?)
1750 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001751 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1752 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001753 *
1754 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001755 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001756 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001757 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001758 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001759 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001760 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001761 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001762 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001763 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001764 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001765 *
1766 * SIGQUIT: ignore
1767 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001768 * SIGHUP (interactive):
1769 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001770 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001771 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1772 * that all pipe members are stopped. Try this in bash:
1773 * while :; do :; done - ^Z does not background it
1774 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001775 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001776 * of the command line, show prompt. NB: ^C does not send SIGINT
1777 * to interactive shell while shell is waiting for a pipe,
1778 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001779 * Example 1: this waits 5 sec, but does not execute ls:
1780 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1781 * Example 2: this does not wait and does not execute ls:
1782 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1783 * Example 3: this does not wait 5 sec, but executes ls:
1784 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001785 * Example 4: this does not wait and does not execute ls:
1786 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001787 *
1788 * (What happens to signals which are IGN on shell start?)
1789 * (What happens with signal mask on shell start?)
1790 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001791 * Old implementation
1792 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001793 * We use in-kernel pending signal mask to determine which signals were sent.
1794 * We block all signals which we don't want to take action immediately,
1795 * i.e. we block all signals which need to have special handling as described
1796 * above, and all signals which have traps set.
1797 * After each pipe execution, we extract any pending signals via sigtimedwait()
1798 * and act on them.
1799 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001800 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001801 * sigset_t blocked_set: current blocked signal set
1802 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001803 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001804 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001805 * "trap 'cmd' SIGxxx":
1806 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001807 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001808 * unblock signals with special interactive handling
1809 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001810 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001811 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001812 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001813 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001814 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001815 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001816 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001817 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001818 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001819 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001820 * Standard says "When a subshell is entered, traps that are not being ignored
1821 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001822 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001823 *
1824 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001825 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001826 * masked signals are not visible!
1827 *
1828 * New implementation
1829 * ==================
1830 * We record each signal we are interested in by installing signal handler
1831 * for them - a bit like emulating kernel pending signal mask in userspace.
1832 * We are interested in: signals which need to have special handling
1833 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001834 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001835 * After each pipe execution, we extract any pending signals
1836 * and act on them.
1837 *
1838 * unsigned special_sig_mask: a mask of shell-special signals.
1839 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1840 * char *traps[sig] if trap for sig is set (even if it's '').
1841 * sigset_t pending_set: set of sigs we received.
1842 *
1843 * "trap - SIGxxx":
1844 * if sig is in special_sig_mask, set handler back to:
1845 * record_pending_signo, or to IGN if it's a tty stop signal
1846 * if sig is in fatal_sig_mask, set handler back to sigexit.
1847 * else: set handler back to SIG_DFL
1848 * "trap 'cmd' SIGxxx":
1849 * set handler to record_pending_signo.
1850 * "trap '' SIGxxx":
1851 * set handler to SIG_IGN.
1852 * after [v]fork, if we plan to be a shell:
1853 * set signals with special interactive handling to SIG_DFL
1854 * (because child shell is not interactive),
1855 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1856 * after [v]fork, if we plan to exec:
1857 * POSIX says fork clears pending signal mask in child - no need to clear it.
1858 *
1859 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1860 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1861 *
1862 * Note (compat):
1863 * Standard says "When a subshell is entered, traps that are not being ignored
1864 * are set to the default actions". bash interprets it so that traps which
1865 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001866 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001867enum {
1868 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001869 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001870 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001871 | (1 << SIGHUP)
1872 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001873 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001874#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001875 | (1 << SIGTTIN)
1876 | (1 << SIGTTOU)
1877 | (1 << SIGTSTP)
1878#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001879 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001880};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001881
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001882static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001883{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001884 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001885#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001886 if (sig == SIGCHLD) {
1887 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001888//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 +02001889 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001890#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001891}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001892
Denys Vlasenko0806e402011-05-12 23:06:20 +02001893static sighandler_t install_sighandler(int sig, sighandler_t handler)
1894{
1895 struct sigaction old_sa;
1896
1897 /* We could use signal() to install handlers... almost:
1898 * except that we need to mask ALL signals while handlers run.
1899 * I saw signal nesting in strace, race window isn't small.
1900 * SA_RESTART is also needed, but in Linux, signal()
1901 * sets SA_RESTART too.
1902 */
1903 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1904 /* sigfillset(&G.sa.sa_mask); - already done */
1905 /* G.sa.sa_flags = SA_RESTART; - already done */
1906 G.sa.sa_handler = handler;
1907 sigaction(sig, &G.sa, &old_sa);
1908 return old_sa.sa_handler;
1909}
1910
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001911static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001912
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001913static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001914static void restore_ttypgrp_and__exit(void)
1915{
1916 /* xfunc has failed! die die die */
1917 /* no EXIT traps, this is an escape hatch! */
1918 G.exiting = 1;
1919 hush_exit(xfunc_error_retval);
1920}
1921
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001922#if ENABLE_HUSH_JOB
1923
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001924/* Needed only on some libc:
1925 * It was observed that on exit(), fgetc'ed buffered data
1926 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1927 * With the net effect that even after fork(), not vfork(),
1928 * exit() in NOEXECed applet in "sh SCRIPT":
1929 * noexec_applet_here
1930 * echo END_OF_SCRIPT
1931 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1932 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001933 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001934 * and in `cmd` handling.
1935 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1936 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001937static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001938static void fflush_and__exit(void)
1939{
1940 fflush_all();
1941 _exit(xfunc_error_retval);
1942}
1943
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001944/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001945# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001946/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001947# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001948
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001949/* Restores tty foreground process group, and exits.
1950 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001951 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001952 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001953 * We also call it if xfunc is exiting.
1954 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001955static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001956static void sigexit(int sig)
1957{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001958 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001959 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001960 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1961 /* Disable all signals: job control, SIGPIPE, etc.
1962 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1963 */
1964 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001965 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001966 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001967
1968 /* Not a signal, just exit */
1969 if (sig <= 0)
1970 _exit(- sig);
1971
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001972 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001973}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001974#else
1975
Denys Vlasenko8391c482010-05-22 17:50:43 +02001976# define disable_restore_tty_pgrp_on_exit() ((void)0)
1977# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001978
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001979#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001980
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001981static sighandler_t pick_sighandler(unsigned sig)
1982{
1983 sighandler_t handler = SIG_DFL;
1984 if (sig < sizeof(unsigned)*8) {
1985 unsigned sigmask = (1 << sig);
1986
1987#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001988 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001989 if (G_fatal_sig_mask & sigmask)
1990 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001991 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001992#endif
1993 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001994 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001995 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001996 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001997 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001998 * in an endless loop when we try to do some
1999 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002000 */
2001 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2002 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002003 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002004 }
2005 return handler;
2006}
2007
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002008/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002009static void hush_exit(int exitcode)
2010{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002011#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2012 save_history(G.line_input_state);
2013#endif
2014
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002015 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002016 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002017 char *argv[3];
2018 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002019 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002020 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002021 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002022 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002023 * "trap" will still show it, if executed
2024 * in the handler */
2025 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002026 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002027
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002028#if ENABLE_FEATURE_CLEAN_UP
2029 {
2030 struct variable *cur_var;
2031 if (G.cwd != bb_msg_unknown)
2032 free((char*)G.cwd);
2033 cur_var = G.top_var;
2034 while (cur_var) {
2035 struct variable *tmp = cur_var;
2036 if (!cur_var->max_len)
2037 free(cur_var->varstr);
2038 cur_var = cur_var->next;
2039 free(tmp);
2040 }
2041 }
2042#endif
2043
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002044 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002045#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002046 sigexit(- (exitcode & 0xff));
2047#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002048 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002049#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002050}
2051
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002052
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002053//TODO: return a mask of ALL handled sigs?
2054static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002055{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002056 int last_sig = 0;
2057
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002058 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002059 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002060
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002061 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002062 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002063 sig = 0;
2064 do {
2065 sig++;
2066 if (sigismember(&G.pending_set, sig)) {
2067 sigdelset(&G.pending_set, sig);
2068 goto got_sig;
2069 }
2070 } while (sig < NSIG);
2071 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002072 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002073 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002074 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002075 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002076 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002077 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002078 char *argv[3];
2079 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002080 argv[1] = xstrdup(G_traps[sig]);
2081 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002082 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002083 save_rcode = G.last_exitcode;
2084 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002085 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002086//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002087 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002088 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002089 } /* else: "" trap, ignoring signal */
2090 continue;
2091 }
2092 /* not a trap: special action */
2093 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002094 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002095 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002096 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002097 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002098 break;
2099#if ENABLE_HUSH_JOB
2100 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002101//TODO: why are we doing this? ash and dash don't do this,
2102//they have no handler for SIGHUP at all,
2103//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002104 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002105 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002106 /* bash is observed to signal whole process groups,
2107 * not individual processes */
2108 for (job = G.job_list; job; job = job->next) {
2109 if (job->pgrp <= 0)
2110 continue;
2111 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2112 if (kill(- job->pgrp, SIGHUP) == 0)
2113 kill(- job->pgrp, SIGCONT);
2114 }
2115 sigexit(SIGHUP);
2116 }
2117#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002118#if ENABLE_HUSH_FAST
2119 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002120 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002121 G.count_SIGCHLD++;
2122//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2123 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002124 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002125 * This simplifies wait builtin a bit.
2126 */
2127 break;
2128#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002129 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002130 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002131 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002132 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002133 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002134 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002135 * in interactive shell, because TERM is ignored.
2136 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002137 break;
2138 }
2139 }
2140 return last_sig;
2141}
2142
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002143
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002144static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002145{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002146 if (force || G.cwd == NULL) {
2147 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2148 * we must not try to free(bb_msg_unknown) */
2149 if (G.cwd == bb_msg_unknown)
2150 G.cwd = NULL;
2151 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2152 if (!G.cwd)
2153 G.cwd = bb_msg_unknown;
2154 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002155 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002156}
2157
Denis Vlasenko83506862007-11-23 13:11:42 +00002158
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002159/*
2160 * Shell and environment variable support
2161 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002162static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002163{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002164 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002165 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002166
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002167 pp = &G.top_var;
2168 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002169 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002170 return pp;
2171 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002172 }
2173 return NULL;
2174}
2175
Denys Vlasenko03dad222010-01-12 23:29:57 +01002176static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002177{
Denys Vlasenko29082232010-07-16 13:52:32 +02002178 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002179 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002180
2181 if (G.expanded_assignments) {
2182 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002183 while (*cpp) {
2184 char *cp = *cpp;
2185 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2186 return cp + len + 1;
2187 cpp++;
2188 }
2189 }
2190
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002191 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002192 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002193 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002194
Denys Vlasenkodea47882009-10-09 15:40:49 +02002195 if (strcmp(name, "PPID") == 0)
2196 return utoa(G.root_ppid);
2197 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002198#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002199 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002200 return utoa(next_random(&G.random_gen));
2201#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202 return NULL;
2203}
2204
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002205static void handle_changed_special_names(const char *name, unsigned name_len)
2206{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002207 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2208 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2209 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002210 cmdedit_update_prompt();
2211 return;
2212 }
2213
2214 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2215 && name_len == 6
2216 ) {
2217#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002218 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002219 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002220 return;
2221 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002222#endif
2223#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002224 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002225 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002226 return;
2227 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002228#endif
2229 }
2230}
2231
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002232/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002233 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002234 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002235#define SETFLAG_EXPORT (1 << 0)
2236#define SETFLAG_UNEXPORT (1 << 1)
2237#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002238#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002239static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002240{
Denys Vlasenko61407802018-04-04 21:14:28 +02002241 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002242 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002243 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002244 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002245 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002246 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002247
Denis Vlasenko950bd722009-04-21 11:23:56 +00002248 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002249 if (HUSH_DEBUG && !eq_sign)
2250 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002251
Denis Vlasenko950bd722009-04-21 11:23:56 +00002252 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002253 cur_pp = &G.top_var;
2254 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002255 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002256 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002257 continue;
2258 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002259
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002260 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002261 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002262 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002263 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002264//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2265//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266 return -1;
2267 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002268 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002269 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2270 *eq_sign = '\0';
2271 unsetenv(str);
2272 *eq_sign = '=';
2273 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002274 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002275 /* bash 3.2.33(1) and exported vars:
2276 * # export z=z
2277 * # f() { local z=a; env | grep ^z; }
2278 * # f
2279 * z=a
2280 * # env | grep ^z
2281 * z=z
2282 */
2283 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002284 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002285 /* New variable is local ("local VAR=VAL" or
2286 * "VAR=VAL cmd")
2287 * and existing one is global, or local
2288 * on a lower level that new one.
2289 * Remove it from global variable list:
2290 */
2291 *cur_pp = cur->next;
2292 if (G.shadowed_vars_pp) {
2293 /* Save in "shadowed" list */
2294 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2295 cur->flg_export ? "exported " : "",
2296 cur->varstr, cur->var_nest_level, str, local_lvl
2297 );
2298 cur->next = *G.shadowed_vars_pp;
2299 *G.shadowed_vars_pp = cur;
2300 } else {
2301 /* Came from pseudo_exec_argv(), no need to save: delete it */
2302 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2303 cur->flg_export ? "exported " : "",
2304 cur->varstr, cur->var_nest_level, str, local_lvl
2305 );
2306 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2307 free_me = cur->varstr; /* then free it later */
2308 free(cur);
2309 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002310 break;
2311 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002312
Denis Vlasenko950bd722009-04-21 11:23:56 +00002313 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002314 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315 free_and_exp:
2316 free(str);
2317 goto exp;
2318 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002319
2320 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002321 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002322 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002323 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002324 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002325 strcpy(cur->varstr, str);
2326 goto free_and_exp;
2327 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002328 /* Can't reuse */
2329 cur->max_len = 0;
2330 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002331 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002332 /* max_len == 0 signifies "malloced" var, which we can
2333 * (and have to) free. But we can't free(cur->varstr) here:
2334 * if cur->flg_export is 1, it is in the environment.
2335 * We should either unsetenv+free, or wait until putenv,
2336 * then putenv(new)+free(old).
2337 */
2338 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002339 goto set_str_and_exp;
2340 }
2341
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002342 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002343 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002344 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002345 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002346 cur->next = *cur_pp;
2347 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002348
2349 set_str_and_exp:
2350 cur->varstr = str;
2351 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002352#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002353 if (flags & SETFLAG_MAKE_RO) {
2354 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002355 }
2356#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002357 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002358 cur->flg_export = 1;
2359 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002360 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002361 cur->flg_export = 0;
2362 /* unsetenv was already done */
2363 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002364 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002365 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002366 i = putenv(cur->varstr);
2367 /* only now we can free old exported malloced string */
2368 free(free_me);
2369 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002370 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002371 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002372 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002373
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002374 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002375
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002376 return 0;
2377}
2378
Denys Vlasenko6db47842009-09-05 20:15:17 +02002379/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002380static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002381{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002382 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002383}
2384
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002385#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002386static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002387{
2388 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002389 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002390
Denys Vlasenko61407802018-04-04 21:14:28 +02002391 cur_pp = &G.top_var;
2392 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002393 if (strncmp(cur->varstr, name, name_len) == 0
2394 && cur->varstr[name_len] == '='
2395 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002396 if (cur->flg_read_only) {
2397 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002398 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002399 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002400
Denys Vlasenko61407802018-04-04 21:14:28 +02002401 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002402 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2403 bb_unsetenv(cur->varstr);
2404 if (!cur->max_len)
2405 free(cur->varstr);
2406 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002407
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002408 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002409 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002410 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002411 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002412
2413 /* Handle "unset PS1" et al even if did not find the variable to unset */
2414 handle_changed_special_names(name, name_len);
2415
Mike Frysingerd690f682009-03-30 06:50:54 +00002416 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002417}
2418
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002419static int unset_local_var(const char *name)
2420{
2421 return unset_local_var_len(name, strlen(name));
2422}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002423#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002424
Denys Vlasenkob2b14cb2018-06-26 18:09:22 +02002425#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2426 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002427static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002428{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002429 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002430 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002431}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002432#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002433
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002434
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002435/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002436 * Helpers for "var1=val1 var2=val2 cmd" feature
2437 */
2438static void add_vars(struct variable *var)
2439{
2440 struct variable *next;
2441
2442 while (var) {
2443 next = var->next;
2444 var->next = G.top_var;
2445 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002446 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002447 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002448 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002449 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002450 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002451 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002452 var = next;
2453 }
2454}
2455
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002456/* We put strings[i] into variable table and possibly putenv them.
2457 * If variable is read only, we can free the strings[i]
2458 * which attempts to overwrite it.
2459 * The strings[] vector itself is freed.
2460 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002461static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002462{
2463 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002464
2465 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002466 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002467
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002468 s = strings;
2469 while (*s) {
2470 struct variable *var_p;
2471 struct variable **var_pp;
2472 char *eq;
2473
2474 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002475 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002476 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002477 var_pp = get_ptr_to_local_var(*s, eq - *s);
2478 if (var_pp) {
2479 var_p = *var_pp;
2480 if (var_p->flg_read_only) {
2481 char **p;
2482 bb_error_msg("%s: readonly variable", *s);
2483 /*
2484 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2485 * If VAR is readonly, leaving it in the list
2486 * after asssignment error (msg above)
2487 * causes doubled error message later, on unset.
2488 */
2489 debug_printf_env("removing/freeing '%s' element\n", *s);
2490 free(*s);
2491 p = s;
2492 do { *p = p[1]; p++; } while (*p);
2493 goto next;
2494 }
2495 /* below, set_local_var() with nest level will
2496 * "shadow" (remove) this variable from
2497 * global linked list.
2498 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002499 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002500 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2501 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002502 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002503 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002504 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002505 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002506}
2507
2508
2509/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002510 * Unicode helper
2511 */
2512static void reinit_unicode_for_hush(void)
2513{
2514 /* Unicode support should be activated even if LANG is set
2515 * _during_ shell execution, not only if it was set when
2516 * shell was started. Therefore, re-check LANG every time:
2517 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002518 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2519 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002520 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002521 const char *s = get_local_var_value("LC_ALL");
2522 if (!s) s = get_local_var_value("LC_CTYPE");
2523 if (!s) s = get_local_var_value("LANG");
2524 reinit_unicode(s);
2525 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002526}
2527
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002528/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002529 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002530 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002531
2532#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002533/* To test correct lineedit/interactive behavior, type from command line:
2534 * echo $P\
2535 * \
2536 * AT\
2537 * H\
2538 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002539 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002540 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002541# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002542static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002543{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002544 G.PS1 = get_local_var_value("PS1");
2545 if (G.PS1 == NULL)
2546 G.PS1 = "";
2547 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002548 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002549 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002550}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002551# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002552static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002553{
2554 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002555
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002556 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002557
2558 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2559 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002560 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002561 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2562 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002563 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002564 /* bash uses $PWD value, even if it is set by user.
2565 * It uses current dir only if PWD is unset.
2566 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002567 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002568 }
2569 prompt_str = G.PS1;
2570 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002571 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002572 return prompt_str;
2573}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002574static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002575{
2576 int r;
2577 const char *prompt_str;
2578
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002579 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002580# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002581 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002582 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002583 if (G.flag_SIGINT) {
2584 /* There was ^C'ed, make it look prettier: */
2585 bb_putchar('\n');
2586 G.flag_SIGINT = 0;
2587 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002588 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002589 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002590 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002591 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002592 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002593 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002594 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002595 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002596 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002597 if (r != 0 && !G.flag_SIGINT)
2598 break;
2599 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002600 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2601 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002602 G.last_exitcode = 128 + SIGINT;
2603 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002604 if (r < 0) {
2605 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002606 i->p = NULL;
2607 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002608 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002609 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002610 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002611 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002612# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002613 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002614 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002615 if (i->last_char == '\0' || i->last_char == '\n') {
2616 /* Why check_and_run_traps here? Try this interactively:
2617 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2618 * $ <[enter], repeatedly...>
2619 * Without check_and_run_traps, handler never runs.
2620 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002621 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002622 fputs(prompt_str, stdout);
2623 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002624 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002625//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002626 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002627 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2628 * no ^C masking happens during fgetc, no special code for ^C:
2629 * it generates SIGINT as usual.
2630 */
2631 check_and_run_traps();
2632 if (G.flag_SIGINT)
2633 G.last_exitcode = 128 + SIGINT;
2634 if (r != '\0')
2635 break;
2636 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002637 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002638# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002639}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002640/* This is the magic location that prints prompts
2641 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002642static int fgetc_interactive(struct in_str *i)
2643{
2644 int ch;
2645 /* If it's interactive stdin, get new line. */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002646 if (G_interactive_fd && i->file->is_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002647 /* Returns first char (or EOF), the rest is in i->p[] */
2648 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002649 G.promptmode = 1; /* PS2 */
2650 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002651 } else {
2652 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002653 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002654 }
2655 return ch;
2656}
2657#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002658static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002659{
2660 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002661 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002662 return ch;
2663}
2664#endif /* INTERACTIVE */
2665
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002666static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002667{
2668 int ch;
2669
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002670 if (!i->file) {
2671 /* string-based in_str */
2672 ch = (unsigned char)*i->p;
2673 if (ch != '\0') {
2674 i->p++;
2675 i->last_char = ch;
2676 return ch;
2677 }
2678 return EOF;
2679 }
2680
2681 /* FILE-based in_str */
2682
Denys Vlasenko4074d492016-09-30 01:49:53 +02002683#if ENABLE_FEATURE_EDITING
2684 /* This can be stdin, check line editing char[] buffer */
2685 if (i->p && *i->p != '\0') {
2686 ch = (unsigned char)*i->p++;
2687 goto out;
2688 }
2689#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002690 /* peek_buf[] is an int array, not char. Can contain EOF. */
2691 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002692 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002693 int ch2 = i->peek_buf[1];
2694 i->peek_buf[0] = ch2;
2695 if (ch2 == 0) /* very likely, avoid redundant write */
2696 goto out;
2697 i->peek_buf[1] = 0;
2698 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002699 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002700
Denys Vlasenko4074d492016-09-30 01:49:53 +02002701 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002702 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002703 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002704 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002705#if ENABLE_HUSH_LINENO_VAR
2706 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002707 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002708 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2709 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002710#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002711 return ch;
2712}
2713
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002714static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002715{
2716 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002717
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002718 if (!i->file) {
2719 /* string-based in_str */
2720 /* Doesn't report EOF on NUL. None of the callers care. */
2721 return (unsigned char)*i->p;
2722 }
2723
2724 /* FILE-based in_str */
2725
Denys Vlasenko4074d492016-09-30 01:49:53 +02002726#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002727 /* This can be stdin, check line editing char[] buffer */
2728 if (i->p && *i->p != '\0')
2729 return (unsigned char)*i->p;
2730#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002731 /* peek_buf[] is an int array, not char. Can contain EOF. */
2732 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002733 if (ch != 0)
2734 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002735
Denys Vlasenko4074d492016-09-30 01:49:53 +02002736 /* Need to get a new char */
2737 ch = fgetc_interactive(i);
2738 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2739
2740 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2741#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2742 if (i->p) {
2743 i->p -= 1;
2744 return ch;
2745 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002746#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002747 i->peek_buf[0] = ch;
2748 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002749 return ch;
2750}
2751
Denys Vlasenko4074d492016-09-30 01:49:53 +02002752/* Only ever called if i_peek() was called, and did not return EOF.
2753 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2754 * not end-of-line. Therefore we never need to read a new editing line here.
2755 */
2756static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002757{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002758 int ch;
2759
2760 /* There are two cases when i->p[] buffer exists.
2761 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002762 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002763 * In both cases, we know that i->p[0] exists and not NUL, and
2764 * the peek2 result is in i->p[1].
2765 */
2766 if (i->p)
2767 return (unsigned char)i->p[1];
2768
2769 /* Now we know it is a file-based in_str. */
2770
2771 /* peek_buf[] is an int array, not char. Can contain EOF. */
2772 /* Is there 2nd char? */
2773 ch = i->peek_buf[1];
2774 if (ch == 0) {
2775 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002776 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002777 i->peek_buf[1] = ch;
2778 }
2779
2780 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2781 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002782}
2783
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002784static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2785{
2786 for (;;) {
2787 int ch, ch2;
2788
2789 ch = i_getch(input);
2790 if (ch != '\\')
2791 return ch;
2792 ch2 = i_peek(input);
2793 if (ch2 != '\n')
2794 return ch;
2795 /* backslash+newline, skip it */
2796 i_getch(input);
2797 }
2798}
2799
2800/* Note: this function _eats_ \<newline> pairs, safe to use plain
2801 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2802 */
2803static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2804{
2805 for (;;) {
2806 int ch, ch2;
2807
2808 ch = i_peek(input);
2809 if (ch != '\\')
2810 return ch;
2811 ch2 = i_peek2(input);
2812 if (ch2 != '\n')
2813 return ch;
2814 /* backslash+newline, skip it */
2815 i_getch(input);
2816 i_getch(input);
2817 }
2818}
2819
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002820static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002821{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002822 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002823 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002824 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002825}
2826
2827static void setup_string_in_str(struct in_str *i, const char *s)
2828{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002829 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002830 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002831 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002832}
2833
2834
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002835/*
2836 * o_string support
2837 */
2838#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002839
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002840static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002841{
2842 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002843 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002844 if (o->data)
2845 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002846}
2847
Denys Vlasenko18567402018-07-20 17:51:31 +02002848static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002849{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002850 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002851 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002852}
2853
Denys Vlasenko18567402018-07-20 17:51:31 +02002854static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002855{
2856 free(o->data);
2857}
2858
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002859static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002860{
2861 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002862 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002863 o->data = xrealloc(o->data, 1 + o->maxlen);
2864 }
2865}
2866
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002867static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002868{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002869 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002870 if (o->length < o->maxlen) {
2871 /* likely. avoid o_grow_by() call */
2872 add:
2873 o->data[o->length] = ch;
2874 o->length++;
2875 o->data[o->length] = '\0';
2876 return;
2877 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002878 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002879 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002880}
2881
Denys Vlasenko657086a2016-09-29 18:07:42 +02002882#if 0
2883/* Valid only if we know o_string is not empty */
2884static void o_delchr(o_string *o)
2885{
2886 o->length--;
2887 o->data[o->length] = '\0';
2888}
2889#endif
2890
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002891static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002892{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002893 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002894 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002895 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002896}
2897
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002898static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002899{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002900 o_addblock(o, str, strlen(str));
2901}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002902
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002903#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002904static void nommu_addchr(o_string *o, int ch)
2905{
2906 if (o)
2907 o_addchr(o, ch);
2908}
2909#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002910# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002911#endif
2912
2913static void o_addstr_with_NUL(o_string *o, const char *str)
2914{
2915 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002916}
2917
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002918/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002919 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002920 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2921 * Apparently, on unquoted $v bash still does globbing
2922 * ("v='*.txt'; echo $v" prints all .txt files),
2923 * but NOT brace expansion! Thus, there should be TWO independent
2924 * quoting mechanisms on $v expansion side: one protects
2925 * $v from brace expansion, and other additionally protects "$v" against globbing.
2926 * We have only second one.
2927 */
2928
Denys Vlasenko9e800222010-10-03 14:28:04 +02002929#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002930# define MAYBE_BRACES "{}"
2931#else
2932# define MAYBE_BRACES ""
2933#endif
2934
Eric Andersen25f27032001-04-26 23:22:31 +00002935/* My analysis of quoting semantics tells me that state information
2936 * is associated with a destination, not a source.
2937 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002938static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002939{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002940 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002941 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002942 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002943 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002944 o_grow_by(o, sz);
2945 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002946 o->data[o->length] = '\\';
2947 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002948 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002949 o->data[o->length] = ch;
2950 o->length++;
2951 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002952}
2953
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002954static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002955{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002956 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002957 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2958 && strchr("*?[\\" MAYBE_BRACES, ch)
2959 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002960 sz++;
2961 o->data[o->length] = '\\';
2962 o->length++;
2963 }
2964 o_grow_by(o, sz);
2965 o->data[o->length] = ch;
2966 o->length++;
2967 o->data[o->length] = '\0';
2968}
2969
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002970static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002971{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002972 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002973 char ch;
2974 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002975 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002976 if (ordinary_cnt > len) /* paranoia */
2977 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002978 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002979 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002980 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002981 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002982 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002983
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002984 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002985 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002986 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002987 sz++;
2988 o->data[o->length] = '\\';
2989 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002990 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002991 o_grow_by(o, sz);
2992 o->data[o->length] = ch;
2993 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002994 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002995 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002996}
2997
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002998static void o_addQblock(o_string *o, const char *str, int len)
2999{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003000 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003001 o_addblock(o, str, len);
3002 return;
3003 }
3004 o_addqblock(o, str, len);
3005}
3006
Denys Vlasenko38292b62010-09-05 14:49:40 +02003007static void o_addQstr(o_string *o, const char *str)
3008{
3009 o_addQblock(o, str, strlen(str));
3010}
3011
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003012/* A special kind of o_string for $VAR and `cmd` expansion.
3013 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003014 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003015 * list[i] contains an INDEX (int!) into this string data.
3016 * It means that if list[] needs to grow, data needs to be moved higher up
3017 * but list[i]'s need not be modified.
3018 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003019 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003020 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3021 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003022#if DEBUG_EXPAND || DEBUG_GLOB
3023static void debug_print_list(const char *prefix, o_string *o, int n)
3024{
3025 char **list = (char**)o->data;
3026 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3027 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003028
3029 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003030 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 +02003031 prefix, list, n, string_start, o->length, o->maxlen,
3032 !!(o->o_expflags & EXP_FLAG_GLOB),
3033 o->has_quoted_part,
3034 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003035 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003036 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003037 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3038 o->data + (int)(uintptr_t)list[i] + string_start,
3039 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003040 i++;
3041 }
3042 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003043 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003044 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003045 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003046 }
3047}
3048#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003049# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003050#endif
3051
3052/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3053 * in list[n] so that it points past last stored byte so far.
3054 * It returns n+1. */
3055static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003056{
3057 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003058 int string_start;
3059 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003060
3061 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003062 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3063 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003064 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003065 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003066 /* list[n] points to string_start, make space for 16 more pointers */
3067 o->maxlen += 0x10 * sizeof(list[0]);
3068 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003069 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003070 memmove(list + n + 0x10, list + n, string_len);
3071 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003072 } else {
3073 debug_printf_list("list[%d]=%d string_start=%d\n",
3074 n, string_len, string_start);
3075 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003076 } else {
3077 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003078 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3079 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003080 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3081 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003082 o->has_empty_slot = 0;
3083 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003084 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003085 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003086 return n + 1;
3087}
3088
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003089/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003090static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003091{
3092 char **list = (char**)o->data;
3093 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3094
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003095 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003096}
3097
Denys Vlasenko9e800222010-10-03 14:28:04 +02003098#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003099/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3100 * first, it processes even {a} (no commas), second,
3101 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003102 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003103 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003104
3105/* Helper */
3106static int glob_needed(const char *s)
3107{
3108 while (*s) {
3109 if (*s == '\\') {
3110 if (!s[1])
3111 return 0;
3112 s += 2;
3113 continue;
3114 }
3115 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3116 return 1;
3117 s++;
3118 }
3119 return 0;
3120}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003121/* Return pointer to next closing brace or to comma */
3122static const char *next_brace_sub(const char *cp)
3123{
3124 unsigned depth = 0;
3125 cp++;
3126 while (*cp != '\0') {
3127 if (*cp == '\\') {
3128 if (*++cp == '\0')
3129 break;
3130 cp++;
3131 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003132 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003133 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003134 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003135 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003136 depth++;
3137 }
3138
3139 return *cp != '\0' ? cp : NULL;
3140}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003141/* Recursive brace globber. Note: may garble pattern[]. */
3142static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003143{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003144 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003145 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003146 const char *next;
3147 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003148 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003149 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003150
3151 debug_printf_glob("glob_brace('%s')\n", pattern);
3152
3153 begin = pattern;
3154 while (1) {
3155 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003156 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003157 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003158 /* Find the first sub-pattern and at the same time
3159 * find the rest after the closing brace */
3160 next = next_brace_sub(begin);
3161 if (next == NULL) {
3162 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003163 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003164 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003165 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003166 /* "{abc}" with no commas - illegal
3167 * brace expr, disregard and skip it */
3168 begin = next + 1;
3169 continue;
3170 }
3171 break;
3172 }
3173 if (*begin == '\\' && begin[1] != '\0')
3174 begin++;
3175 begin++;
3176 }
3177 debug_printf_glob("begin:%s\n", begin);
3178 debug_printf_glob("next:%s\n", next);
3179
3180 /* Now find the end of the whole brace expression */
3181 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003182 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003183 rest = next_brace_sub(rest);
3184 if (rest == NULL) {
3185 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003186 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003187 }
3188 debug_printf_glob("rest:%s\n", rest);
3189 }
3190 rest_len = strlen(++rest) + 1;
3191
3192 /* We are sure the brace expression is well-formed */
3193
3194 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003195 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003196
3197 /* We have a brace expression. BEGIN points to the opening {,
3198 * NEXT points past the terminator of the first element, and REST
3199 * points past the final }. We will accumulate result names from
3200 * recursive runs for each brace alternative in the buffer using
3201 * GLOB_APPEND. */
3202
3203 p = begin + 1;
3204 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003205 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003206 memcpy(
3207 mempcpy(
3208 mempcpy(new_pattern_buf,
3209 /* We know the prefix for all sub-patterns */
3210 pattern, begin - pattern),
3211 p, next - p),
3212 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003213
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003214 /* Note: glob_brace() may garble new_pattern_buf[].
3215 * That's why we re-copy prefix every time (1st memcpy above).
3216 */
3217 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003218 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003219 /* We saw the last entry */
3220 break;
3221 }
3222 p = next + 1;
3223 next = next_brace_sub(next);
3224 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003225 free(new_pattern_buf);
3226 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003227
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003228 simple_glob:
3229 {
3230 int gr;
3231 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003232
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003233 memset(&globdata, 0, sizeof(globdata));
3234 gr = glob(pattern, 0, NULL, &globdata);
3235 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3236 if (gr != 0) {
3237 if (gr == GLOB_NOMATCH) {
3238 globfree(&globdata);
3239 /* NB: garbles parameter */
3240 unbackslash(pattern);
3241 o_addstr_with_NUL(o, pattern);
3242 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3243 return o_save_ptr_helper(o, n);
3244 }
3245 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003246 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003247 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3248 * but we didn't specify it. Paranoia again. */
3249 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3250 }
3251 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3252 char **argv = globdata.gl_pathv;
3253 while (1) {
3254 o_addstr_with_NUL(o, *argv);
3255 n = o_save_ptr_helper(o, n);
3256 argv++;
3257 if (!*argv)
3258 break;
3259 }
3260 }
3261 globfree(&globdata);
3262 }
3263 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003264}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003265/* Performs globbing on last list[],
3266 * saving each result as a new list[].
3267 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003268static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003269{
3270 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003271
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003272 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003273 if (!o->data)
3274 return o_save_ptr_helper(o, n);
3275 pattern = o->data + o_get_last_ptr(o, n);
3276 debug_printf_glob("glob pattern '%s'\n", pattern);
3277 if (!glob_needed(pattern)) {
3278 /* unbackslash last string in o in place, fix length */
3279 o->length = unbackslash(pattern) - o->data;
3280 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3281 return o_save_ptr_helper(o, n);
3282 }
3283
3284 copy = xstrdup(pattern);
3285 /* "forget" pattern in o */
3286 o->length = pattern - o->data;
3287 n = glob_brace(copy, o, n);
3288 free(copy);
3289 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003290 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003291 return n;
3292}
3293
Denys Vlasenko238081f2010-10-03 14:26:26 +02003294#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003295
3296/* Helper */
3297static int glob_needed(const char *s)
3298{
3299 while (*s) {
3300 if (*s == '\\') {
3301 if (!s[1])
3302 return 0;
3303 s += 2;
3304 continue;
3305 }
3306 if (*s == '*' || *s == '[' || *s == '?')
3307 return 1;
3308 s++;
3309 }
3310 return 0;
3311}
3312/* Performs globbing on last list[],
3313 * saving each result as a new list[].
3314 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003315static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003316{
3317 glob_t globdata;
3318 int gr;
3319 char *pattern;
3320
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003321 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003322 if (!o->data)
3323 return o_save_ptr_helper(o, n);
3324 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003325 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003326 if (!glob_needed(pattern)) {
3327 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003328 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003329 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003330 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003331 return o_save_ptr_helper(o, n);
3332 }
3333
3334 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003335 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3336 * If we glob "*.\*" and don't find anything, we need
3337 * to fall back to using literal "*.*", but GLOB_NOCHECK
3338 * will return "*.\*"!
3339 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003340 gr = glob(pattern, 0, NULL, &globdata);
3341 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003342 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003343 if (gr == GLOB_NOMATCH) {
3344 globfree(&globdata);
3345 goto literal;
3346 }
3347 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003348 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003349 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3350 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003351 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003352 }
3353 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3354 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003355 /* "forget" pattern in o */
3356 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003357 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003358 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003359 n = o_save_ptr_helper(o, n);
3360 argv++;
3361 if (!*argv)
3362 break;
3363 }
3364 }
3365 globfree(&globdata);
3366 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003367 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003368 return n;
3369}
3370
Denys Vlasenko238081f2010-10-03 14:26:26 +02003371#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003372
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003373/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003374 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003375static int o_save_ptr(o_string *o, int n)
3376{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003377 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003378 /* If o->has_empty_slot, list[n] was already globbed
3379 * (if it was requested back then when it was filled)
3380 * so don't do that again! */
3381 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003382 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003383 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003384 return o_save_ptr_helper(o, n);
3385}
3386
3387/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003388static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003389{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003390 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003391 int string_start;
3392
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003393 if (DEBUG_EXPAND)
3394 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003395 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003396 list = (char**)o->data;
3397 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3398 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003399 while (n) {
3400 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003401 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003402 }
3403 return list;
3404}
3405
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003406static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003407
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003408/* Returns pi->next - next pipe in the list */
3409static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003410{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003411 struct pipe *next;
3412 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003413
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003414 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003415 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003416 struct command *command;
3417 struct redir_struct *r, *rnext;
3418
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003419 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003420 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003421 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003422 if (DEBUG_CLEAN) {
3423 int a;
3424 char **p;
3425 for (a = 0, p = command->argv; *p; a++, p++) {
3426 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3427 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003428 }
3429 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003430 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003431 }
3432 /* not "else if": on syntax error, we may have both! */
3433 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003434 debug_printf_clean(" begin group (cmd_type:%d)\n",
3435 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003436 free_pipe_list(command->group);
3437 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003438 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003439 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003440 /* else is crucial here.
3441 * If group != NULL, child_func is meaningless */
3442#if ENABLE_HUSH_FUNCTIONS
3443 else if (command->child_func) {
3444 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3445 command->child_func->parent_cmd = NULL;
3446 }
3447#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003448#if !BB_MMU
3449 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003450 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003451#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003452 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003453 debug_printf_clean(" redirect %d%s",
3454 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003455 /* guard against the case >$FOO, where foo is unset or blank */
3456 if (r->rd_filename) {
3457 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3458 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003459 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003460 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003461 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003462 rnext = r->next;
3463 free(r);
3464 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003465 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003466 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003467 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003468 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003469#if ENABLE_HUSH_JOB
3470 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003471 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003472#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003473
3474 next = pi->next;
3475 free(pi);
3476 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003477}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003478
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003479static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003480{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003481 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003482#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003483 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003484#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003485 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003486 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003487 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003488}
3489
3490
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003491/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003492
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003493#ifndef debug_print_tree
3494static void debug_print_tree(struct pipe *pi, int lvl)
3495{
3496 static const char *const PIPE[] = {
3497 [PIPE_SEQ] = "SEQ",
3498 [PIPE_AND] = "AND",
3499 [PIPE_OR ] = "OR" ,
3500 [PIPE_BG ] = "BG" ,
3501 };
3502 static const char *RES[] = {
3503 [RES_NONE ] = "NONE" ,
3504# if ENABLE_HUSH_IF
3505 [RES_IF ] = "IF" ,
3506 [RES_THEN ] = "THEN" ,
3507 [RES_ELIF ] = "ELIF" ,
3508 [RES_ELSE ] = "ELSE" ,
3509 [RES_FI ] = "FI" ,
3510# endif
3511# if ENABLE_HUSH_LOOPS
3512 [RES_FOR ] = "FOR" ,
3513 [RES_WHILE] = "WHILE",
3514 [RES_UNTIL] = "UNTIL",
3515 [RES_DO ] = "DO" ,
3516 [RES_DONE ] = "DONE" ,
3517# endif
3518# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3519 [RES_IN ] = "IN" ,
3520# endif
3521# if ENABLE_HUSH_CASE
3522 [RES_CASE ] = "CASE" ,
3523 [RES_CASE_IN ] = "CASE_IN" ,
3524 [RES_MATCH] = "MATCH",
3525 [RES_CASE_BODY] = "CASE_BODY",
3526 [RES_ESAC ] = "ESAC" ,
3527# endif
3528 [RES_XXXX ] = "XXXX" ,
3529 [RES_SNTX ] = "SNTX" ,
3530 };
3531 static const char *const CMDTYPE[] = {
3532 "{}",
3533 "()",
3534 "[noglob]",
3535# if ENABLE_HUSH_FUNCTIONS
3536 "func()",
3537# endif
3538 };
3539
3540 int pin, prn;
3541
3542 pin = 0;
3543 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003544 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3545 lvl*2, "",
3546 pin,
3547 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3548 RES[pi->res_word],
3549 pi->followup, PIPE[pi->followup]
3550 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003551 prn = 0;
3552 while (prn < pi->num_cmds) {
3553 struct command *command = &pi->cmds[prn];
3554 char **argv = command->argv;
3555
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003556 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003557 lvl*2, "", prn,
3558 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003559#if ENABLE_HUSH_LINENO_VAR
3560 fdprintf(2, " LINENO:%u", command->lineno);
3561#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003562 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003563 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003564 CMDTYPE[command->cmd_type],
3565 argv
3566# if !BB_MMU
3567 , " group_as_string:", command->group_as_string
3568# else
3569 , "", ""
3570# endif
3571 );
3572 debug_print_tree(command->group, lvl+1);
3573 prn++;
3574 continue;
3575 }
3576 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003577 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003578 argv++;
3579 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003580 if (command->redirects)
3581 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003582 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003583 prn++;
3584 }
3585 pi = pi->next;
3586 pin++;
3587 }
3588}
3589#endif /* debug_print_tree */
3590
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003591static struct pipe *new_pipe(void)
3592{
Eric Andersen25f27032001-04-26 23:22:31 +00003593 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003594 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003595 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003596 return pi;
3597}
3598
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003599/* Command (member of a pipe) is complete, or we start a new pipe
3600 * if ctx->command is NULL.
3601 * No errors possible here.
3602 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003603static int done_command(struct parse_context *ctx)
3604{
3605 /* The command is really already in the pipe structure, so
3606 * advance the pipe counter and make a new, null command. */
3607 struct pipe *pi = ctx->pipe;
3608 struct command *command = ctx->command;
3609
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003610#if 0 /* Instead we emit error message at run time */
3611 if (ctx->pending_redirect) {
3612 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003613 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003614 ctx->pending_redirect = NULL;
3615 }
3616#endif
3617
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003618 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003619 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003620 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003621 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003622 }
3623 pi->num_cmds++;
3624 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003625 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003626 } else {
3627 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3628 }
3629
3630 /* Only real trickiness here is that the uncommitted
3631 * command structure is not counted in pi->num_cmds. */
3632 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003633 ctx->command = command = &pi->cmds[pi->num_cmds];
3634 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003635 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003636#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003637 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003638 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003639#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003640 return pi->num_cmds; /* used only for 0/nonzero check */
3641}
3642
3643static void done_pipe(struct parse_context *ctx, pipe_style type)
3644{
3645 int not_null;
3646
3647 debug_printf_parse("done_pipe entered, followup %d\n", type);
3648 /* Close previous command */
3649 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003650#if HAS_KEYWORDS
3651 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3652 ctx->ctx_inverted = 0;
3653 ctx->pipe->res_word = ctx->ctx_res_w;
3654#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003655 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3656 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003657 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3658 * in a backgrounded subshell.
3659 */
3660 struct pipe *pi;
3661 struct command *command;
3662
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003663 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003664 pi = ctx->list_head;
3665 while (pi != ctx->pipe) {
3666 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3667 goto no_conv;
3668 pi = pi->next;
3669 }
3670
3671 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3672 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3673 pi = xzalloc(sizeof(*pi));
3674 pi->followup = PIPE_BG;
3675 pi->num_cmds = 1;
3676 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3677 command = &pi->cmds[0];
3678 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3679 command->cmd_type = CMD_NORMAL;
3680 command->group = ctx->list_head;
3681#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003682 command->group_as_string = xstrndup(
3683 ctx->as_string.data,
3684 ctx->as_string.length - 1 /* do not copy last char, "&" */
3685 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003686#endif
3687 /* Replace all pipes in ctx with one newly created */
3688 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003689 } else {
3690 no_conv:
3691 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003692 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003693
3694 /* Without this check, even just <enter> on command line generates
3695 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003696 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003697 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003698#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003699 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003700#endif
3701#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003702 || ctx->ctx_res_w == RES_DONE
3703 || ctx->ctx_res_w == RES_FOR
3704 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003705#endif
3706#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003707 || ctx->ctx_res_w == RES_ESAC
3708#endif
3709 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003710 struct pipe *new_p;
3711 debug_printf_parse("done_pipe: adding new pipe: "
3712 "not_null:%d ctx->ctx_res_w:%d\n",
3713 not_null, ctx->ctx_res_w);
3714 new_p = new_pipe();
3715 ctx->pipe->next = new_p;
3716 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003717 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003718 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003719 * This is used to control execution.
3720 * RES_FOR and RES_IN are NOT sticky (needed to support
3721 * cases where variable or value happens to match a keyword):
3722 */
3723#if ENABLE_HUSH_LOOPS
3724 if (ctx->ctx_res_w == RES_FOR
3725 || ctx->ctx_res_w == RES_IN)
3726 ctx->ctx_res_w = RES_NONE;
3727#endif
3728#if ENABLE_HUSH_CASE
3729 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003730 ctx->ctx_res_w = RES_CASE_BODY;
3731 if (ctx->ctx_res_w == RES_CASE)
3732 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003733#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003734 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003735 /* Create the memory for command, roughly:
3736 * ctx->pipe->cmds = new struct command;
3737 * ctx->command = &ctx->pipe->cmds[0];
3738 */
3739 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003740 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003741 }
3742 debug_printf_parse("done_pipe return\n");
3743}
3744
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003745static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003746{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003747 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003748 if (MAYBE_ASSIGNMENT != 0)
3749 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003750 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003751 /* Create the memory for command, roughly:
3752 * ctx->pipe->cmds = new struct command;
3753 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003754 */
3755 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003756}
3757
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003758/* If a reserved word is found and processed, parse context is modified
3759 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003760 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003761#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003762struct reserved_combo {
3763 char literal[6];
3764 unsigned char res;
3765 unsigned char assignment_flag;
3766 int flag;
3767};
3768enum {
3769 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003770# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003771 FLAG_IF = (1 << RES_IF ),
3772 FLAG_THEN = (1 << RES_THEN ),
3773 FLAG_ELIF = (1 << RES_ELIF ),
3774 FLAG_ELSE = (1 << RES_ELSE ),
3775 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003776# endif
3777# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003778 FLAG_FOR = (1 << RES_FOR ),
3779 FLAG_WHILE = (1 << RES_WHILE),
3780 FLAG_UNTIL = (1 << RES_UNTIL),
3781 FLAG_DO = (1 << RES_DO ),
3782 FLAG_DONE = (1 << RES_DONE ),
3783 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003784# endif
3785# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003786 FLAG_MATCH = (1 << RES_MATCH),
3787 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003788# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003789 FLAG_START = (1 << RES_XXXX ),
3790};
3791
3792static const struct reserved_combo* match_reserved_word(o_string *word)
3793{
Eric Andersen25f27032001-04-26 23:22:31 +00003794 /* Mostly a list of accepted follow-up reserved words.
3795 * FLAG_END means we are done with the sequence, and are ready
3796 * to turn the compound list into a command.
3797 * FLAG_START means the word must start a new compound list.
3798 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003799 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003800# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003801 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3802 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3803 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3804 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3805 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3806 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003807# endif
3808# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003809 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3810 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3811 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3812 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3813 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3814 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003815# endif
3816# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003817 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3818 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003819# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003820 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003821 const struct reserved_combo *r;
3822
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003823 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003824 if (strcmp(word->data, r->literal) == 0)
3825 return r;
3826 }
3827 return NULL;
3828}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003829/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003830 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003831static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003832{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003833# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003834 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003835 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003836 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003837# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003838 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003839
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003840 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003841 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003842 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003843 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003844 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003845
3846 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003847# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003848 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3849 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003850 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003851 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003852# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003853 if (r->flag == 0) { /* '!' */
3854 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003855 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003856 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003857 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003858 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003859 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003860 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003861 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003862 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003863
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003864 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003865 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003866 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003867 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003868 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003869 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003870 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003871 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003872 } else {
3873 /* "{...} fi" is ok. "{...} if" is not
3874 * Example:
3875 * if { echo foo; } then { echo bar; } fi */
3876 if (ctx->command->group)
3877 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003878 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003879
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003880 ctx->ctx_res_w = r->res;
3881 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003882 ctx->is_assignment = r->assignment_flag;
3883 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003884
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003885 if (ctx->old_flag & FLAG_END) {
3886 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003887
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003888 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003889 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003890 old = ctx->stack;
3891 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003892 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003893# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003894 /* At this point, the compound command's string is in
3895 * ctx->as_string... except for the leading keyword!
3896 * Consider this example: "echo a | if true; then echo a; fi"
3897 * ctx->as_string will contain "true; then echo a; fi",
3898 * with "if " remaining in old->as_string!
3899 */
3900 {
3901 char *str;
3902 int len = old->as_string.length;
3903 /* Concatenate halves */
3904 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02003905 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003906 /* Find where leading keyword starts in first half */
3907 str = old->as_string.data + len;
3908 if (str > old->as_string.data)
3909 str--; /* skip whitespace after keyword */
3910 while (str > old->as_string.data && isalpha(str[-1]))
3911 str--;
3912 /* Ugh, we're done with this horrid hack */
3913 old->command->group_as_string = xstrdup(str);
3914 debug_printf_parse("pop, remembering as:'%s'\n",
3915 old->command->group_as_string);
3916 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003917# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003918 *ctx = *old; /* physical copy */
3919 free(old);
3920 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003921 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003922}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003923#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003924
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003925/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003926 * Normal return is 0. Syntax errors return 1.
3927 * Note: on return, word is reset, but not o_free'd!
3928 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003929static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003930{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003931 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003932
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003933 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3934 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003935 debug_printf_parse("done_word return 0: true null, ignored\n");
3936 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003937 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003938
Eric Andersen25f27032001-04-26 23:22:31 +00003939 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003940 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3941 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003942 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003943 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003944 * If the redirection operator is "<<" or "<<-", the word
3945 * that follows the redirection operator shall be
3946 * subjected to quote removal; it is unspecified whether
3947 * any of the other expansions occur. For the other
3948 * redirection operators, the word that follows the
3949 * redirection operator shall be subjected to tilde
3950 * expansion, parameter expansion, command substitution,
3951 * arithmetic expansion, and quote removal.
3952 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003953 * on the word by a non-interactive shell; an interactive
3954 * shell may perform it, but shall do so only when
3955 * the expansion would result in one word."
3956 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003957//bash does not do parameter/command substitution or arithmetic expansion
3958//for _heredoc_ redirection word: these constructs look for exact eof marker
3959// as written:
3960// <<EOF$t
3961// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003962// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3963
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003964 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003965 /* Cater for >\file case:
3966 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3967 * Same with heredocs:
3968 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3969 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003970 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3971 unbackslash(ctx->pending_redirect->rd_filename);
3972 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003973 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003974 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3975 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003976 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003977 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003978 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003979 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003980#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003981# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003982 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003983 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003984 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003985 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003986 /* ctx->ctx_res_w = RES_MATCH; */
3987 ctx->ctx_dsemicolon = 0;
3988 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003989# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003990 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003991# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003992 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3993 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003994# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003995# if ENABLE_HUSH_CASE
3996 && ctx->ctx_res_w != RES_CASE
3997# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003998 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003999 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004000 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004001 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004002 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004003# if ENABLE_HUSH_LINENO_VAR
4004/* Case:
4005 * "while ...; do
4006 * cmd ..."
4007 * If we don't close the pipe _now_, immediately after "do", lineno logic
4008 * sees "cmd" as starting at "do" - i.e., at the previous line.
4009 */
4010 if (0
4011 IF_HUSH_IF(|| reserved->res == RES_THEN)
4012 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4013 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4014 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4015 ) {
4016 done_pipe(ctx, PIPE_SEQ);
4017 }
4018# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004019 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004020 debug_printf_parse("done_word return %d\n",
4021 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004022 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004023 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004024# if defined(CMD_SINGLEWORD_NOGLOB)
4025 if (0
4026# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004027 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004028# endif
4029 /* In bash, local/export/readonly are special, args
4030 * are assignments and therefore expansion of them
4031 * should be "one-word" expansion:
4032 * $ export i=`echo 'a b'` # one arg: "i=a b"
4033 * compare with:
4034 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4035 * ls: cannot access i=a: No such file or directory
4036 * ls: cannot access b: No such file or directory
4037 * Note: bash 3.2.33(1) does this only if export word
4038 * itself is not quoted:
4039 * $ export i=`echo 'aaa bbb'`; echo "$i"
4040 * aaa bbb
4041 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4042 * aaa
4043 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004044 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4045 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4046 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004047 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004048 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4049 }
4050 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004051# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004052 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004053#endif /* HAS_KEYWORDS */
4054
Denis Vlasenkobb929512009-04-16 10:59:40 +00004055 if (command->group) {
4056 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004057 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004058 debug_printf_parse("done_word return 1: syntax error, "
4059 "groups and arglists don't mix\n");
4060 return 1;
4061 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004062
4063 /* If this word wasn't an assignment, next ones definitely
4064 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004065 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4066 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004067 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004068 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004069 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004070 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004071 command->assignment_cnt++;
4072 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4073 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004074 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4075 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004076 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004077 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4078 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004079 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004080 }
Eric Andersen25f27032001-04-26 23:22:31 +00004081
Denis Vlasenko06810332007-05-21 23:30:54 +00004082#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004083 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004084 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004085 || !is_well_formed_var_name(command->argv[0], '\0')
4086 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004087 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004088 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004089 return 1;
4090 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004091 /* Force FOR to have just one word (variable name) */
4092 /* NB: basically, this makes hush see "for v in ..."
4093 * syntax as if it is "for v; in ...". FOR and IN become
4094 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004095 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004096 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004097#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004098#if ENABLE_HUSH_CASE
4099 /* Force CASE to have just one word */
4100 if (ctx->ctx_res_w == RES_CASE) {
4101 done_pipe(ctx, PIPE_SEQ);
4102 }
4103#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004104
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004105 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004106
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004107 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004108 return 0;
4109}
4110
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004111
4112/* Peek ahead in the input to find out if we have a "&n" construct,
4113 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004114 * Return:
4115 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4116 * REDIRFD_SYNTAX_ERR if syntax error,
4117 * REDIRFD_TO_FILE if no & was seen,
4118 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004119 */
4120#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004121#define parse_redir_right_fd(as_string, input) \
4122 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004123#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004124static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004125{
4126 int ch, d, ok;
4127
4128 ch = i_peek(input);
4129 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004130 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004131
4132 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004133 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004134 ch = i_peek(input);
4135 if (ch == '-') {
4136 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004137 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004138 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004139 }
4140 d = 0;
4141 ok = 0;
4142 while (ch != EOF && isdigit(ch)) {
4143 d = d*10 + (ch-'0');
4144 ok = 1;
4145 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004146 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004147 ch = i_peek(input);
4148 }
4149 if (ok) return d;
4150
4151//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4152
4153 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004154 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004155}
4156
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004157/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004158 */
4159static int parse_redirect(struct parse_context *ctx,
4160 int fd,
4161 redir_type style,
4162 struct in_str *input)
4163{
4164 struct command *command = ctx->command;
4165 struct redir_struct *redir;
4166 struct redir_struct **redirp;
4167 int dup_num;
4168
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004169 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004170 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004171 /* Check for a '>&1' type redirect */
4172 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4173 if (dup_num == REDIRFD_SYNTAX_ERR)
4174 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004175 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004176 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004177 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004178 if (dup_num) { /* <<-... */
4179 ch = i_getch(input);
4180 nommu_addchr(&ctx->as_string, ch);
4181 ch = i_peek(input);
4182 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004183 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004184
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004185 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004186 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004187 if (ch == '|') {
4188 /* >|FILE redirect ("clobbering" >).
4189 * Since we do not support "set -o noclobber" yet,
4190 * >| and > are the same for now. Just eat |.
4191 */
4192 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004193 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004194 }
4195 }
4196
4197 /* Create a new redir_struct and append it to the linked list */
4198 redirp = &command->redirects;
4199 while ((redir = *redirp) != NULL) {
4200 redirp = &(redir->next);
4201 }
4202 *redirp = redir = xzalloc(sizeof(*redir));
4203 /* redir->next = NULL; */
4204 /* redir->rd_filename = NULL; */
4205 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004206 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004207
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004208 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4209 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004210
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004211 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004212 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004213 /* Erik had a check here that the file descriptor in question
4214 * is legit; I postpone that to "run time"
4215 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004216 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4217 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004218 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004219#if 0 /* Instead we emit error message at run time */
4220 if (ctx->pending_redirect) {
4221 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004222 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004223 }
4224#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004225 /* Set ctx->pending_redirect, so we know what to do at the
4226 * end of the next parsed word. */
4227 ctx->pending_redirect = redir;
4228 }
4229 return 0;
4230}
4231
Eric Andersen25f27032001-04-26 23:22:31 +00004232/* If a redirect is immediately preceded by a number, that number is
4233 * supposed to tell which file descriptor to redirect. This routine
4234 * looks for such preceding numbers. In an ideal world this routine
4235 * needs to handle all the following classes of redirects...
4236 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4237 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4238 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4239 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004240 *
4241 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4242 * "2.7 Redirection
4243 * ... If n is quoted, the number shall not be recognized as part of
4244 * the redirection expression. For example:
4245 * echo \2>a
4246 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004247 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004248 *
4249 * A -1 return means no valid number was found,
4250 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004251 */
4252static int redirect_opt_num(o_string *o)
4253{
4254 int num;
4255
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004256 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004257 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004258 num = bb_strtou(o->data, NULL, 10);
4259 if (errno || num < 0)
4260 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004261 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004262 return num;
4263}
4264
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004265#if BB_MMU
4266#define fetch_till_str(as_string, input, word, skip_tabs) \
4267 fetch_till_str(input, word, skip_tabs)
4268#endif
4269static char *fetch_till_str(o_string *as_string,
4270 struct in_str *input,
4271 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004272 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004273{
4274 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004275 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004276 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004277 int ch;
4278
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004279 /* Starting with "" is necessary for this case:
4280 * cat <<EOF
4281 *
4282 * xxx
4283 * EOF
4284 */
4285 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4286
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004287 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004288
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004289 while (1) {
4290 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004291 if (ch != EOF)
4292 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004293 if (ch == '\n' || ch == EOF) {
4294 check_heredoc_end:
4295 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004296 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004297 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4298 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004299 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004300 return heredoc.data;
4301 }
4302 if (ch == '\n') {
4303 /* This is a new line.
4304 * Remember position and backslash-escaping status.
4305 */
4306 o_addchr(&heredoc, ch);
4307 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004308 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004309 past_EOL = heredoc.length;
4310 /* Get 1st char of next line, possibly skipping leading tabs */
4311 do {
4312 ch = i_getch(input);
4313 if (ch != EOF)
4314 nommu_addchr(as_string, ch);
4315 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4316 /* If this immediately ended the line,
4317 * go back to end-of-line checks.
4318 */
4319 if (ch == '\n')
4320 goto check_heredoc_end;
4321 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004322 } else {
4323 /* Backslash-line continuation in an unquoted
4324 * heredoc. This does not need special handling
4325 * for heredoc body (unquoted heredocs are
4326 * expanded on "execution" and that would take
4327 * care of this case too), but not the case
4328 * of line continuation *in terminator*:
4329 * cat <<EOF
4330 * Ok1
4331 * EO\
4332 * F
4333 */
4334 heredoc.data[--heredoc.length] = '\0';
4335 prev = 0; /* not '\' */
4336 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004337 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004338 }
4339 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004340 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004341 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004342 }
4343 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004344 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004345 if (prev == '\\' && ch == '\\')
4346 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004347 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004348 else
4349 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004350 }
4351}
4352
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004353/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4354 * and load them all. There should be exactly heredoc_cnt of them.
4355 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004356#if BB_MMU
4357#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4358 fetch_heredocs(pi, heredoc_cnt, input)
4359#endif
4360static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004361{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004362 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004363 int i;
4364 struct command *cmd = pi->cmds;
4365
Denys Vlasenko3675c372018-07-23 16:31:21 +02004366 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004367 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004368 cmd->argv ? cmd->argv[0] : "NONE"
4369 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004370 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004371 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004372
Denys Vlasenko3675c372018-07-23 16:31:21 +02004373 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004374 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004375 while (redir) {
4376 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004377 char *p;
4378
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004379 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004380 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004381 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004382 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004383 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004384 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004385 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004386 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004387 free(redir->rd_filename);
4388 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004389 heredoc_cnt--;
4390 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004391 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004392 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004393 if (cmd->group) {
4394 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4395 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4396 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4397 if (heredoc_cnt < 0)
4398 return heredoc_cnt; /* error */
4399 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004400 cmd++;
4401 }
4402 pi = pi->next;
4403 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004404 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004405}
4406
4407
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004408static int run_list(struct pipe *pi);
4409#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004410#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4411 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004412#endif
4413static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004414 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004415 struct in_str *input,
4416 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004417
Denys Vlasenko474cb202018-07-24 13:03:03 +02004418/* Returns number of heredocs not yet consumed,
4419 * or -1 on error.
4420 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004421static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004422 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004423{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004424 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004425 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004426 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004427#if BB_MMU
4428# define as_string NULL
4429#else
4430 char *as_string = NULL;
4431#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004432 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004433 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004434 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004435 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004436
4437 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004438#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004439 if (ch == '(' && !ctx->word.has_quoted_part) {
4440 if (ctx->word.length)
4441 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004442 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004443 if (!command->argv)
4444 goto skip; /* (... */
4445 if (command->argv[1]) { /* word word ... (... */
4446 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004447 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004448 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004449 /* it is "word(..." or "word (..." */
4450 do
4451 ch = i_getch(input);
4452 while (ch == ' ' || ch == '\t');
4453 if (ch != ')') {
4454 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004455 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004456 }
4457 nommu_addchr(&ctx->as_string, ch);
4458 do
4459 ch = i_getch(input);
4460 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004461 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004462 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004463 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004464 }
4465 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004466 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004467 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004468 }
4469#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004470
4471#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004472 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004473 || ctx->word.length /* word{... */
4474 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004475 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004476 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004477 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004478 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004479 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004480 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004481#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004482
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004483 IF_HUSH_FUNCTIONS(skip:)
4484
Denis Vlasenko240c2552009-04-03 03:45:05 +00004485 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004486 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004487 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004488 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4489 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004490 } else {
4491 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004492 ch = i_peek(input);
4493 if (ch != ' ' && ch != '\t' && ch != '\n'
4494 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4495 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004496 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004497 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004498 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004499 if (ch != '(') {
4500 ch = i_getch(input);
4501 nommu_addchr(&ctx->as_string, ch);
4502 }
Eric Andersen25f27032001-04-26 23:22:31 +00004503 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004504
Denys Vlasenko474cb202018-07-24 13:03:03 +02004505 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4506 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4507 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004508#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004509 if (as_string)
4510 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004511#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004512
4513 /* empty ()/{} or parse error? */
4514 if (!pipe_list || pipe_list == ERR_PTR) {
4515 /* parse_stream already emitted error msg */
4516 if (!BB_MMU)
4517 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004518 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004519 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004520 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004521 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004522#if !BB_MMU
4523 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4524 command->group_as_string = as_string;
4525 debug_printf_parse("end of group, remembering as:'%s'\n",
4526 command->group_as_string);
4527#endif
4528
4529#if ENABLE_HUSH_FUNCTIONS
4530 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4531 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4532 struct command *cmd2;
4533
4534 cmd2 = xzalloc(sizeof(*cmd2));
4535 cmd2->cmd_type = CMD_SUBSHELL;
4536 cmd2->group = pipe_list;
4537# if !BB_MMU
4538//UNTESTED!
4539 cmd2->group_as_string = command->group_as_string;
4540 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4541# endif
4542
4543 pipe_list = new_pipe();
4544 pipe_list->cmds = cmd2;
4545 pipe_list->num_cmds = 1;
4546 }
4547#endif
4548
4549 command->group = pipe_list;
4550
Denys Vlasenko474cb202018-07-24 13:03:03 +02004551 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4552 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004553 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004554#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004555}
4556
Denys Vlasenko0b883582016-12-23 16:49:07 +01004557#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004558/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004559/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004560static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004561{
4562 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004563 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004564 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004565 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004566 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004567 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004568 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004569 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004570 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004571 }
4572}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004573static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4574{
4575 while (1) {
4576 int ch = i_getch(input);
4577 if (ch == EOF) {
4578 syntax_error_unterm_ch('\'');
4579 return 0;
4580 }
4581 if (ch == '\'')
4582 return 1;
4583 o_addqchr(dest, ch);
4584 }
4585}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004586/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004587static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004588static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004589{
4590 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004591 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004592 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004593 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004594 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004595 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004596 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004597 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004598 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004599 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004600 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004601 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004602 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004603 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004604 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4605 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004606 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004607 continue;
4608 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004609 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004610 }
4611}
4612/* Process `cmd` - copy contents until "`" is seen. Complicated by
4613 * \` quoting.
4614 * "Within the backquoted style of command substitution, backslash
4615 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4616 * The search for the matching backquote shall be satisfied by the first
4617 * backquote found without a preceding backslash; during this search,
4618 * if a non-escaped backquote is encountered within a shell comment,
4619 * a here-document, an embedded command substitution of the $(command)
4620 * form, or a quoted string, undefined results occur. A single-quoted
4621 * or double-quoted string that begins, but does not end, within the
4622 * "`...`" sequence produces undefined results."
4623 * Example Output
4624 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4625 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004626static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004627{
4628 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004629 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004630 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004631 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004632 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004633 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4634 ch = i_getch(input);
4635 if (ch != '`'
4636 && ch != '$'
4637 && ch != '\\'
4638 && (!in_dquote || ch != '"')
4639 ) {
4640 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004641 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004642 }
4643 if (ch == EOF) {
4644 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004645 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004646 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004647 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004648 }
4649}
4650/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4651 * quoting and nested ()s.
4652 * "With the $(command) style of command substitution, all characters
4653 * following the open parenthesis to the matching closing parenthesis
4654 * constitute the command. Any valid shell script can be used for command,
4655 * except a script consisting solely of redirections which produces
4656 * unspecified results."
4657 * Example Output
4658 * echo $(echo '(TEST)' BEST) (TEST) BEST
4659 * echo $(echo 'TEST)' BEST) TEST) BEST
4660 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004661 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004662 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004663 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004664 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4665 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004666 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004667#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004668static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004669{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004670 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004671 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004672# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004673 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004674# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004675 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4676
Denys Vlasenko817a2022018-06-26 15:35:17 +02004677#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004678 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004679#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004680 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4681
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004682 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004683 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004684 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004685 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004686 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004687 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004688 if (ch == end_ch
4689# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004690 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004691# endif
4692 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004693 if (!dbl)
4694 break;
4695 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004696 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004697 i_getch(input); /* eat second ')' */
4698 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004699 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004700 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004701 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004702 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004703 if (ch == '(' || ch == '{') {
4704 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004705 if (!add_till_closing_bracket(dest, input, ch))
4706 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004707 o_addchr(dest, ch);
4708 continue;
4709 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004710 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004711 if (!add_till_single_quote(dest, input))
4712 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004713 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004714 continue;
4715 }
4716 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004717 if (!add_till_double_quote(dest, input))
4718 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004719 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004720 continue;
4721 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004722 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004723 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4724 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004725 o_addchr(dest, ch);
4726 continue;
4727 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004728 if (ch == '\\') {
4729 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004730 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004731 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004732 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004733 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004734 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004735#if 0
4736 if (ch == '\n') {
4737 /* "backslash+newline", ignore both */
4738 o_delchr(dest); /* undo insertion of '\' */
4739 continue;
4740 }
4741#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004742 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004743 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004744 continue;
4745 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004746 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004747 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004748 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004749}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004750#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004751
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004752/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004753#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004754#define parse_dollar(as_string, dest, input, quote_mask) \
4755 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004756#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004757#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004758static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004759 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004760 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004761{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004762 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004763
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004764 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004765 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004766 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004767 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004768 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004769 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004770 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004771 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004772 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004773 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004774 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004775 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004776 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004777 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004778 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004779 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004780 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004781 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004782 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004783 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004784 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004785 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004786 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004787 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004788 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004789 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004790 o_addchr(dest, ch | quote_mask);
4791 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004792 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004793 case '$': /* pid */
4794 case '!': /* last bg pid */
4795 case '?': /* last exit code */
4796 case '#': /* number of args */
4797 case '*': /* args */
4798 case '@': /* args */
4799 goto make_one_char_var;
4800 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004801 char len_single_ch;
4802
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004803 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4804
Denys Vlasenko74369502010-05-21 19:52:01 +02004805 ch = i_getch(input); /* eat '{' */
4806 nommu_addchr(as_string, ch);
4807
Denys Vlasenko46e64982016-09-29 19:50:55 +02004808 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004809 /* It should be ${?}, or ${#var},
4810 * or even ${?+subst} - operator acting on a special variable,
4811 * or the beginning of variable name.
4812 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004813 if (ch == EOF
4814 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4815 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004816 bad_dollar_syntax:
4817 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004818 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4819 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004820 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004821 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004822 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004823 ch |= quote_mask;
4824
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004825 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004826 * However, this regresses some of our testsuite cases
4827 * which check invalid constructs like ${%}.
4828 * Oh well... let's check that the var name part is fine... */
4829
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004830 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004831 unsigned pos;
4832
Denys Vlasenko74369502010-05-21 19:52:01 +02004833 o_addchr(dest, ch);
4834 debug_printf_parse(": '%c'\n", ch);
4835
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004836 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004837 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004838 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004839 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004840
Denys Vlasenko74369502010-05-21 19:52:01 +02004841 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004842 unsigned end_ch;
4843 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004844 /* handle parameter expansions
4845 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4846 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004847 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4848 if (len_single_ch != '#'
4849 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4850 || i_peek(input) != '}'
4851 ) {
4852 goto bad_dollar_syntax;
4853 }
4854 /* else: it's "length of C" ${#C} op,
4855 * where C is a single char
4856 * special var name, e.g. ${#!}.
4857 */
4858 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004859 /* Eat everything until closing '}' (or ':') */
4860 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004861 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004862 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004863 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004864 ) {
4865 /* It's ${var:N[:M]} thing */
4866 end_ch = '}' * 0x100 + ':';
4867 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004868 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004869 && ch == '/'
4870 ) {
4871 /* It's ${var/[/]pattern[/repl]} thing */
4872 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4873 i_getch(input);
4874 nommu_addchr(as_string, '/');
4875 ch = '\\';
4876 }
4877 end_ch = '}' * 0x100 + '/';
4878 }
4879 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004880 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004881 if (!BB_MMU)
4882 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004883#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004884 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004885 if (last_ch == 0) /* error? */
4886 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004887#else
4888#error Simple code to only allow ${var} is not implemented
4889#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004890 if (as_string) {
4891 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004892 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004893 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004894
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004895 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4896 && (end_ch & 0xff00)
4897 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004898 /* close the first block: */
4899 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004900 /* while parsing N from ${var:N[:M]}
4901 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004902 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004903 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004904 end_ch = '}';
4905 goto again;
4906 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004907 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004908 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004909 /* it's ${var:N} - emulate :999999999 */
4910 o_addstr(dest, "999999999");
4911 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004912 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004913 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004914 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004915 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004916 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004917 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4918 break;
4919 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004920#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004921 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004922 unsigned pos;
4923
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004924 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004925 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004926# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004927 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004928 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004929 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004930 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4931 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004932 if (!BB_MMU)
4933 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004934 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4935 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004936 if (as_string) {
4937 o_addstr(as_string, dest->data + pos);
4938 o_addchr(as_string, ')');
4939 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004940 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004941 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004942 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004943 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004944# endif
4945# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004946 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4947 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004948 if (!BB_MMU)
4949 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004950 if (!add_till_closing_bracket(dest, input, ')'))
4951 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004952 if (as_string) {
4953 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004954 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004955 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004956 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004957# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004958 break;
4959 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004960#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004961 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004962 goto make_var;
4963#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004964 /* TODO: $_ and $-: */
4965 /* $_ Shell or shell script name; or last argument of last command
4966 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4967 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004968 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004969 ch = i_getch(input);
4970 nommu_addchr(as_string, ch);
4971 ch = i_peek_and_eat_bkslash_nl(input);
4972 if (isalnum(ch)) { /* it's $_name or $_123 */
4973 ch = '_';
4974 goto make_var1;
4975 }
4976 /* else: it's $_ */
4977#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004978 default:
4979 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004980 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004981 debug_printf_parse("parse_dollar return 1 (ok)\n");
4982 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004983#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004984}
4985
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004986#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02004987#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004988 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004989#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004990#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004991static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004992 o_string *dest,
4993 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02004994 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004995{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004996 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004997 int next;
4998
4999 again:
5000 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005001 if (ch != EOF)
5002 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005003 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005004 debug_printf_parse("encode_string return 1 (ok)\n");
5005 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005006 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005007 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005008 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005009 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005010 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005011 }
5012 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005013 if (ch != '\n') {
5014 next = i_peek(input);
5015 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005016 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005017 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005018 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005019 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005020 /* Testcase: in interactive shell a file with
5021 * echo "unterminated string\<eof>
5022 * is sourced.
5023 */
5024 syntax_error_unterm_ch('"');
5025 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005026 }
5027 /* bash:
5028 * "The backslash retains its special meaning [in "..."]
5029 * only when followed by one of the following characters:
5030 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005031 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005032 * NB: in (unquoted) heredoc, above does not apply to ",
5033 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005034 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005035 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005036 ch = i_getch(input); /* eat next */
5037 if (ch == '\n')
5038 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005039 } /* else: ch remains == '\\', and we double it below: */
5040 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005041 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005042 goto again;
5043 }
5044 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005045 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5046 debug_printf_parse("encode_string return 0: "
5047 "parse_dollar returned 0 (error)\n");
5048 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005049 }
5050 goto again;
5051 }
5052#if ENABLE_HUSH_TICK
5053 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005054 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005055 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5056 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005057 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5058 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005059 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5060 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005061 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005062 }
5063#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005064 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005065 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005066#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005067}
5068
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005069/*
5070 * Scan input until EOF or end_trigger char.
5071 * Return a list of pipes to execute, or NULL on EOF
5072 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005073 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005074 * reset parsing machinery and start parsing anew,
5075 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005076 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005077static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005078 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005079 struct in_str *input,
5080 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005081{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005082 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005083 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005084
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005085 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005086 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005087 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005088 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005089 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005090 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005091
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005092 initialize_context(&ctx);
5093
5094 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5095 * Preventing this:
5096 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005097 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005098
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005099 /* We used to separate words on $IFS here. This was wrong.
5100 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005101 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005102 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005103
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005104 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005105 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005106 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005107 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005108 int ch;
5109 int next;
5110 int redir_fd;
5111 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005112
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005113 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005114 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005115 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005116 if (ch == EOF) {
5117 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005118
5119 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005120 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005121 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005122 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005123 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005124 syntax_error_unterm_ch('(');
5125 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005126 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005127 if (end_trigger == '}') {
5128 syntax_error_unterm_ch('{');
5129 goto parse_error;
5130 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005131
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005132 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005133 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005134 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005135 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005136 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005137 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005138 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005139 /* (this makes bare "&" cmd a no-op.
5140 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005141 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005142 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005143 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005144 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005145 pi = NULL;
5146 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005147#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005148 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005149 if (pstring)
5150 *pstring = ctx.as_string.data;
5151 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005152 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005153#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005154 // heredoc_cnt must be 0 here anyway
5155 //if (heredoc_cnt_ptr)
5156 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005157 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005158 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005159 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005160 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005161 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005162
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005163 /* Handle "'" and "\" first, as they won't play nice with
5164 * i_peek_and_eat_bkslash_nl() anyway:
5165 * echo z\\
5166 * and
5167 * echo '\
5168 * '
5169 * would break.
5170 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005171 if (ch == '\\') {
5172 ch = i_getch(input);
5173 if (ch == '\n')
5174 continue; /* drop \<newline>, get next char */
5175 nommu_addchr(&ctx.as_string, '\\');
5176 o_addchr(&ctx.word, '\\');
5177 if (ch == EOF) {
5178 /* Testcase: eval 'echo Ok\' */
5179 /* bash-4.3.43 was removing backslash,
5180 * but 4.4.19 retains it, most other shells too
5181 */
5182 continue; /* get next char */
5183 }
5184 /* Example: echo Hello \2>file
5185 * we need to know that word 2 is quoted
5186 */
5187 ctx.word.has_quoted_part = 1;
5188 nommu_addchr(&ctx.as_string, ch);
5189 o_addchr(&ctx.word, ch);
5190 continue; /* get next char */
5191 }
5192 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005193 if (ch == '\'') {
5194 ctx.word.has_quoted_part = 1;
5195 next = i_getch(input);
5196 if (next == '\'' && !ctx.pending_redirect)
5197 goto insert_empty_quoted_str_marker;
5198
5199 ch = next;
5200 while (1) {
5201 if (ch == EOF) {
5202 syntax_error_unterm_ch('\'');
5203 goto parse_error;
5204 }
5205 nommu_addchr(&ctx.as_string, ch);
5206 if (ch == '\'')
5207 break;
5208 if (ch == SPECIAL_VAR_SYMBOL) {
5209 /* Convert raw ^C to corresponding special variable reference */
5210 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5211 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5212 }
5213 o_addqchr(&ctx.word, ch);
5214 ch = i_getch(input);
5215 }
5216 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005217 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005218
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005219 next = '\0';
5220 if (ch != '\n')
5221 next = i_peek_and_eat_bkslash_nl(input);
5222
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005223 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005224 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005225 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005226 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005227 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005228 || ctx.word.length /* word{... - non-special */
5229 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005230 || (next != ';' /* }; - special */
5231 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005232 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005233 && next != '&' /* }& and }&& ... - special */
5234 && next != '|' /* }|| ... - special */
5235 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005236 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005237 ) {
5238 /* They are not special, skip "{}" */
5239 is_special += 2;
5240 }
5241 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005242 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005243
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005244 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005245 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005246 o_addQchr(&ctx.word, ch);
5247 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5248 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005249 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005250 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005251 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005252 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5253 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005254 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005255 continue;
5256 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005257
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005258 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005259#if ENABLE_HUSH_LINENO_VAR
5260/* Case:
5261 * "while ...; do<whitespace><newline>
5262 * cmd ..."
5263 * would think that "cmd" starts in <whitespace> -
5264 * i.e., at the previous line.
5265 * We need to skip all whitespace before newlines.
5266 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005267 while (ch != '\n') {
5268 next = i_peek(input);
5269 if (next != ' ' && next != '\t' && next != '\n')
5270 break; /* next char is not ws */
5271 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005272 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005273 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005274#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005275 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005276 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005277 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005278 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005279 /* Is this a case when newline is simply ignored?
5280 * Some examples:
5281 * "cmd | <newline> cmd ..."
5282 * "case ... in <newline> word) ..."
5283 */
5284 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005285 && ctx.word.length == 0
5286 && !ctx.word.has_quoted_part
5287 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005288 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005289 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005290 * Without check #1, interactive shell
5291 * ignores even bare <newline>,
5292 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005293 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005294 * ps2> _ <=== wrong, should be ps1
5295 * Without check #2, "cmd & <newline>"
5296 * is similarly mistreated.
5297 * (BTW, this makes "cmd & cmd"
5298 * and "cmd && cmd" non-orthogonal.
5299 * Really, ask yourself, why
5300 * "cmd && <newline>" doesn't start
5301 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005302 * The only reason is that it might be
5303 * a "cmd1 && <nl> cmd2 &" construct,
5304 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005305 */
5306 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005307 if (pi->num_cmds != 0 /* check #1 */
5308 && pi->followup != PIPE_BG /* check #2 */
5309 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005310 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005311 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005312 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005313 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005314 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005315 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005316 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005317 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5318 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005319 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005320 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005321 ctx.is_assignment = MAYBE_ASSIGNMENT;
5322 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005323 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005324 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005325 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005326 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005327 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005328
5329 /* "cmd}" or "cmd }..." without semicolon or &:
5330 * } is an ordinary char in this case, even inside { cmd; }
5331 * Pathological example: { ""}; } should exec "}" cmd
5332 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005333 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005334 if (ctx.word.length != 0 /* word} */
5335 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005336 ) {
5337 goto ordinary_char;
5338 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005339 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5340 /* Generally, there should be semicolon: "cmd; }"
5341 * However, bash allows to omit it if "cmd" is
5342 * a group. Examples:
5343 * { { echo 1; } }
5344 * {(echo 1)}
5345 * { echo 0 >&2 | { echo 1; } }
5346 * { while false; do :; done }
5347 * { case a in b) ;; esac }
5348 */
5349 if (ctx.command->group)
5350 goto term_group;
5351 goto ordinary_char;
5352 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005353 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005354 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005355 goto skip_end_trigger;
5356 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005357 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005358 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005359 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005360 && (ch != ';' || heredoc_cnt == 0)
5361#if ENABLE_HUSH_CASE
5362 && (ch != ')'
5363 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005364 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005365 )
5366#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005367 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005368 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005369 goto parse_error;
5370 }
5371 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005372 ctx.is_assignment = MAYBE_ASSIGNMENT;
5373 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005374 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005375 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005376 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005377 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005378 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005379#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005380 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005381 if (pstring)
5382 *pstring = ctx.as_string.data;
5383 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005384 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005385#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005386 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5387 /* Example: bare "{ }", "()" */
5388 G.last_exitcode = 2; /* bash compat */
5389 syntax_error_unexpected_ch(ch);
5390 goto parse_error2;
5391 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005392 if (heredoc_cnt_ptr)
5393 *heredoc_cnt_ptr = heredoc_cnt;
5394 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005395 debug_printf_parse("parse_stream return %p: "
5396 "end_trigger char found\n",
5397 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005398 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005399 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005400 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005401 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005402
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005403 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005404 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005405
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005406 /* Catch <, > before deciding whether this word is
5407 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5408 switch (ch) {
5409 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005410 redir_fd = redirect_opt_num(&ctx.word);
5411 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005412 goto parse_error;
5413 }
5414 redir_style = REDIRECT_OVERWRITE;
5415 if (next == '>') {
5416 redir_style = REDIRECT_APPEND;
5417 ch = i_getch(input);
5418 nommu_addchr(&ctx.as_string, ch);
5419 }
5420#if 0
5421 else if (next == '(') {
5422 syntax_error(">(process) not supported");
5423 goto parse_error;
5424 }
5425#endif
5426 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5427 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005428 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005429 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005430 redir_fd = redirect_opt_num(&ctx.word);
5431 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005432 goto parse_error;
5433 }
5434 redir_style = REDIRECT_INPUT;
5435 if (next == '<') {
5436 redir_style = REDIRECT_HEREDOC;
5437 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005438 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005439 ch = i_getch(input);
5440 nommu_addchr(&ctx.as_string, ch);
5441 } else if (next == '>') {
5442 redir_style = REDIRECT_IO;
5443 ch = i_getch(input);
5444 nommu_addchr(&ctx.as_string, ch);
5445 }
5446#if 0
5447 else if (next == '(') {
5448 syntax_error("<(process) not supported");
5449 goto parse_error;
5450 }
5451#endif
5452 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5453 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005454 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005455 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005456 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005457 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005458 /* note: we do not add it to &ctx.as_string */
5459/* TODO: in bash:
5460 * comment inside $() goes to the next \n, even inside quoted string (!):
5461 * cmd "$(cmd2 #comment)" - syntax error
5462 * cmd "`cmd2 #comment`" - ok
5463 * We accept both (comment ends where command subst ends, in both cases).
5464 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005465 while (1) {
5466 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005467 if (ch == '\n') {
5468 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005469 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005470 }
5471 ch = i_getch(input);
5472 if (ch == EOF)
5473 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005474 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005475 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005476 }
5477 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005478 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005479 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005480
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005481 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005482 /* check that we are not in word in "a=1 2>word b=1": */
5483 && !ctx.pending_redirect
5484 ) {
5485 /* ch is a special char and thus this word
5486 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005487 ctx.is_assignment = NOT_ASSIGNMENT;
5488 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005489 }
5490
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005491 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5492
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005493 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005494 case SPECIAL_VAR_SYMBOL:
5495 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005496 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5497 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005498 /* fall through */
5499 case '#':
5500 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005501 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005502 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005503 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005504 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005505 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005506 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005507 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005508 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005509 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005510 case '"':
5511 ctx.word.has_quoted_part = 1;
5512 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005513 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005514 insert_empty_quoted_str_marker:
5515 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005516 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5517 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005518 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005519 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005520 if (ctx.is_assignment == NOT_ASSIGNMENT)
5521 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005522 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005523 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005524 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005525 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005526#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005527 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005528 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005529
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005530 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5531 o_addchr(&ctx.word, '`');
5532 USE_FOR_NOMMU(pos = ctx.word.length;)
5533 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005534 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005535# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005536 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005537 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005538# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005539 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5540 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005541 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005542 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005543#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005544 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005545#if ENABLE_HUSH_CASE
5546 case_semi:
5547#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005548 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005549 goto parse_error;
5550 }
5551 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005552#if ENABLE_HUSH_CASE
5553 /* Eat multiple semicolons, detect
5554 * whether it means something special */
5555 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005556 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005557 if (ch != ';')
5558 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005559 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005560 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005561 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005562 ctx.ctx_dsemicolon = 1;
5563 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005564 break;
5565 }
5566 }
5567#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005568 new_cmd:
5569 /* We just finished a cmd. New one may start
5570 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005571 ctx.is_assignment = MAYBE_ASSIGNMENT;
5572 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005573 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005574 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005575 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005576 goto parse_error;
5577 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005578 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005579 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005580 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005581 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005582 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005583 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005584 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005585 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005586 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005587 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005588 goto parse_error;
5589 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005590#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005591 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005592 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005593#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005594 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005595 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005596 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005597 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005598 } else {
5599 /* we could pick up a file descriptor choice here
5600 * with redirect_opt_num(), but bash doesn't do it.
5601 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005602 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005603 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005604 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005605 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005606#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005607 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005608 if (ctx.ctx_res_w == RES_MATCH
5609 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005610 && ctx.word.length == 0 /* not word(... */
5611 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005612 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005613 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005614 }
5615#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005616 /* fall through */
5617 case '{': {
5618 int n = parse_group(&ctx, input, ch);
5619 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005620 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005621 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005622 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5623 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005624 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005625 }
Eric Andersen25f27032001-04-26 23:22:31 +00005626 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005627#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005628 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005629 goto case_semi;
5630#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005631
Eric Andersen25f27032001-04-26 23:22:31 +00005632 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005633 /* proper use of this character is caught by end_trigger:
5634 * if we see {, we call parse_group(..., end_trigger='}')
5635 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005636 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005637 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005638 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005639 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005640 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005641 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005642 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005643 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005644
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005645 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005646 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005647 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005648 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005649 struct parse_context *pctx;
5650 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005651
5652 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005653 * Sample for finding leaks on syntax error recovery path.
5654 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005655 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005656 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005657 * while if (true | { true;}); then echo ok; fi; do break; done
5658 * 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 +00005659 */
5660 pctx = &ctx;
5661 do {
5662 /* Update pipe/command counts,
5663 * otherwise freeing may miss some */
5664 done_pipe(pctx, PIPE_SEQ);
5665 debug_printf_clean("freeing list %p from ctx %p\n",
5666 pctx->list_head, pctx);
5667 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005668 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005669 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005670#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005671 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005672#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005673 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005674 if (pctx != &ctx) {
5675 free(pctx);
5676 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005677 IF_HAS_KEYWORDS(pctx = p2;)
5678 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005679
Denys Vlasenko474cb202018-07-24 13:03:03 +02005680 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005681#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005682 if (pstring)
5683 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005684#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005685 debug_leave();
5686 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005687 }
Eric Andersen25f27032001-04-26 23:22:31 +00005688}
5689
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005690
5691/*** Execution routines ***/
5692
5693/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005694#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005695#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005696 expand_string_to_string(str)
5697#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005698static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005699#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005700static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005701#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005702static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005703
5704/* expand_strvec_to_strvec() takes a list of strings, expands
5705 * all variable references within and returns a pointer to
5706 * a list of expanded strings, possibly with larger number
5707 * of strings. (Think VAR="a b"; echo $VAR).
5708 * This new list is allocated as a single malloc block.
5709 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005710 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005711 * Caller can deallocate entire list by single free(list). */
5712
Denys Vlasenko238081f2010-10-03 14:26:26 +02005713/* A horde of its helpers come first: */
5714
5715static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5716{
5717 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005718 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005719
Denys Vlasenko9e800222010-10-03 14:28:04 +02005720#if ENABLE_HUSH_BRACE_EXPANSION
5721 if (c == '{' || c == '}') {
5722 /* { -> \{, } -> \} */
5723 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005724 /* And now we want to add { or } and continue:
5725 * o_addchr(o, c);
5726 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005727 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005728 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005729 }
5730#endif
5731 o_addchr(o, c);
5732 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005733 /* \z -> \\\z; \<eol> -> \\<eol> */
5734 o_addchr(o, '\\');
5735 if (len) {
5736 len--;
5737 o_addchr(o, '\\');
5738 o_addchr(o, *str++);
5739 }
5740 }
5741 }
5742}
5743
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005744/* Store given string, finalizing the word and starting new one whenever
5745 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005746 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005747 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005748 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5749 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005750static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005751{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005752 int last_is_ifs = 0;
5753
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005754 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005755 int word_len;
5756
5757 if (!*str) /* EOL - do not finalize word */
5758 break;
5759 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005760 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005761 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005762 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005763 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005764 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005765 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005766 * Example: "v='\*'; echo b$v" prints "b\*"
5767 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005768 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005769 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005770 /*/ Why can't we do it easier? */
5771 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5772 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5773 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005774 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005775 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005776 if (!*str) /* EOL - do not finalize word */
5777 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005778 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005779
5780 /* We know str here points to at least one IFS char */
5781 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005782 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005783 if (!*str) /* EOL - do not finalize word */
5784 break;
5785
Denys Vlasenko96786362018-04-11 16:02:58 +02005786 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5787 && strchr(G.ifs, *str) /* the second check would fail */
5788 ) {
5789 /* This is a non-whitespace $IFS char */
5790 /* Skip it and IFS whitespace chars, start new word */
5791 str++;
5792 str += strspn(str, G.ifs_whitespace);
5793 goto new_word;
5794 }
5795
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005796 /* Start new word... but not always! */
5797 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005798 if (output->has_quoted_part
5799 /* Case "v=' a'; echo $v":
5800 * here nothing precedes the space in $v expansion,
5801 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005802 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005803 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005804 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005805 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005806 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005807 o_addchr(output, '\0');
5808 debug_print_list("expand_on_ifs", output, n);
5809 n = o_save_ptr(output, n);
5810 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005811 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005812
Denys Vlasenko168579a2018-07-19 13:45:54 +02005813 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005814 debug_print_list("expand_on_ifs[1]", output, n);
5815 return n;
5816}
5817
5818/* Helper to expand $((...)) and heredoc body. These act as if
5819 * they are in double quotes, with the exception that they are not :).
5820 * Just the rules are similar: "expand only $var and `cmd`"
5821 *
5822 * Returns malloced string.
5823 * As an optimization, we return NULL if expansion is not needed.
5824 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005825static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005826{
5827 char *exp_str;
5828 struct in_str input;
5829 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005830 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005831
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005832 cp = str;
5833 for (;;) {
5834 if (!*cp) return NULL; /* string has no special chars */
5835 if (*cp == '$') break;
5836 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005837#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005838 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005839#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005840 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005841 }
5842
5843 /* We need to expand. Example:
5844 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5845 */
5846 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005847 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005848//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005849 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005850 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005851 EXP_FLAG_ESC_GLOB_CHARS,
5852 /*unbackslash:*/ 1
5853 );
5854 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005855 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005856 return exp_str;
5857}
5858
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005859/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5860 * These can contain single- and double-quoted strings,
5861 * and treated as if the ARG string is initially unquoted. IOW:
5862 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5863 * a dquoted string: "${var#"zz"}"), the difference only comes later
5864 * (word splitting and globbing of the ${var...} result).
5865 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005866#if !BASH_PATTERN_SUBST
5867#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5868 encode_then_expand_vararg(str, handle_squotes)
5869#endif
5870static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5871{
5872#if !BASH_PATTERN_SUBST
5873 const int do_unbackslash = 0;
5874#endif
5875 char *exp_str;
5876 struct in_str input;
5877 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005878 const char *cp;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005879
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005880 cp = str;
5881 for (;;) {
5882 if (!*cp) return NULL; /* string has no special chars */
5883 if (*cp == '$') break;
5884 if (*cp == '\\') break;
5885 if (*cp == '\'') break;
5886 if (*cp == '"') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005887#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005888 if (*cp == '`') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005889#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005890 cp++;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005891 }
5892
Denys Vlasenkob762c782018-07-17 14:21:38 +02005893 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005894 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005895 exp_str = NULL;
5896
5897 for (;;) {
5898 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005899
5900 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005901 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5902 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005903
5904 if (!dest.o_expflags) {
5905 if (ch == EOF)
5906 break;
5907 if (handle_squotes && ch == '\'') {
5908 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02005909 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005910 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005911 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005912 }
5913 if (ch == EOF) {
5914 syntax_error_unterm_ch('"');
5915 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005916 }
5917 if (ch == '"') {
5918 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5919 continue;
5920 }
5921 if (ch == '\\') {
5922 ch = i_getch(&input);
5923 if (ch == EOF) {
5924//example? error message? syntax_error_unterm_ch('"');
5925 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5926 goto ret;
5927 }
5928 o_addqchr(&dest, ch);
5929 continue;
5930 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02005931 if (ch == '$') {
5932 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5933 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5934 goto ret;
5935 }
5936 continue;
5937 }
5938#if ENABLE_HUSH_TICK
5939 if (ch == '`') {
5940 //unsigned pos = dest->length;
5941 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5942 o_addchr(&dest, 0x80 | '`');
5943 if (!add_till_backquote(&dest, &input,
5944 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5945 )
5946 ) {
5947 goto ret; /* error */
5948 }
5949 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5950 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5951 continue;
5952 }
5953#endif
5954 o_addQchr(&dest, ch);
5955 } /* for (;;) */
5956
5957 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5958 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02005959 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5960 do_unbackslash
5961 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02005962 ret:
5963 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005964 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005965 return exp_str;
5966}
5967
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005968/* Expanding ARG in ${var+ARG}, ${var-ARG}
5969 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02005970static int encode_then_append_var_plusminus(o_string *output, int n,
5971 const char *str, int dquoted)
5972{
5973 struct in_str input;
5974 o_string dest = NULL_O_STRING;
5975
5976#if 0 //todo?
5977 const char *cp;
5978 cp = str;
5979 for (;;) {
5980 if (!*cp) return NULL; /* string has no special chars */
5981 if (*cp == '$') break;
5982 if (*cp == '\\') break;
5983 if (*cp == '\'') break;
5984 if (*cp == '"') break;
5985#if ENABLE_HUSH_TICK
5986 if (*cp == '`') break;
5987#endif
5988 cp++;
5989 }
5990#endif
5991
Denys Vlasenko294eb462018-07-20 16:18:59 +02005992 setup_string_in_str(&input, str);
5993
5994 for (;;) {
5995 int ch;
5996
5997 ch = i_getch(&input);
5998 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
5999 __func__, ch, ch, dest.o_expflags);
6000
6001 if (!dest.o_expflags) {
6002 if (ch == EOF)
6003 break;
6004 if (!dquoted && strchr(G.ifs, ch)) {
6005 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6006 * do not assume we are at the start of the word (PREFIX above).
6007 */
6008 if (dest.data) {
6009 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006010 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006011 o_addchr(output, '\0');
6012 n = o_save_ptr(output, n); /* create next word */
6013 } else
6014 if (output->length != o_get_last_ptr(output, n)
6015 || output->has_quoted_part
6016 ) {
6017 /* For these cases:
6018 * f() { for i; do echo "|$i|"; done; }; x=x
6019 * f a${x:+ }b # 1st condition
6020 * |a|
6021 * |b|
6022 * f ""${x:+ }b # 2nd condition
6023 * ||
6024 * |b|
6025 */
6026 o_addchr(output, '\0');
6027 n = o_save_ptr(output, n); /* create next word */
6028 }
6029 continue;
6030 }
6031 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006032 if (!add_till_single_quote_dquoted(&dest, &input))
6033 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006034 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6035 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006036 continue;
6037 }
6038 }
6039 if (ch == EOF) {
6040 syntax_error_unterm_ch('"');
6041 goto ret; /* error */
6042 }
6043 if (ch == '"') {
6044 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006045 if (dest.o_expflags) {
6046 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6047 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6048 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006049 continue;
6050 }
6051 if (ch == '\\') {
6052 ch = i_getch(&input);
6053 if (ch == EOF) {
6054//example? error message? syntax_error_unterm_ch('"');
6055 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6056 goto ret;
6057 }
6058 o_addqchr(&dest, ch);
6059 continue;
6060 }
6061 if (ch == '$') {
6062 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6063 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6064 goto ret;
6065 }
6066 continue;
6067 }
6068#if ENABLE_HUSH_TICK
6069 if (ch == '`') {
6070 //unsigned pos = dest->length;
6071 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6072 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6073 if (!add_till_backquote(&dest, &input,
6074 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6075 )
6076 ) {
6077 goto ret; /* error */
6078 }
6079 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6080 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6081 continue;
6082 }
6083#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006084 if (dquoted) {
6085 /* Always glob-protect if in dquotes:
6086 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6087 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6088 */
6089 o_addqchr(&dest, ch);
6090 } else {
6091 /* Glob-protect only if char is quoted:
6092 * x=x; echo ${x:+/bin/c*} - prints many filenames
6093 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6094 */
6095 o_addQchr(&dest, ch);
6096 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006097 } /* for (;;) */
6098
6099 if (dest.data) {
6100 n = expand_vars_to_list(output, n, dest.data);
6101 }
6102 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006103 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006104 return n;
6105}
6106
Denys Vlasenko0b883582016-12-23 16:49:07 +01006107#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006108static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006109{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006110 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006111 arith_t res;
6112 char *exp_str;
6113
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006114 math_state.lookupvar = get_local_var_value;
6115 math_state.setvar = set_local_var_from_halves;
6116 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006117 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006118 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006119 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006120 if (errmsg_p)
6121 *errmsg_p = math_state.errmsg;
6122 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006123 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006124 return res;
6125}
6126#endif
6127
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006128#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006129/* ${var/[/]pattern[/repl]} helpers */
6130static char *strstr_pattern(char *val, const char *pattern, int *size)
6131{
6132 while (1) {
6133 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6134 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6135 if (end) {
6136 *size = end - val;
6137 return val;
6138 }
6139 if (*val == '\0')
6140 return NULL;
6141 /* Optimization: if "*pat" did not match the start of "string",
6142 * we know that "tring", "ring" etc will not match too:
6143 */
6144 if (pattern[0] == '*')
6145 return NULL;
6146 val++;
6147 }
6148}
6149static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6150{
6151 char *result = NULL;
6152 unsigned res_len = 0;
6153 unsigned repl_len = strlen(repl);
6154
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006155 /* Null pattern never matches, including if "var" is empty */
6156 if (!pattern[0])
6157 return result; /* NULL, no replaces happened */
6158
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006159 while (1) {
6160 int size;
6161 char *s = strstr_pattern(val, pattern, &size);
6162 if (!s)
6163 break;
6164
6165 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006166 strcpy(mempcpy(result + res_len, val, s - val), repl);
6167 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006168 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6169
6170 val = s + size;
6171 if (exp_op == '/')
6172 break;
6173 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006174 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006175 result = xrealloc(result, res_len + strlen(val) + 1);
6176 strcpy(result + res_len, val);
6177 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6178 }
6179 debug_printf_varexp("result:'%s'\n", result);
6180 return result;
6181}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006182#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006183
Denys Vlasenko168579a2018-07-19 13:45:54 +02006184static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006185 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006186{
6187 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6188 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6189 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6190 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006191 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006192 } else { /* quoted "$VAR" */
6193 output->has_quoted_part = 1;
6194 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6195 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6196 if (val && val[0])
6197 o_addQstr(output, val);
6198 }
6199 return n;
6200}
6201
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006202/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006203 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006204static NOINLINE int expand_one_var(o_string *output, int n,
6205 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006206{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006207 const char *val;
6208 char *to_be_freed;
6209 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006210 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006211 char exp_op;
6212 char exp_save = exp_save; /* for compiler */
6213 char *exp_saveptr; /* points to expansion operator */
6214 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006215 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006216
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006217 val = NULL;
6218 to_be_freed = NULL;
6219 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006220 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006221 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006222 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006223 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006224 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006225 exp_op = 0;
6226
Denys Vlasenkob762c782018-07-17 14:21:38 +02006227 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006228 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6229 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6230 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006231 ) {
6232 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006233 var++;
6234 exp_op = 'L';
6235 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006236 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006237 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006238 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006239 ) {
6240 /* ${?:0}, ${#[:]%0} etc */
6241 exp_saveptr = var + 1;
6242 } else {
6243 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6244 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6245 }
6246 exp_op = exp_save = *exp_saveptr;
6247 if (exp_op) {
6248 exp_word = exp_saveptr + 1;
6249 if (exp_op == ':') {
6250 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006251//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006252 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006253 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006254 ) {
6255 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6256 exp_op = ':';
6257 exp_word--;
6258 }
6259 }
6260 *exp_saveptr = '\0';
6261 } /* else: it's not an expansion op, but bare ${var} */
6262 }
6263
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006264 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006265 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006266 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006267 int nn = xatoi_positive(var);
6268 if (nn < G.global_argc)
6269 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006270 /* else val remains NULL: $N with too big N */
6271 } else {
6272 switch (var[0]) {
6273 case '$': /* pid */
6274 val = utoa(G.root_pid);
6275 break;
6276 case '!': /* bg pid */
6277 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6278 break;
6279 case '?': /* exitcode */
6280 val = utoa(G.last_exitcode);
6281 break;
6282 case '#': /* argc */
6283 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6284 break;
6285 default:
6286 val = get_local_var_value(var);
6287 }
6288 }
6289
6290 /* Handle any expansions */
6291 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006292 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006293 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006294 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006295 debug_printf_expand("%s\n", val);
6296 } else if (exp_op) {
6297 if (exp_op == '%' || exp_op == '#') {
6298 /* Standard-mandated substring removal ops:
6299 * ${parameter%word} - remove smallest suffix pattern
6300 * ${parameter%%word} - remove largest suffix pattern
6301 * ${parameter#word} - remove smallest prefix pattern
6302 * ${parameter##word} - remove largest prefix pattern
6303 *
6304 * Word is expanded to produce a glob pattern.
6305 * Then var's value is matched to it and matching part removed.
6306 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006307//FIXME: ${x#...${...}...}
6308//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6309//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006310 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006311 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006312 char *exp_exp_word;
6313 char *loc;
6314 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006315 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006316 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006317 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006318 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006319 if (exp_exp_word)
6320 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006321 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6322 /*
6323 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006324 * G.global_argv and results of utoa and get_local_var_value
6325 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006326 * scan_and_match momentarily stores NULs there.
6327 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006328 t = (char*)val;
6329 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006330 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 +02006331 free(exp_exp_word);
6332 if (loc) { /* match was found */
6333 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006334 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006335 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006336 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006337 }
6338 }
6339 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006340#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006341 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006342 /* It's ${var/[/]pattern[/repl]} thing.
6343 * Note that in encoded form it has TWO parts:
6344 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006345 * and if // is used, it is encoded as \:
6346 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006347 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006348 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006349 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006350 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006351 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006352 * >az >bz
6353 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6354 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6355 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6356 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006357 * (note that a*z _pattern_ is never globbed!)
6358 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006359 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006360 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006361 if (!pattern)
6362 pattern = xstrdup(exp_word);
6363 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6364 *p++ = SPECIAL_VAR_SYMBOL;
6365 exp_word = p;
6366 p = strchr(p, SPECIAL_VAR_SYMBOL);
6367 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006368 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006369 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6370 /* HACK ALERT. We depend here on the fact that
6371 * G.global_argv and results of utoa and get_local_var_value
6372 * are actually in writable memory:
6373 * replace_pattern momentarily stores NULs there. */
6374 t = (char*)val;
6375 to_be_freed = replace_pattern(t,
6376 pattern,
6377 (repl ? repl : exp_word),
6378 exp_op);
6379 if (to_be_freed) /* at least one replace happened */
6380 val = to_be_freed;
6381 free(pattern);
6382 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006383 } else {
6384 /* Empty variable always gives nothing */
6385 // "v=''; echo ${v/*/w}" prints "", not "w"
6386 /* Just skip "replace" part */
6387 *p++ = SPECIAL_VAR_SYMBOL;
6388 p = strchr(p, SPECIAL_VAR_SYMBOL);
6389 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006390 }
6391 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006392#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006393 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006394#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006395 /* It's ${var:N[:M]} bashism.
6396 * Note that in encoded form it has TWO parts:
6397 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6398 */
6399 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006400 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006401
Denys Vlasenko063847d2010-09-15 13:33:02 +02006402 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6403 if (errmsg)
6404 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006405 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6406 *p++ = SPECIAL_VAR_SYMBOL;
6407 exp_word = p;
6408 p = strchr(p, SPECIAL_VAR_SYMBOL);
6409 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006410 len = expand_and_evaluate_arith(exp_word, &errmsg);
6411 if (errmsg)
6412 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006413 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006414 if (beg < 0) {
6415 /* negative beg counts from the end */
6416 beg = (arith_t)strlen(val) + beg;
6417 if (beg < 0) /* ${v: -999999} is "" */
6418 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006419 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006420 debug_printf_varexp("from val:'%s'\n", val);
6421 if (len < 0) {
6422 /* in bash, len=-n means strlen()-n */
6423 len = (arith_t)strlen(val) - beg + len;
6424 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006425 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006426 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006427 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006428 arith_err:
6429 val = NULL;
6430 } else {
6431 /* Paranoia. What if user entered 9999999999999
6432 * which fits in arith_t but not int? */
6433 if (len >= INT_MAX)
6434 len = INT_MAX;
6435 val = to_be_freed = xstrndup(val + beg, len);
6436 }
6437 debug_printf_varexp("val:'%s'\n", val);
6438#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006439 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006440 val = NULL;
6441#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006442 } else { /* one of "-=+?" */
6443 /* Standard-mandated substitution ops:
6444 * ${var?word} - indicate error if unset
6445 * If var is unset, word (or a message indicating it is unset
6446 * if word is null) is written to standard error
6447 * and the shell exits with a non-zero exit status.
6448 * Otherwise, the value of var is substituted.
6449 * ${var-word} - use default value
6450 * If var is unset, word is substituted.
6451 * ${var=word} - assign and use default value
6452 * If var is unset, word is assigned to var.
6453 * In all cases, final value of var is substituted.
6454 * ${var+word} - use alternative value
6455 * If var is unset, null is substituted.
6456 * Otherwise, word is substituted.
6457 *
6458 * Word is subjected to tilde expansion, parameter expansion,
6459 * command substitution, and arithmetic expansion.
6460 * If word is not needed, it is not expanded.
6461 *
6462 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6463 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006464 *
6465 * Word-splitting and single quote behavior:
6466 *
6467 * $ f() { for i; do echo "|$i|"; done; };
6468 *
6469 * $ x=; f ${x:?'x y' z}
6470 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6471 * $ x=; f "${x:?'x y' z}"
6472 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6473 *
6474 * $ x=; f ${x:='x y' z}
6475 * |x|
6476 * |y|
6477 * |z|
6478 * $ x=; f "${x:='x y' z}"
6479 * |'x y' z|
6480 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006481 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006482 * |x y|
6483 * |z|
6484 * $ x=x; f "${x:+'x y' z}"
6485 * |'x y' z|
6486 *
6487 * $ x=; f ${x:-'x y' z}
6488 * |x y|
6489 * |z|
6490 * $ x=; f "${x:-'x y' z}"
6491 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006492 */
6493 int use_word = (!val || ((exp_save == ':') && !val[0]));
6494 if (exp_op == '+')
6495 use_word = !use_word;
6496 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6497 (exp_save == ':') ? "true" : "false", use_word);
6498 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006499 if (exp_op == '+' || exp_op == '-') {
6500 /* ${var+word} - use alternative value */
6501 /* ${var-word} - use default value */
6502 n = encode_then_append_var_plusminus(output, n, exp_word,
6503 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006504 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006505 val = NULL;
6506 } else {
6507 /* ${var?word} - indicate error if unset */
6508 /* ${var=word} - assign and use default value */
6509 to_be_freed = encode_then_expand_vararg(exp_word,
6510 /*handle_squotes:*/ !(arg0 & 0x80),
6511 /*unbackslash:*/ 0
6512 );
6513 if (to_be_freed)
6514 exp_word = to_be_freed;
6515 if (exp_op == '?') {
6516 /* mimic bash message */
6517 msg_and_die_if_script("%s: %s",
6518 var,
6519 exp_word[0]
6520 ? exp_word
6521 : "parameter null or not set"
6522 /* ash has more specific messages, a-la: */
6523 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6524 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006525//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006526//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006527// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6528// bash: x: x y z
6529// $
6530// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006531 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006532 val = exp_word;
6533 }
6534 if (exp_op == '=') {
6535 /* ${var=[word]} or ${var:=[word]} */
6536 if (isdigit(var[0]) || var[0] == '#') {
6537 /* mimic bash message */
6538 msg_and_die_if_script("$%s: cannot assign in this way", var);
6539 val = NULL;
6540 } else {
6541 char *new_var = xasprintf("%s=%s", var, val);
6542 set_local_var(new_var, /*flag:*/ 0);
6543 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006544 }
6545 }
6546 }
6547 } /* one of "-=+?" */
6548
6549 *exp_saveptr = exp_save;
6550 } /* if (exp_op) */
6551
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006552 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006553 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006554
Denys Vlasenko168579a2018-07-19 13:45:54 +02006555 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006556
6557 free(to_be_freed);
6558 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006559}
6560
6561/* Expand all variable references in given string, adding words to list[]
6562 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6563 * to be filled). This routine is extremely tricky: has to deal with
6564 * variables/parameters with whitespace, $* and $@, and constructs like
6565 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006566static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006567{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006568 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006569 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006570 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006571 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006572 char *p;
6573
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006574 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6575 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006576 debug_print_list("expand_vars_to_list[0]", output, n);
6577
6578 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6579 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006580#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006581 char arith_buf[sizeof(arith_t)*3 + 2];
6582#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006583
Denys Vlasenko168579a2018-07-19 13:45:54 +02006584 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006585 o_addchr(output, '\0');
6586 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006587 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006588 }
6589
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006590 o_addblock(output, arg, p - arg);
6591 debug_print_list("expand_vars_to_list[1]", output, n);
6592 arg = ++p;
6593 p = strchr(p, SPECIAL_VAR_SYMBOL);
6594
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006595 /* Fetch special var name (if it is indeed one of them)
6596 * and quote bit, force the bit on if singleword expansion -
6597 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006598 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006599
6600 /* Is this variable quoted and thus expansion can't be null?
6601 * "$@" is special. Even if quoted, it can still
6602 * expand to nothing (not even an empty string),
6603 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006604 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006605 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006606
6607 switch (first_ch & 0x7f) {
6608 /* Highest bit in first_ch indicates that var is double-quoted */
6609 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006610 case '@': {
6611 int i;
6612 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006613 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006614 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006615 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006616 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006617 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006618 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006619 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6620 if (G.global_argv[i++][0] && G.global_argv[i]) {
6621 /* this argv[] is not empty and not last:
6622 * put terminating NUL, start new word */
6623 o_addchr(output, '\0');
6624 debug_print_list("expand_vars_to_list[2]", output, n);
6625 n = o_save_ptr(output, n);
6626 debug_print_list("expand_vars_to_list[3]", output, n);
6627 }
6628 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006629 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006630 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006631 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006632 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006633 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006634 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006635 while (1) {
6636 o_addQstr(output, G.global_argv[i]);
6637 if (++i >= G.global_argc)
6638 break;
6639 o_addchr(output, '\0');
6640 debug_print_list("expand_vars_to_list[4]", output, n);
6641 n = o_save_ptr(output, n);
6642 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006643 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006644 while (1) {
6645 o_addQstr(output, G.global_argv[i]);
6646 if (!G.global_argv[++i])
6647 break;
6648 if (G.ifs[0])
6649 o_addchr(output, G.ifs[0]);
6650 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006651 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006652 }
6653 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006654 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006655 case SPECIAL_VAR_SYMBOL: {
6656 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006657 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006658 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006659 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006660 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006661 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006662 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006663 case SPECIAL_VAR_QUOTED_SVS:
6664 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006665 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006666 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006667 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006668 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006669#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006670 case '`': {
6671 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006672 o_string subst_result = NULL_O_STRING;
6673
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006674 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006675 arg++;
6676 /* Can't just stuff it into output o_string,
6677 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006678 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006679 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6680 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006681 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006682 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006683 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006684 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006685 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006686 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006687#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006688#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006689 case '+': {
6690 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006691 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006692
6693 arg++; /* skip '+' */
6694 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6695 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006696 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006697 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6698 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006699 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006700 break;
6701 }
6702#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006703 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006704 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006705 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006706 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006707 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6708
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006709 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6710 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006711 if (*p != SPECIAL_VAR_SYMBOL)
6712 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006713 arg = ++p;
6714 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6715
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006716 if (*arg) {
6717 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006718 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006719 o_addchr(output, '\0');
6720 n = o_save_ptr(output, n);
6721 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006722 debug_print_list("expand_vars_to_list[a]", output, n);
6723 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006724 * if needed (much earlier), do not use o_addQstr here!
6725 */
6726 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006727 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006728 } else
6729 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006730 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6731 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006732 ) {
6733 n--;
6734 /* allow to reuse list[n] later without re-growth */
6735 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006736 }
6737
6738 return n;
6739}
6740
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006741static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006742{
6743 int n;
6744 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006745 o_string output = NULL_O_STRING;
6746
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006747 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006748
6749 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006750 for (;;) {
6751 /* go to next list[n] */
6752 output.ended_in_ifs = 0;
6753 n = o_save_ptr(&output, n);
6754
6755 if (!*argv)
6756 break;
6757
6758 /* expand argv[i] */
6759 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006760 /* if (!output->has_empty_slot) -- need this?? */
6761 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006762 }
6763 debug_print_list("expand_variables", &output, n);
6764
6765 /* output.data (malloced in one block) gets returned in "list" */
6766 list = o_finalize_list(&output, n);
6767 debug_print_strings("expand_variables[1]", list);
6768 return list;
6769}
6770
6771static char **expand_strvec_to_strvec(char **argv)
6772{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006773 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006774}
6775
Denys Vlasenko11752d42018-04-03 08:20:58 +02006776#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006777static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6778{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006779 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006780}
6781#endif
6782
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006783/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006784 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006785 *
6786 * NB: should NOT do globbing!
6787 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6788 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006789static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006790{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006791#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006792 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006793 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006794#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006795 char *argv[2], **list;
6796
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006797 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006798 /* This is generally an optimization, but it also
6799 * handles "", which otherwise trips over !list[0] check below.
6800 * (is this ever happens that we actually get str="" here?)
6801 */
6802 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6803 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006804 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006805 return xstrdup(str);
6806 }
6807
6808 argv[0] = (char*)str;
6809 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006810 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006811 if (!list[0]) {
6812 /* Example where it happens:
6813 * x=; echo ${x:-"$@"}
6814 */
6815 ((char*)list)[0] = '\0';
6816 } else {
6817 if (HUSH_DEBUG)
6818 if (list[1])
6819 bb_error_msg_and_die("BUG in varexp2");
6820 /* actually, just move string 2*sizeof(char*) bytes back */
6821 overlapping_strcpy((char*)list, list[0]);
6822 if (do_unbackslash)
6823 unbackslash((char*)list);
6824 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006825 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006826 return (char*)list;
6827}
6828
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006829#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006830static char* expand_strvec_to_string(char **argv)
6831{
6832 char **list;
6833
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006834 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006835 /* Convert all NULs to spaces */
6836 if (list[0]) {
6837 int n = 1;
6838 while (list[n]) {
6839 if (HUSH_DEBUG)
6840 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6841 bb_error_msg_and_die("BUG in varexp3");
6842 /* bash uses ' ' regardless of $IFS contents */
6843 list[n][-1] = ' ';
6844 n++;
6845 }
6846 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006847 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006848 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6849 return (char*)list;
6850}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006851#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006852
6853static char **expand_assignments(char **argv, int count)
6854{
6855 int i;
6856 char **p;
6857
6858 G.expanded_assignments = p = NULL;
6859 /* Expand assignments into one string each */
6860 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006861 p = add_string_to_strings(p,
6862 expand_string_to_string(argv[i],
6863 EXP_FLAG_ESC_GLOB_CHARS,
6864 /*unbackslash:*/ 1
6865 )
6866 );
6867 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006868 }
6869 G.expanded_assignments = NULL;
6870 return p;
6871}
6872
6873
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006874static void switch_off_special_sigs(unsigned mask)
6875{
6876 unsigned sig = 0;
6877 while ((mask >>= 1) != 0) {
6878 sig++;
6879 if (!(mask & 1))
6880 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006881#if ENABLE_HUSH_TRAP
6882 if (G_traps) {
6883 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006884 /* trap is '', has to remain SIG_IGN */
6885 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006886 free(G_traps[sig]);
6887 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006888 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006889#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006890 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006891 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006892 }
6893}
6894
Denys Vlasenkob347df92011-08-09 22:49:15 +02006895#if BB_MMU
6896/* never called */
6897void re_execute_shell(char ***to_free, const char *s,
6898 char *g_argv0, char **g_argv,
6899 char **builtin_argv) NORETURN;
6900
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006901static void reset_traps_to_defaults(void)
6902{
6903 /* This function is always called in a child shell
6904 * after fork (not vfork, NOMMU doesn't use this function).
6905 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006906 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006907 unsigned mask;
6908
6909 /* Child shells are not interactive.
6910 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6911 * Testcase: (while :; do :; done) + ^Z should background.
6912 * Same goes for SIGTERM, SIGHUP, SIGINT.
6913 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006914 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006915 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006916 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006917
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006918 /* Switch off special sigs */
6919 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006920# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006921 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006922# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006923 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006924 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6925 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006926
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006927# if ENABLE_HUSH_TRAP
6928 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006929 return;
6930
6931 /* Reset all sigs to default except ones with empty traps */
6932 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006933 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006934 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006935 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006936 continue; /* empty trap: has to remain SIG_IGN */
6937 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006938 free(G_traps[sig]);
6939 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006940 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006941 if (sig == 0)
6942 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006943 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006944 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006945# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006946}
6947
6948#else /* !BB_MMU */
6949
6950static void re_execute_shell(char ***to_free, const char *s,
6951 char *g_argv0, char **g_argv,
6952 char **builtin_argv) NORETURN;
6953static void re_execute_shell(char ***to_free, const char *s,
6954 char *g_argv0, char **g_argv,
6955 char **builtin_argv)
6956{
6957# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6958 /* delims + 2 * (number of bytes in printed hex numbers) */
6959 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6960 char *heredoc_argv[4];
6961 struct variable *cur;
6962# if ENABLE_HUSH_FUNCTIONS
6963 struct function *funcp;
6964# endif
6965 char **argv, **pp;
6966 unsigned cnt;
6967 unsigned long long empty_trap_mask;
6968
6969 if (!g_argv0) { /* heredoc */
6970 argv = heredoc_argv;
6971 argv[0] = (char *) G.argv0_for_re_execing;
6972 argv[1] = (char *) "-<";
6973 argv[2] = (char *) s;
6974 argv[3] = NULL;
6975 pp = &argv[3]; /* used as pointer to empty environment */
6976 goto do_exec;
6977 }
6978
6979 cnt = 0;
6980 pp = builtin_argv;
6981 if (pp) while (*pp++)
6982 cnt++;
6983
6984 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006985 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006986 int sig;
6987 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006988 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006989 empty_trap_mask |= 1LL << sig;
6990 }
6991 }
6992
6993 sprintf(param_buf, NOMMU_HACK_FMT
6994 , (unsigned) G.root_pid
6995 , (unsigned) G.root_ppid
6996 , (unsigned) G.last_bg_pid
6997 , (unsigned) G.last_exitcode
6998 , cnt
6999 , empty_trap_mask
7000 IF_HUSH_LOOPS(, G.depth_of_loop)
7001 );
7002# undef NOMMU_HACK_FMT
7003 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7004 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7005 */
7006 cnt += 6;
7007 for (cur = G.top_var; cur; cur = cur->next) {
7008 if (!cur->flg_export || cur->flg_read_only)
7009 cnt += 2;
7010 }
7011# if ENABLE_HUSH_FUNCTIONS
7012 for (funcp = G.top_func; funcp; funcp = funcp->next)
7013 cnt += 3;
7014# endif
7015 pp = g_argv;
7016 while (*pp++)
7017 cnt++;
7018 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7019 *pp++ = (char *) G.argv0_for_re_execing;
7020 *pp++ = param_buf;
7021 for (cur = G.top_var; cur; cur = cur->next) {
7022 if (strcmp(cur->varstr, hush_version_str) == 0)
7023 continue;
7024 if (cur->flg_read_only) {
7025 *pp++ = (char *) "-R";
7026 *pp++ = cur->varstr;
7027 } else if (!cur->flg_export) {
7028 *pp++ = (char *) "-V";
7029 *pp++ = cur->varstr;
7030 }
7031 }
7032# if ENABLE_HUSH_FUNCTIONS
7033 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7034 *pp++ = (char *) "-F";
7035 *pp++ = funcp->name;
7036 *pp++ = funcp->body_as_string;
7037 }
7038# endif
7039 /* We can pass activated traps here. Say, -Tnn:trap_string
7040 *
7041 * However, POSIX says that subshells reset signals with traps
7042 * to SIG_DFL.
7043 * I tested bash-3.2 and it not only does that with true subshells
7044 * of the form ( list ), but with any forked children shells.
7045 * I set trap "echo W" WINCH; and then tried:
7046 *
7047 * { echo 1; sleep 20; echo 2; } &
7048 * while true; do echo 1; sleep 20; echo 2; break; done &
7049 * true | { echo 1; sleep 20; echo 2; } | cat
7050 *
7051 * In all these cases sending SIGWINCH to the child shell
7052 * did not run the trap. If I add trap "echo V" WINCH;
7053 * _inside_ group (just before echo 1), it works.
7054 *
7055 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007056 */
7057 *pp++ = (char *) "-c";
7058 *pp++ = (char *) s;
7059 if (builtin_argv) {
7060 while (*++builtin_argv)
7061 *pp++ = *builtin_argv;
7062 *pp++ = (char *) "";
7063 }
7064 *pp++ = g_argv0;
7065 while (*g_argv)
7066 *pp++ = *g_argv++;
7067 /* *pp = NULL; - is already there */
7068 pp = environ;
7069
7070 do_exec:
7071 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007072 /* Don't propagate SIG_IGN to the child */
7073 if (SPECIAL_JOBSTOP_SIGS != 0)
7074 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007075 execve(bb_busybox_exec_path, argv, pp);
7076 /* Fallback. Useful for init=/bin/hush usage etc */
7077 if (argv[0][0] == '/')
7078 execve(argv[0], argv, pp);
7079 xfunc_error_retval = 127;
7080 bb_error_msg_and_die("can't re-execute the shell");
7081}
7082#endif /* !BB_MMU */
7083
7084
7085static int run_and_free_list(struct pipe *pi);
7086
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007087/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007088 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7089 * end_trigger controls how often we stop parsing
7090 * NUL: parse all, execute, return
7091 * ';': parse till ';' or newline, execute, repeat till EOF
7092 */
7093static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007094{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007095 /* Why we need empty flag?
7096 * An obscure corner case "false; ``; echo $?":
7097 * empty command in `` should still set $? to 0.
7098 * But we can't just set $? to 0 at the start,
7099 * this breaks "false; echo `echo $?`" case.
7100 */
7101 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007102 while (1) {
7103 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007104
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007105#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007106 if (end_trigger == ';') {
7107 G.promptmode = 0; /* PS1 */
7108 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7109 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007110#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007111 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007112 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7113 /* If we are in "big" script
7114 * (not in `cmd` or something similar)...
7115 */
7116 if (pipe_list == ERR_PTR && end_trigger == ';') {
7117 /* Discard cached input (rest of line) */
7118 int ch = inp->last_char;
7119 while (ch != EOF && ch != '\n') {
7120 //bb_error_msg("Discarded:'%c'", ch);
7121 ch = i_getch(inp);
7122 }
7123 /* Force prompt */
7124 inp->p = NULL;
7125 /* This stream isn't empty */
7126 empty = 0;
7127 continue;
7128 }
7129 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007130 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007131 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007132 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007133 debug_print_tree(pipe_list, 0);
7134 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7135 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007136 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007137 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007138 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007139 }
Eric Andersen25f27032001-04-26 23:22:31 +00007140}
7141
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007142static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007143{
7144 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007145 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7146
Eric Andersen25f27032001-04-26 23:22:31 +00007147 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007148 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007149 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007150}
7151
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007152static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007153{
Eric Andersen25f27032001-04-26 23:22:31 +00007154 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007155 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007156
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007157 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007158 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007159 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007160 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007161}
7162
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007163#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007164static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007165{
7166 pid_t pid;
7167 int channel[2];
7168# if !BB_MMU
7169 char **to_free = NULL;
7170# endif
7171
7172 xpipe(channel);
7173 pid = BB_MMU ? xfork() : xvfork();
7174 if (pid == 0) { /* child */
7175 disable_restore_tty_pgrp_on_exit();
7176 /* Process substitution is not considered to be usual
7177 * 'command execution'.
7178 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7179 */
7180 bb_signals(0
7181 + (1 << SIGTSTP)
7182 + (1 << SIGTTIN)
7183 + (1 << SIGTTOU)
7184 , SIG_IGN);
7185 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7186 close(channel[0]); /* NB: close _first_, then move fd! */
7187 xmove_fd(channel[1], 1);
7188 /* Prevent it from trying to handle ctrl-z etc */
7189 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007190# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007191 /* Awful hack for `trap` or $(trap).
7192 *
7193 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7194 * contains an example where "trap" is executed in a subshell:
7195 *
7196 * save_traps=$(trap)
7197 * ...
7198 * eval "$save_traps"
7199 *
7200 * Standard does not say that "trap" in subshell shall print
7201 * parent shell's traps. It only says that its output
7202 * must have suitable form, but then, in the above example
7203 * (which is not supposed to be normative), it implies that.
7204 *
7205 * bash (and probably other shell) does implement it
7206 * (traps are reset to defaults, but "trap" still shows them),
7207 * but as a result, "trap" logic is hopelessly messed up:
7208 *
7209 * # trap
7210 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7211 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7212 * # true | trap <--- trap is in subshell - no output (ditto)
7213 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7214 * trap -- 'echo Ho' SIGWINCH
7215 * # echo `(trap)` <--- in subshell in subshell - output
7216 * trap -- 'echo Ho' SIGWINCH
7217 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7218 * trap -- 'echo Ho' SIGWINCH
7219 *
7220 * The rules when to forget and when to not forget traps
7221 * get really complex and nonsensical.
7222 *
7223 * Our solution: ONLY bare $(trap) or `trap` is special.
7224 */
7225 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007226 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007227 && skip_whitespace(s + 4)[0] == '\0'
7228 ) {
7229 static const char *const argv[] = { NULL, NULL };
7230 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007231 fflush_all(); /* important */
7232 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007233 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007234# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007235# if BB_MMU
7236 reset_traps_to_defaults();
7237 parse_and_run_string(s);
7238 _exit(G.last_exitcode);
7239# else
7240 /* We re-execute after vfork on NOMMU. This makes this script safe:
7241 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7242 * huge=`cat BIG` # was blocking here forever
7243 * echo OK
7244 */
7245 re_execute_shell(&to_free,
7246 s,
7247 G.global_argv[0],
7248 G.global_argv + 1,
7249 NULL);
7250# endif
7251 }
7252
7253 /* parent */
7254 *pid_p = pid;
7255# if ENABLE_HUSH_FAST
7256 G.count_SIGCHLD++;
7257//bb_error_msg("[%d] fork in generate_stream_from_string:"
7258// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7259// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7260# endif
7261 enable_restore_tty_pgrp_on_exit();
7262# if !BB_MMU
7263 free(to_free);
7264# endif
7265 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007266 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007267}
7268
7269/* Return code is exit status of the process that is run. */
7270static int process_command_subs(o_string *dest, const char *s)
7271{
7272 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007273 pid_t pid;
7274 int status, ch, eol_cnt;
7275
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007276 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007277
7278 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007279 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007280 while ((ch = getc(fp)) != EOF) {
7281 if (ch == '\0')
7282 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007283 if (ch == '\n') {
7284 eol_cnt++;
7285 continue;
7286 }
7287 while (eol_cnt) {
7288 o_addchr(dest, '\n');
7289 eol_cnt--;
7290 }
7291 o_addQchr(dest, ch);
7292 }
7293
7294 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007295 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007296 /* We need to extract exitcode. Test case
7297 * "true; echo `sleep 1; false` $?"
7298 * should print 1 */
7299 safe_waitpid(pid, &status, 0);
7300 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7301 return WEXITSTATUS(status);
7302}
7303#endif /* ENABLE_HUSH_TICK */
7304
7305
7306static void setup_heredoc(struct redir_struct *redir)
7307{
7308 struct fd_pair pair;
7309 pid_t pid;
7310 int len, written;
7311 /* the _body_ of heredoc (misleading field name) */
7312 const char *heredoc = redir->rd_filename;
7313 char *expanded;
7314#if !BB_MMU
7315 char **to_free;
7316#endif
7317
7318 expanded = NULL;
7319 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007320 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007321 if (expanded)
7322 heredoc = expanded;
7323 }
7324 len = strlen(heredoc);
7325
7326 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7327 xpiped_pair(pair);
7328 xmove_fd(pair.rd, redir->rd_fd);
7329
7330 /* Try writing without forking. Newer kernels have
7331 * dynamically growing pipes. Must use non-blocking write! */
7332 ndelay_on(pair.wr);
7333 while (1) {
7334 written = write(pair.wr, heredoc, len);
7335 if (written <= 0)
7336 break;
7337 len -= written;
7338 if (len == 0) {
7339 close(pair.wr);
7340 free(expanded);
7341 return;
7342 }
7343 heredoc += written;
7344 }
7345 ndelay_off(pair.wr);
7346
7347 /* Okay, pipe buffer was not big enough */
7348 /* Note: we must not create a stray child (bastard? :)
7349 * for the unsuspecting parent process. Child creates a grandchild
7350 * and exits before parent execs the process which consumes heredoc
7351 * (that exec happens after we return from this function) */
7352#if !BB_MMU
7353 to_free = NULL;
7354#endif
7355 pid = xvfork();
7356 if (pid == 0) {
7357 /* child */
7358 disable_restore_tty_pgrp_on_exit();
7359 pid = BB_MMU ? xfork() : xvfork();
7360 if (pid != 0)
7361 _exit(0);
7362 /* grandchild */
7363 close(redir->rd_fd); /* read side of the pipe */
7364#if BB_MMU
7365 full_write(pair.wr, heredoc, len); /* may loop or block */
7366 _exit(0);
7367#else
7368 /* Delegate blocking writes to another process */
7369 xmove_fd(pair.wr, STDOUT_FILENO);
7370 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7371#endif
7372 }
7373 /* parent */
7374#if ENABLE_HUSH_FAST
7375 G.count_SIGCHLD++;
7376//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7377#endif
7378 enable_restore_tty_pgrp_on_exit();
7379#if !BB_MMU
7380 free(to_free);
7381#endif
7382 close(pair.wr);
7383 free(expanded);
7384 wait(NULL); /* wait till child has died */
7385}
7386
Denys Vlasenko2db74612017-07-07 22:07:28 +02007387struct squirrel {
7388 int orig_fd;
7389 int moved_to;
7390 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7391 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7392};
7393
Denys Vlasenko621fc502017-07-24 12:42:17 +02007394static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7395{
7396 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7397 sq[i].orig_fd = orig;
7398 sq[i].moved_to = moved;
7399 sq[i+1].orig_fd = -1; /* end marker */
7400 return sq;
7401}
7402
Denys Vlasenko2db74612017-07-07 22:07:28 +02007403static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7404{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007405 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007406 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007407
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007408 i = 0;
7409 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007410 /* If we collide with an already moved fd... */
7411 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007412 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007413 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7414 if (sq[i].moved_to < 0) /* what? */
7415 xfunc_die();
7416 return sq;
7417 }
7418 if (fd == sq[i].orig_fd) {
7419 /* Example: echo Hello >/dev/null 1>&2 */
7420 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7421 return sq;
7422 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007423 }
7424
Denys Vlasenko2db74612017-07-07 22:07:28 +02007425 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007426 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007427 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7428 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007429 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007430 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007431}
7432
Denys Vlasenko657e9002017-07-30 23:34:04 +02007433static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7434{
7435 int i;
7436
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007437 i = 0;
7438 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007439 /* If we collide with an already moved fd... */
7440 if (fd == sq[i].orig_fd) {
7441 /* Examples:
7442 * "echo 3>FILE 3>&- 3>FILE"
7443 * "echo 3>&- 3>FILE"
7444 * No need for last redirect to insert
7445 * another "need to close 3" indicator.
7446 */
7447 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7448 return sq;
7449 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007450 }
7451
7452 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7453 return append_squirrel(sq, i, fd, -1);
7454}
7455
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007456/* fd: redirect wants this fd to be used (e.g. 3>file).
7457 * Move all conflicting internally used fds,
7458 * and remember them so that we can restore them later.
7459 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007460static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007461{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007462 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7463 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007464
7465#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007466 if (fd == G.interactive_fd) {
7467 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007468 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007469 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7470 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007471 }
7472#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007473 /* If this one of script's fds? */
7474 if (move_HFILEs_on_redirect(fd, avoid_fd))
7475 return 1; /* yes. "we closed fd" (actually moved it) */
7476
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007477 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007478 * (1) Redirect in a forked child.
7479 * (2) "exec 3>FILE".
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007480 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007481 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007482 return 0;
7483
Denys Vlasenko2db74612017-07-07 22:07:28 +02007484 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7485 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7486 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007487}
7488
Denys Vlasenko2db74612017-07-07 22:07:28 +02007489static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007490{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007491 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007492 int i;
7493 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007494 if (sq[i].moved_to >= 0) {
7495 /* We simply die on error */
7496 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7497 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7498 } else {
7499 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7500 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7501 close(sq[i].orig_fd);
7502 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007503 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007504 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007505 }
7506
Denys Vlasenko2db74612017-07-07 22:07:28 +02007507 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007508}
7509
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007510#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007511static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007512{
7513 if (G_interactive_fd)
7514 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007515 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007516}
7517#endif
7518
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007519static int internally_opened_fd(int fd, struct squirrel *sq)
7520{
7521 int i;
7522
7523#if ENABLE_HUSH_INTERACTIVE
7524 if (fd == G.interactive_fd)
7525 return 1;
7526#endif
7527 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007528 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007529 return 1;
7530
7531 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7532 if (fd == sq[i].moved_to)
7533 return 1;
7534 }
7535 return 0;
7536}
7537
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007538/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7539 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007540static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007541{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007542 struct redir_struct *redir;
7543
7544 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007545 int newfd;
7546 int closed;
7547
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007548 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007549 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007550 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007551 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7552 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007553 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007554 redir->rd_filename);
7555 setup_heredoc(redir);
7556 continue;
7557 }
7558
7559 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007560 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007561 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007562 int mode;
7563
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007564 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007565 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007566 * "cmd >" (no filename)
7567 * "cmd > <file" (2nd redirect starts too early)
7568 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007569 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007570 continue;
7571 }
7572 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007573 p = expand_string_to_string(redir->rd_filename,
7574 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007575 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007576 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007577 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007578 /* Error message from open_or_warn can be lost
7579 * if stderr has been redirected, but bash
7580 * and ash both lose it as well
7581 * (though zsh doesn't!)
7582 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007583 return 1;
7584 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007585 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007586 /* open() gave us precisely the fd we wanted.
7587 * This means that this fd was not busy
7588 * (not opened to anywhere).
7589 * Remember to close it on restore:
7590 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007591 *sqp = add_squirrel_closed(*sqp, newfd);
7592 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007593 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007594 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007595 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7596 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007597 }
7598
Denys Vlasenko657e9002017-07-30 23:34:04 +02007599 if (newfd == redir->rd_fd)
7600 continue;
7601
7602 /* if "N>FILE": move newfd to redir->rd_fd */
7603 /* if "N>&M": dup newfd to redir->rd_fd */
7604 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7605
7606 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7607 if (newfd == REDIRFD_CLOSE) {
7608 /* "N>&-" means "close me" */
7609 if (!closed) {
7610 /* ^^^ optimization: saving may already
7611 * have closed it. If not... */
7612 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007613 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007614 /* Sometimes we do another close on restore, getting EBADF.
7615 * Consider "echo 3>FILE 3>&-"
7616 * first redirect remembers "need to close 3",
7617 * and second redirect closes 3! Restore code then closes 3 again.
7618 */
7619 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007620 /* if newfd is a script fd or saved fd, simulate EBADF */
7621 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7622 //errno = EBADF;
7623 //bb_perror_msg_and_die("can't duplicate file descriptor");
7624 newfd = -1; /* same effect as code above */
7625 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007626 xdup2(newfd, redir->rd_fd);
7627 if (redir->rd_dup == REDIRFD_TO_FILE)
7628 /* "rd_fd > FILE" */
7629 close(newfd);
7630 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007631 }
7632 }
7633 return 0;
7634}
7635
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007636static char *find_in_path(const char *arg)
7637{
7638 char *ret = NULL;
7639 const char *PATH = get_local_var_value("PATH");
7640
7641 if (!PATH)
7642 return NULL;
7643
7644 while (1) {
7645 const char *end = strchrnul(PATH, ':');
7646 int sz = end - PATH; /* must be int! */
7647
7648 free(ret);
7649 if (sz != 0) {
7650 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7651 } else {
7652 /* We have xxx::yyyy in $PATH,
7653 * it means "use current dir" */
7654 ret = xstrdup(arg);
7655 }
7656 if (access(ret, F_OK) == 0)
7657 break;
7658
7659 if (*end == '\0') {
7660 free(ret);
7661 return NULL;
7662 }
7663 PATH = end + 1;
7664 }
7665
7666 return ret;
7667}
7668
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007669static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007670 const struct built_in_command *x,
7671 const struct built_in_command *end)
7672{
7673 while (x != end) {
7674 if (strcmp(name, x->b_cmd) != 0) {
7675 x++;
7676 continue;
7677 }
7678 debug_printf_exec("found builtin '%s'\n", name);
7679 return x;
7680 }
7681 return NULL;
7682}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007683static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007684{
7685 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7686}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007687static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007688{
7689 const struct built_in_command *x = find_builtin1(name);
7690 if (x)
7691 return x;
7692 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7693}
7694
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007695static void remove_nested_vars(void)
7696{
7697 struct variable *cur;
7698 struct variable **cur_pp;
7699
7700 cur_pp = &G.top_var;
7701 while ((cur = *cur_pp) != NULL) {
7702 if (cur->var_nest_level <= G.var_nest_level) {
7703 cur_pp = &cur->next;
7704 continue;
7705 }
7706 /* Unexport */
7707 if (cur->flg_export) {
7708 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7709 bb_unsetenv(cur->varstr);
7710 }
7711 /* Remove from global list */
7712 *cur_pp = cur->next;
7713 /* Free */
7714 if (!cur->max_len) {
7715 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7716 free(cur->varstr);
7717 }
7718 free(cur);
7719 }
7720}
7721
7722static void enter_var_nest_level(void)
7723{
7724 G.var_nest_level++;
7725 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7726
7727 /* Try: f() { echo -n .; f; }; f
7728 * struct variable::var_nest_level is uint16_t,
7729 * thus limiting recursion to < 2^16.
7730 * In any case, with 8 Mbyte stack SEGV happens
7731 * not too long after 2^16 recursions anyway.
7732 */
7733 if (G.var_nest_level > 0xff00)
7734 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7735}
7736
7737static void leave_var_nest_level(void)
7738{
7739 G.var_nest_level--;
7740 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7741 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7742 bb_error_msg_and_die("BUG: nesting underflow");
7743
7744 remove_nested_vars();
7745}
7746
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007747#if ENABLE_HUSH_FUNCTIONS
7748static struct function **find_function_slot(const char *name)
7749{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007750 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007751 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007752
7753 while ((funcp = *funcpp) != NULL) {
7754 if (strcmp(name, funcp->name) == 0) {
7755 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007756 break;
7757 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007758 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007759 }
7760 return funcpp;
7761}
7762
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007763static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007764{
7765 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007766 return funcp;
7767}
7768
7769/* Note: takes ownership on name ptr */
7770static struct function *new_function(char *name)
7771{
7772 struct function **funcpp = find_function_slot(name);
7773 struct function *funcp = *funcpp;
7774
7775 if (funcp != NULL) {
7776 struct command *cmd = funcp->parent_cmd;
7777 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7778 if (!cmd) {
7779 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7780 free(funcp->name);
7781 /* Note: if !funcp->body, do not free body_as_string!
7782 * This is a special case of "-F name body" function:
7783 * body_as_string was not malloced! */
7784 if (funcp->body) {
7785 free_pipe_list(funcp->body);
7786# if !BB_MMU
7787 free(funcp->body_as_string);
7788# endif
7789 }
7790 } else {
7791 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7792 cmd->argv[0] = funcp->name;
7793 cmd->group = funcp->body;
7794# if !BB_MMU
7795 cmd->group_as_string = funcp->body_as_string;
7796# endif
7797 }
7798 } else {
7799 debug_printf_exec("remembering new function '%s'\n", name);
7800 funcp = *funcpp = xzalloc(sizeof(*funcp));
7801 /*funcp->next = NULL;*/
7802 }
7803
7804 funcp->name = name;
7805 return funcp;
7806}
7807
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007808# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007809static void unset_func(const char *name)
7810{
7811 struct function **funcpp = find_function_slot(name);
7812 struct function *funcp = *funcpp;
7813
7814 if (funcp != NULL) {
7815 debug_printf_exec("freeing function '%s'\n", funcp->name);
7816 *funcpp = funcp->next;
7817 /* funcp is unlinked now, deleting it.
7818 * Note: if !funcp->body, the function was created by
7819 * "-F name body", do not free ->body_as_string
7820 * and ->name as they were not malloced. */
7821 if (funcp->body) {
7822 free_pipe_list(funcp->body);
7823 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007824# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007825 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007826# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007827 }
7828 free(funcp);
7829 }
7830}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007831# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007832
7833# if BB_MMU
7834#define exec_function(to_free, funcp, argv) \
7835 exec_function(funcp, argv)
7836# endif
7837static void exec_function(char ***to_free,
7838 const struct function *funcp,
7839 char **argv) NORETURN;
7840static void exec_function(char ***to_free,
7841 const struct function *funcp,
7842 char **argv)
7843{
7844# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007845 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007846
7847 argv[0] = G.global_argv[0];
7848 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007849 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007850
7851// Example when we are here: "cmd | func"
7852// func will run with saved-redirect fds open.
7853// $ f() { echo /proc/self/fd/*; }
7854// $ true | f
7855// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7856// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7857// Same in script:
7858// $ . ./SCRIPT
7859// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7860// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7861// They are CLOEXEC so external programs won't see them, but
7862// for "more correctness" we might want to close those extra fds here:
7863//? close_saved_fds_and_FILE_fds();
7864
Denys Vlasenko332e4112018-04-04 22:32:59 +02007865 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007866 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007867 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007868 IF_HUSH_LOCAL(G.func_nest_level++;)
7869
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007870 /* On MMU, funcp->body is always non-NULL */
7871 n = run_list(funcp->body);
7872 fflush_all();
7873 _exit(n);
7874# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007875//? close_saved_fds_and_FILE_fds();
7876
7877//TODO: check whether "true | func_with_return" works
7878
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007879 re_execute_shell(to_free,
7880 funcp->body_as_string,
7881 G.global_argv[0],
7882 argv + 1,
7883 NULL);
7884# endif
7885}
7886
7887static int run_function(const struct function *funcp, char **argv)
7888{
7889 int rc;
7890 save_arg_t sv;
7891 smallint sv_flg;
7892
7893 save_and_replace_G_args(&sv, argv);
7894
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007895 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007896 sv_flg = G_flag_return_in_progress;
7897 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007898
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007899 /* Make "local" variables properly shadow previous ones */
7900 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007901 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007902
7903 /* On MMU, funcp->body is always non-NULL */
7904# if !BB_MMU
7905 if (!funcp->body) {
7906 /* Function defined by -F */
7907 parse_and_run_string(funcp->body_as_string);
7908 rc = G.last_exitcode;
7909 } else
7910# endif
7911 {
7912 rc = run_list(funcp->body);
7913 }
7914
Denys Vlasenko332e4112018-04-04 22:32:59 +02007915 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007916 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007917
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007918 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007919
7920 restore_G_args(&sv, argv);
7921
7922 return rc;
7923}
7924#endif /* ENABLE_HUSH_FUNCTIONS */
7925
7926
7927#if BB_MMU
7928#define exec_builtin(to_free, x, argv) \
7929 exec_builtin(x, argv)
7930#else
7931#define exec_builtin(to_free, x, argv) \
7932 exec_builtin(to_free, argv)
7933#endif
7934static void exec_builtin(char ***to_free,
7935 const struct built_in_command *x,
7936 char **argv) NORETURN;
7937static void exec_builtin(char ***to_free,
7938 const struct built_in_command *x,
7939 char **argv)
7940{
7941#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007942 int rcode;
7943 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007944//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007945 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007946 fflush_all();
7947 _exit(rcode);
7948#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007949 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007950 /* On NOMMU, we must never block!
7951 * Example: { sleep 99 | read line; } & echo Ok
7952 */
7953 re_execute_shell(to_free,
7954 argv[0],
7955 G.global_argv[0],
7956 G.global_argv + 1,
7957 argv);
7958#endif
7959}
7960
7961
7962static void execvp_or_die(char **argv) NORETURN;
7963static void execvp_or_die(char **argv)
7964{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007965 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007966 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007967 /* Don't propagate SIG_IGN to the child */
7968 if (SPECIAL_JOBSTOP_SIGS != 0)
7969 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007970 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007971 e = 2;
7972 if (errno == EACCES) e = 126;
7973 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007974 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007975 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007976}
7977
7978#if ENABLE_HUSH_MODE_X
7979static void dump_cmd_in_x_mode(char **argv)
7980{
7981 if (G_x_mode && argv) {
7982 /* We want to output the line in one write op */
7983 char *buf, *p;
7984 int len;
7985 int n;
7986
7987 len = 3;
7988 n = 0;
7989 while (argv[n])
7990 len += strlen(argv[n++]) + 1;
7991 buf = xmalloc(len);
7992 buf[0] = '+';
7993 p = buf + 1;
7994 n = 0;
7995 while (argv[n])
7996 p += sprintf(p, " %s", argv[n++]);
7997 *p++ = '\n';
7998 *p = '\0';
7999 fputs(buf, stderr);
8000 free(buf);
8001 }
8002}
8003#else
8004# define dump_cmd_in_x_mode(argv) ((void)0)
8005#endif
8006
Denys Vlasenko57000292018-01-12 14:41:45 +01008007#if ENABLE_HUSH_COMMAND
8008static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8009{
8010 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008011
Denys Vlasenko57000292018-01-12 14:41:45 +01008012 if (!opt_vV)
8013 return;
8014
8015 to_free = NULL;
8016 if (!explanation) {
8017 char *path = getenv("PATH");
8018 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008019 if (!explanation)
8020 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008021 if (opt_vV != 'V')
8022 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8023 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008024 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008025 free(to_free);
8026 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008027 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008028}
8029#else
8030# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8031#endif
8032
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008033#if BB_MMU
8034#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8035 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8036#define pseudo_exec(nommu_save, command, argv_expanded) \
8037 pseudo_exec(command, argv_expanded)
8038#endif
8039
8040/* Called after [v]fork() in run_pipe, or from builtin_exec.
8041 * Never returns.
8042 * Don't exit() here. If you don't exec, use _exit instead.
8043 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008044 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008045 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008046static void pseudo_exec_argv(nommu_save_t *nommu_save,
8047 char **argv, int assignment_cnt,
8048 char **argv_expanded) NORETURN;
8049static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8050 char **argv, int assignment_cnt,
8051 char **argv_expanded)
8052{
Denys Vlasenko57000292018-01-12 14:41:45 +01008053 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008054 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008055 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008056 IF_HUSH_COMMAND(char opt_vV = 0;)
8057 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008058
8059 new_env = expand_assignments(argv, assignment_cnt);
8060 dump_cmd_in_x_mode(new_env);
8061
8062 if (!argv[assignment_cnt]) {
8063 /* Case when we are here: ... | var=val | ...
8064 * (note that we do not exit early, i.e., do not optimize out
8065 * expand_assignments(): think about ... | var=`sleep 1` | ...
8066 */
8067 free_strings(new_env);
8068 _exit(EXIT_SUCCESS);
8069 }
8070
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008071 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008072#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008073 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008074#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008075 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008076 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008077#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008078 set_vars_and_save_old(new_env);
8079 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008080
8081 if (argv_expanded) {
8082 argv = argv_expanded;
8083 } else {
8084 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8085#if !BB_MMU
8086 nommu_save->argv = argv;
8087#endif
8088 }
8089 dump_cmd_in_x_mode(argv);
8090
8091#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8092 if (strchr(argv[0], '/') != NULL)
8093 goto skip;
8094#endif
8095
Denys Vlasenko75481d32017-07-31 05:27:09 +02008096#if ENABLE_HUSH_FUNCTIONS
8097 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008098 funcp = find_function(argv[0]);
8099 if (funcp)
8100 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008101#endif
8102
Denys Vlasenko57000292018-01-12 14:41:45 +01008103#if ENABLE_HUSH_COMMAND
8104 /* "command BAR": run BAR without looking it up among functions
8105 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8106 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8107 */
8108 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8109 char *p;
8110
8111 argv++;
8112 p = *argv;
8113 if (p[0] != '-' || !p[1])
8114 continue; /* bash allows "command command command [-OPT] BAR" */
8115
8116 for (;;) {
8117 p++;
8118 switch (*p) {
8119 case '\0':
8120 argv++;
8121 p = *argv;
8122 if (p[0] != '-' || !p[1])
8123 goto after_opts;
8124 continue; /* next arg is also -opts, process it too */
8125 case 'v':
8126 case 'V':
8127 opt_vV = *p;
8128 continue;
8129 default:
8130 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8131 }
8132 }
8133 }
8134 after_opts:
8135# if ENABLE_HUSH_FUNCTIONS
8136 if (opt_vV && find_function(argv[0]))
8137 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8138# endif
8139#endif
8140
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008141 /* Check if the command matches any of the builtins.
8142 * Depending on context, this might be redundant. But it's
8143 * easier to waste a few CPU cycles than it is to figure out
8144 * if this is one of those cases.
8145 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008146 /* Why "BB_MMU ? :" difference in logic? -
8147 * On NOMMU, it is more expensive to re-execute shell
8148 * just in order to run echo or test builtin.
8149 * It's better to skip it here and run corresponding
8150 * non-builtin later. */
8151 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8152 if (x) {
8153 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8154 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008155 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008156
8157#if ENABLE_FEATURE_SH_STANDALONE
8158 /* Check if the command matches any busybox applets */
8159 {
8160 int a = find_applet_by_name(argv[0]);
8161 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008162 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008163# if BB_MMU /* see above why on NOMMU it is not allowed */
8164 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008165 /* Do not leak open fds from opened script files etc.
8166 * Testcase: interactive "ls -l /proc/self/fd"
8167 * should not show tty fd open.
8168 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008169 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008170//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008171//This casuses test failures in
8172//redir_children_should_not_see_saved_fd_2.tests
8173//redir_children_should_not_see_saved_fd_3.tests
8174//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008175 /* Without this, "rm -i FILE" can't be ^C'ed: */
8176 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008177 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008178 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008179 }
8180# endif
8181 /* Re-exec ourselves */
8182 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008183 /* Don't propagate SIG_IGN to the child */
8184 if (SPECIAL_JOBSTOP_SIGS != 0)
8185 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008186 execv(bb_busybox_exec_path, argv);
8187 /* If they called chroot or otherwise made the binary no longer
8188 * executable, fall through */
8189 }
8190 }
8191#endif
8192
8193#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8194 skip:
8195#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008196 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008197 execvp_or_die(argv);
8198}
8199
8200/* Called after [v]fork() in run_pipe
8201 */
8202static void pseudo_exec(nommu_save_t *nommu_save,
8203 struct command *command,
8204 char **argv_expanded) NORETURN;
8205static void pseudo_exec(nommu_save_t *nommu_save,
8206 struct command *command,
8207 char **argv_expanded)
8208{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008209#if ENABLE_HUSH_FUNCTIONS
8210 if (command->cmd_type == CMD_FUNCDEF) {
8211 /* Ignore funcdefs in pipes:
8212 * true | f() { cmd }
8213 */
8214 _exit(0);
8215 }
8216#endif
8217
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008218 if (command->argv) {
8219 pseudo_exec_argv(nommu_save, command->argv,
8220 command->assignment_cnt, argv_expanded);
8221 }
8222
8223 if (command->group) {
8224 /* Cases when we are here:
8225 * ( list )
8226 * { list } &
8227 * ... | ( list ) | ...
8228 * ... | { list } | ...
8229 */
8230#if BB_MMU
8231 int rcode;
8232 debug_printf_exec("pseudo_exec: run_list\n");
8233 reset_traps_to_defaults();
8234 rcode = run_list(command->group);
8235 /* OK to leak memory by not calling free_pipe_list,
8236 * since this process is about to exit */
8237 _exit(rcode);
8238#else
8239 re_execute_shell(&nommu_save->argv_from_re_execing,
8240 command->group_as_string,
8241 G.global_argv[0],
8242 G.global_argv + 1,
8243 NULL);
8244#endif
8245 }
8246
8247 /* Case when we are here: ... | >file */
8248 debug_printf_exec("pseudo_exec'ed null command\n");
8249 _exit(EXIT_SUCCESS);
8250}
8251
8252#if ENABLE_HUSH_JOB
8253static const char *get_cmdtext(struct pipe *pi)
8254{
8255 char **argv;
8256 char *p;
8257 int len;
8258
8259 /* This is subtle. ->cmdtext is created only on first backgrounding.
8260 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8261 * On subsequent bg argv is trashed, but we won't use it */
8262 if (pi->cmdtext)
8263 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008264
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008265 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008266 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008267 pi->cmdtext = xzalloc(1);
8268 return pi->cmdtext;
8269 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008270 len = 0;
8271 do {
8272 len += strlen(*argv) + 1;
8273 } while (*++argv);
8274 p = xmalloc(len);
8275 pi->cmdtext = p;
8276 argv = pi->cmds[0].argv;
8277 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008278 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008279 *p++ = ' ';
8280 } while (*++argv);
8281 p[-1] = '\0';
8282 return pi->cmdtext;
8283}
8284
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008285static void remove_job_from_table(struct pipe *pi)
8286{
8287 struct pipe *prev_pipe;
8288
8289 if (pi == G.job_list) {
8290 G.job_list = pi->next;
8291 } else {
8292 prev_pipe = G.job_list;
8293 while (prev_pipe->next != pi)
8294 prev_pipe = prev_pipe->next;
8295 prev_pipe->next = pi->next;
8296 }
8297 G.last_jobid = 0;
8298 if (G.job_list)
8299 G.last_jobid = G.job_list->jobid;
8300}
8301
8302static void delete_finished_job(struct pipe *pi)
8303{
8304 remove_job_from_table(pi);
8305 free_pipe(pi);
8306}
8307
8308static void clean_up_last_dead_job(void)
8309{
8310 if (G.job_list && !G.job_list->alive_cmds)
8311 delete_finished_job(G.job_list);
8312}
8313
Denys Vlasenko16096292017-07-10 10:00:28 +02008314static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008315{
8316 struct pipe *job, **jobp;
8317 int i;
8318
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008319 clean_up_last_dead_job();
8320
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008321 /* Find the end of the list, and find next job ID to use */
8322 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008323 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008324 while ((job = *jobp) != NULL) {
8325 if (job->jobid > i)
8326 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008327 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008328 }
8329 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008330
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008331 /* Create a new job struct at the end */
8332 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008333 job->next = NULL;
8334 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8335 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8336 for (i = 0; i < pi->num_cmds; i++) {
8337 job->cmds[i].pid = pi->cmds[i].pid;
8338 /* all other fields are not used and stay zero */
8339 }
8340 job->cmdtext = xstrdup(get_cmdtext(pi));
8341
8342 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008343 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008344 G.last_jobid = job->jobid;
8345}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008346#endif /* JOB */
8347
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008348static int job_exited_or_stopped(struct pipe *pi)
8349{
8350 int rcode, i;
8351
8352 if (pi->alive_cmds != pi->stopped_cmds)
8353 return -1;
8354
8355 /* All processes in fg pipe have exited or stopped */
8356 rcode = 0;
8357 i = pi->num_cmds;
8358 while (--i >= 0) {
8359 rcode = pi->cmds[i].cmd_exitcode;
8360 /* usually last process gives overall exitstatus,
8361 * but with "set -o pipefail", last *failed* process does */
8362 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8363 break;
8364 }
8365 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8366 return rcode;
8367}
8368
Denys Vlasenko7e675362016-10-28 21:57:31 +02008369static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008370{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008371#if ENABLE_HUSH_JOB
8372 struct pipe *pi;
8373#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008374 int i, dead;
8375
8376 dead = WIFEXITED(status) || WIFSIGNALED(status);
8377
8378#if DEBUG_JOBS
8379 if (WIFSTOPPED(status))
8380 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8381 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8382 if (WIFSIGNALED(status))
8383 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8384 childpid, WTERMSIG(status), WEXITSTATUS(status));
8385 if (WIFEXITED(status))
8386 debug_printf_jobs("pid %d exited, exitcode %d\n",
8387 childpid, WEXITSTATUS(status));
8388#endif
8389 /* Were we asked to wait for a fg pipe? */
8390 if (fg_pipe) {
8391 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008392
Denys Vlasenko7e675362016-10-28 21:57:31 +02008393 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008394 int rcode;
8395
Denys Vlasenko7e675362016-10-28 21:57:31 +02008396 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8397 if (fg_pipe->cmds[i].pid != childpid)
8398 continue;
8399 if (dead) {
8400 int ex;
8401 fg_pipe->cmds[i].pid = 0;
8402 fg_pipe->alive_cmds--;
8403 ex = WEXITSTATUS(status);
8404 /* bash prints killer signal's name for *last*
8405 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8406 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8407 */
8408 if (WIFSIGNALED(status)) {
8409 int sig = WTERMSIG(status);
8410 if (i == fg_pipe->num_cmds-1)
8411 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8412 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8413 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8414 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8415 * Maybe we need to use sig | 128? */
8416 ex = sig + 128;
8417 }
8418 fg_pipe->cmds[i].cmd_exitcode = ex;
8419 } else {
8420 fg_pipe->stopped_cmds++;
8421 }
8422 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8423 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008424 rcode = job_exited_or_stopped(fg_pipe);
8425 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008426/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8427 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8428 * and "killall -STOP cat" */
8429 if (G_interactive_fd) {
8430#if ENABLE_HUSH_JOB
8431 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008432 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008433#endif
8434 return rcode;
8435 }
8436 if (fg_pipe->alive_cmds == 0)
8437 return rcode;
8438 }
8439 /* There are still running processes in the fg_pipe */
8440 return -1;
8441 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008442 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008443 }
8444
8445#if ENABLE_HUSH_JOB
8446 /* We were asked to wait for bg or orphaned children */
8447 /* No need to remember exitcode in this case */
8448 for (pi = G.job_list; pi; pi = pi->next) {
8449 for (i = 0; i < pi->num_cmds; i++) {
8450 if (pi->cmds[i].pid == childpid)
8451 goto found_pi_and_prognum;
8452 }
8453 }
8454 /* Happens when shell is used as init process (init=/bin/sh) */
8455 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8456 return -1; /* this wasn't a process from fg_pipe */
8457
8458 found_pi_and_prognum:
8459 if (dead) {
8460 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008461 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008462 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008463 rcode = 128 + WTERMSIG(status);
8464 pi->cmds[i].cmd_exitcode = rcode;
8465 if (G.last_bg_pid == pi->cmds[i].pid)
8466 G.last_bg_pid_exitcode = rcode;
8467 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008468 pi->alive_cmds--;
8469 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008470 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008471 printf(JOB_STATUS_FORMAT, pi->jobid,
8472 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008473 delete_finished_job(pi);
8474 } else {
8475/*
8476 * bash deletes finished jobs from job table only in interactive mode,
8477 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8478 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8479 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8480 * We only retain one "dead" job, if it's the single job on the list.
8481 * This covers most of real-world scenarios where this is useful.
8482 */
8483 if (pi != G.job_list)
8484 delete_finished_job(pi);
8485 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008486 }
8487 } else {
8488 /* child stopped */
8489 pi->stopped_cmds++;
8490 }
8491#endif
8492 return -1; /* this wasn't a process from fg_pipe */
8493}
8494
8495/* Check to see if any processes have exited -- if they have,
8496 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008497 *
8498 * If non-NULL fg_pipe: wait for its completion or stop.
8499 * Return its exitcode or zero if stopped.
8500 *
8501 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8502 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8503 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8504 * or 0 if no children changed status.
8505 *
8506 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8507 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8508 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008509 */
8510static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8511{
8512 int attributes;
8513 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008514 int rcode = 0;
8515
8516 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8517
8518 attributes = WUNTRACED;
8519 if (fg_pipe == NULL)
8520 attributes |= WNOHANG;
8521
8522 errno = 0;
8523#if ENABLE_HUSH_FAST
8524 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8525//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8526//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8527 /* There was neither fork nor SIGCHLD since last waitpid */
8528 /* Avoid doing waitpid syscall if possible */
8529 if (!G.we_have_children) {
8530 errno = ECHILD;
8531 return -1;
8532 }
8533 if (fg_pipe == NULL) { /* is WNOHANG set? */
8534 /* We have children, but they did not exit
8535 * or stop yet (we saw no SIGCHLD) */
8536 return 0;
8537 }
8538 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8539 }
8540#endif
8541
8542/* Do we do this right?
8543 * bash-3.00# sleep 20 | false
8544 * <ctrl-Z pressed>
8545 * [3]+ Stopped sleep 20 | false
8546 * bash-3.00# echo $?
8547 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8548 * [hush 1.14.0: yes we do it right]
8549 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008550 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008551 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008552#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008553 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008554 i = G.count_SIGCHLD;
8555#endif
8556 childpid = waitpid(-1, &status, attributes);
8557 if (childpid <= 0) {
8558 if (childpid && errno != ECHILD)
8559 bb_perror_msg("waitpid");
8560#if ENABLE_HUSH_FAST
8561 else { /* Until next SIGCHLD, waitpid's are useless */
8562 G.we_have_children = (childpid == 0);
8563 G.handled_SIGCHLD = i;
8564//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8565 }
8566#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008567 /* ECHILD (no children), or 0 (no change in children status) */
8568 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008569 break;
8570 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008571 rcode = process_wait_result(fg_pipe, childpid, status);
8572 if (rcode >= 0) {
8573 /* fg_pipe exited or stopped */
8574 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008575 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008576 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008577 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008578 rcode = WEXITSTATUS(status);
8579 if (WIFSIGNALED(status))
8580 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008581 if (WIFSTOPPED(status))
8582 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8583 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008584 rcode++;
8585 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008586 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008587 /* This wasn't one of our processes, or */
8588 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008589 } /* while (waitpid succeeds)... */
8590
8591 return rcode;
8592}
8593
8594#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008595static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008596{
8597 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008598 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008599 if (G_saved_tty_pgrp) {
8600 /* Job finished, move the shell to the foreground */
8601 p = getpgrp(); /* our process group id */
8602 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8603 tcsetpgrp(G_interactive_fd, p);
8604 }
8605 return rcode;
8606}
8607#endif
8608
8609/* Start all the jobs, but don't wait for anything to finish.
8610 * See checkjobs().
8611 *
8612 * Return code is normally -1, when the caller has to wait for children
8613 * to finish to determine the exit status of the pipe. If the pipe
8614 * is a simple builtin command, however, the action is done by the
8615 * time run_pipe returns, and the exit code is provided as the
8616 * return value.
8617 *
8618 * Returns -1 only if started some children. IOW: we have to
8619 * mask out retvals of builtins etc with 0xff!
8620 *
8621 * The only case when we do not need to [v]fork is when the pipe
8622 * is single, non-backgrounded, non-subshell command. Examples:
8623 * cmd ; ... { list } ; ...
8624 * cmd && ... { list } && ...
8625 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008626 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008627 * or (if SH_STANDALONE) an applet, and we can run the { list }
8628 * with run_list. If it isn't one of these, we fork and exec cmd.
8629 *
8630 * Cases when we must fork:
8631 * non-single: cmd | cmd
8632 * backgrounded: cmd & { list } &
8633 * subshell: ( list ) [&]
8634 */
8635#if !ENABLE_HUSH_MODE_X
Denys Vlasenkoc96bb2c2018-06-26 15:43:56 +02008636#define redirect_and_varexp_helper(command, squirrel, argv_expanded) \
8637 redirect_and_varexp_helper(command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008638#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008639static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008640 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008641 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008642 char **argv_expanded)
8643{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008644 /* Assignments occur before redirects. Try:
8645 * a=`sleep 1` sleep 2 3>/qwe/rty
8646 */
8647
8648 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8649 dump_cmd_in_x_mode(new_env);
8650 dump_cmd_in_x_mode(argv_expanded);
8651 /* this takes ownership of new_env[i] elements, and frees new_env: */
8652 set_vars_and_save_old(new_env);
8653
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008654 /* setup_redirects acts on file descriptors, not FILEs.
8655 * This is perfect for work that comes after exec().
8656 * Is it really safe for inline use? Experimentally,
8657 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008658 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008659}
8660static NOINLINE int run_pipe(struct pipe *pi)
8661{
8662 static const char *const null_ptr = NULL;
8663
8664 int cmd_no;
8665 int next_infd;
8666 struct command *command;
8667 char **argv_expanded;
8668 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008669 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008670 int rcode;
8671
8672 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8673 debug_enter();
8674
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008675 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8676 * Result should be 3 lines: q w e, qwe, q w e
8677 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008678 if (G.ifs_whitespace != G.ifs)
8679 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008680 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008681 if (G.ifs) {
8682 char *p;
8683 G.ifs_whitespace = (char*)G.ifs;
8684 p = skip_whitespace(G.ifs);
8685 if (*p) {
8686 /* Not all $IFS is whitespace */
8687 char *d;
8688 int len = p - G.ifs;
8689 p = skip_non_whitespace(p);
8690 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8691 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8692 while (*p) {
8693 if (isspace(*p))
8694 *d++ = *p;
8695 p++;
8696 }
8697 *d = '\0';
8698 }
8699 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008700 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008701 G.ifs_whitespace = (char*)G.ifs;
8702 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008703
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008704 IF_HUSH_JOB(pi->pgrp = -1;)
8705 pi->stopped_cmds = 0;
8706 command = &pi->cmds[0];
8707 argv_expanded = NULL;
8708
8709 if (pi->num_cmds != 1
8710 || pi->followup == PIPE_BG
8711 || command->cmd_type == CMD_SUBSHELL
8712 ) {
8713 goto must_fork;
8714 }
8715
8716 pi->alive_cmds = 1;
8717
8718 debug_printf_exec(": group:%p argv:'%s'\n",
8719 command->group, command->argv ? command->argv[0] : "NONE");
8720
8721 if (command->group) {
8722#if ENABLE_HUSH_FUNCTIONS
8723 if (command->cmd_type == CMD_FUNCDEF) {
8724 /* "executing" func () { list } */
8725 struct function *funcp;
8726
8727 funcp = new_function(command->argv[0]);
8728 /* funcp->name is already set to argv[0] */
8729 funcp->body = command->group;
8730# if !BB_MMU
8731 funcp->body_as_string = command->group_as_string;
8732 command->group_as_string = NULL;
8733# endif
8734 command->group = NULL;
8735 command->argv[0] = NULL;
8736 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8737 funcp->parent_cmd = command;
8738 command->child_func = funcp;
8739
8740 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8741 debug_leave();
8742 return EXIT_SUCCESS;
8743 }
8744#endif
8745 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008746 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008747 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008748 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008749 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008750//FIXME: we need to pass squirrel down into run_list()
8751//for SH_STANDALONE case, or else this construct:
8752// { find /proc/self/fd; true; } >FILE; cmd2
8753//has no way of closing saved fd#1 for "find",
8754//and in SH_STANDALONE mode, "find" is not execed,
8755//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008756 rcode = run_list(command->group) & 0xff;
8757 }
8758 restore_redirects(squirrel);
8759 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8760 debug_leave();
8761 debug_printf_exec("run_pipe: return %d\n", rcode);
8762 return rcode;
8763 }
8764
8765 argv = command->argv ? command->argv : (char **) &null_ptr;
8766 {
8767 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008768 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8769 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008770 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008771 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008772
Denys Vlasenko5807e182018-02-08 19:19:04 +01008773#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008774 if (G.lineno_var)
8775 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8776#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008777
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008778 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008779 /* Assignments, but no command.
8780 * Ensure redirects take effect (that is, create files).
8781 * Try "a=t >file"
8782 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008783 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008784 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008785 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008786 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008787 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008788
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008789 /* Set shell variables */
8790 if (G_x_mode)
8791 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008792 i = 0;
8793 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008794 char *p = expand_string_to_string(argv[i],
8795 EXP_FLAG_ESC_GLOB_CHARS,
8796 /*unbackslash:*/ 1
8797 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008798 if (G_x_mode)
8799 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008800 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008801 if (set_local_var(p, /*flag:*/ 0)) {
8802 /* assignment to readonly var / putenv error? */
8803 rcode = 1;
8804 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008805 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008806 }
8807 if (G_x_mode)
8808 bb_putchar_stderr('\n');
8809 /* Redirect error sets $? to 1. Otherwise,
8810 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008811 * Else, clear $?:
8812 * false; q=`exit 2`; echo $? - should print 2
8813 * false; x=1; echo $? - should print 0
8814 * Because of the 2nd case, we can't just use G.last_exitcode.
8815 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008816 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008817 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008818 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8819 debug_leave();
8820 debug_printf_exec("run_pipe: return %d\n", rcode);
8821 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008822 }
8823
8824 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008825#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008826 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008827 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008828 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008829#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008830 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008831
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008832 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008833 if (!argv_expanded[0]) {
8834 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008835 /* `false` still has to set exitcode 1 */
8836 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008837 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008838 }
8839
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008840 old_vars = NULL;
8841 sv_shadowed = G.shadowed_vars_pp;
8842
Denys Vlasenko75481d32017-07-31 05:27:09 +02008843 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008844 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8845 IF_HUSH_FUNCTIONS(x = NULL;)
8846 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008847 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008848 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008849 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8850 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008851 /*
8852 * Variable assignments are executed, but then "forgotten":
8853 * a=`sleep 1;echo A` exec 3>&-; echo $a
8854 * sleeps, but prints nothing.
8855 */
8856 enter_var_nest_level();
8857 G.shadowed_vars_pp = &old_vars;
8858 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8859 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008860 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008861
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008862 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008863 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008864
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008865 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008866 * a=b true; env | grep ^a=
8867 */
8868 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008869 /* Collect all variables "shadowed" by helper
8870 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8871 * into old_vars list:
8872 */
8873 G.shadowed_vars_pp = &old_vars;
8874 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008875 if (rcode == 0) {
8876 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008877 /* Do not collect *to old_vars list* vars shadowed
8878 * by e.g. "local VAR" builtin (collect them
8879 * in the previously nested list instead):
8880 * don't want them to be restored immediately
8881 * after "local" completes.
8882 */
8883 G.shadowed_vars_pp = sv_shadowed;
8884
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008885 debug_printf_exec(": builtin '%s' '%s'...\n",
8886 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008887 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008888 rcode = x->b_function(argv_expanded) & 0xff;
8889 fflush_all();
8890 }
8891#if ENABLE_HUSH_FUNCTIONS
8892 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008893 debug_printf_exec(": function '%s' '%s'...\n",
8894 funcp->name, argv_expanded[1]);
8895 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008896 /*
8897 * But do collect *to old_vars list* vars shadowed
8898 * within function execution. To that end, restore
8899 * this pointer _after_ function run:
8900 */
8901 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008902 }
8903#endif
8904 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008905 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008906 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008907 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008908 if (n < 0 || !APPLET_IS_NOFORK(n))
8909 goto must_fork;
8910
8911 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008912 /* Collect all variables "shadowed" by helper into old_vars list */
8913 G.shadowed_vars_pp = &old_vars;
8914 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8915 G.shadowed_vars_pp = sv_shadowed;
8916
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008917 if (rcode == 0) {
8918 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8919 argv_expanded[0], argv_expanded[1]);
8920 /*
8921 * Note: signals (^C) can't interrupt here.
8922 * We remember them and they will be acted upon
8923 * after applet returns.
8924 * This makes applets which can run for a long time
8925 * and/or wait for user input ineligible for NOFORK:
8926 * for example, "yes" or "rm" (rm -i waits for input).
8927 */
8928 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008929 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008930 } else
8931 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008932
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008933 restore_redirects(squirrel);
8934 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008935 leave_var_nest_level();
8936 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008937
8938 /*
8939 * Try "usleep 99999999" + ^C + "echo $?"
8940 * with FEATURE_SH_NOFORK=y.
8941 */
8942 if (!funcp) {
8943 /* It was builtin or nofork.
8944 * if this would be a real fork/execed program,
8945 * it should have died if a fatal sig was received.
8946 * But OTOH, there was no separate process,
8947 * the sig was sent to _shell_, not to non-existing
8948 * child.
8949 * Let's just handle ^C only, this one is obvious:
8950 * we aren't ok with exitcode 0 when ^C was pressed
8951 * during builtin/nofork.
8952 */
8953 if (sigismember(&G.pending_set, SIGINT))
8954 rcode = 128 + SIGINT;
8955 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008956 free(argv_expanded);
8957 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8958 debug_leave();
8959 debug_printf_exec("run_pipe return %d\n", rcode);
8960 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008961 }
8962
8963 must_fork:
8964 /* NB: argv_expanded may already be created, and that
8965 * might include `cmd` runs! Do not rerun it! We *must*
8966 * use argv_expanded if it's non-NULL */
8967
8968 /* Going to fork a child per each pipe member */
8969 pi->alive_cmds = 0;
8970 next_infd = 0;
8971
8972 cmd_no = 0;
8973 while (cmd_no < pi->num_cmds) {
8974 struct fd_pair pipefds;
8975#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008976 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008977 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008978 nommu_save.old_vars = NULL;
8979 nommu_save.argv = NULL;
8980 nommu_save.argv_from_re_execing = NULL;
8981#endif
8982 command = &pi->cmds[cmd_no];
8983 cmd_no++;
8984 if (command->argv) {
8985 debug_printf_exec(": pipe member '%s' '%s'...\n",
8986 command->argv[0], command->argv[1]);
8987 } else {
8988 debug_printf_exec(": pipe member with no argv\n");
8989 }
8990
8991 /* pipes are inserted between pairs of commands */
8992 pipefds.rd = 0;
8993 pipefds.wr = 1;
8994 if (cmd_no < pi->num_cmds)
8995 xpiped_pair(pipefds);
8996
Denys Vlasenko5807e182018-02-08 19:19:04 +01008997#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008998 if (G.lineno_var)
8999 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
9000#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009001
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009002 command->pid = BB_MMU ? fork() : vfork();
9003 if (!command->pid) { /* child */
9004#if ENABLE_HUSH_JOB
9005 disable_restore_tty_pgrp_on_exit();
9006 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9007
9008 /* Every child adds itself to new process group
9009 * with pgid == pid_of_first_child_in_pipe */
9010 if (G.run_list_level == 1 && G_interactive_fd) {
9011 pid_t pgrp;
9012 pgrp = pi->pgrp;
9013 if (pgrp < 0) /* true for 1st process only */
9014 pgrp = getpid();
9015 if (setpgid(0, pgrp) == 0
9016 && pi->followup != PIPE_BG
9017 && G_saved_tty_pgrp /* we have ctty */
9018 ) {
9019 /* We do it in *every* child, not just first,
9020 * to avoid races */
9021 tcsetpgrp(G_interactive_fd, pgrp);
9022 }
9023 }
9024#endif
9025 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9026 /* 1st cmd in backgrounded pipe
9027 * should have its stdin /dev/null'ed */
9028 close(0);
9029 if (open(bb_dev_null, O_RDONLY))
9030 xopen("/", O_RDONLY);
9031 } else {
9032 xmove_fd(next_infd, 0);
9033 }
9034 xmove_fd(pipefds.wr, 1);
9035 if (pipefds.rd > 1)
9036 close(pipefds.rd);
9037 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009038 * and the pipe fd (fd#1) is available for dup'ing:
9039 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9040 * of cmd1 goes into pipe.
9041 */
9042 if (setup_redirects(command, NULL)) {
9043 /* Happens when redir file can't be opened:
9044 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9045 * FOO
9046 * hush: can't open '/qwe/rty': No such file or directory
9047 * BAZ
9048 * (echo BAR is not executed, it hits _exit(1) below)
9049 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009050 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009051 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009052
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009053 /* Stores to nommu_save list of env vars putenv'ed
9054 * (NOMMU, on MMU we don't need that) */
9055 /* cast away volatility... */
9056 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9057 /* pseudo_exec() does not return */
9058 }
9059
9060 /* parent or error */
9061#if ENABLE_HUSH_FAST
9062 G.count_SIGCHLD++;
9063//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9064#endif
9065 enable_restore_tty_pgrp_on_exit();
9066#if !BB_MMU
9067 /* Clean up after vforked child */
9068 free(nommu_save.argv);
9069 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009070 G.var_nest_level = sv_var_nest_level;
9071 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009072 add_vars(nommu_save.old_vars);
9073#endif
9074 free(argv_expanded);
9075 argv_expanded = NULL;
9076 if (command->pid < 0) { /* [v]fork failed */
9077 /* Clearly indicate, was it fork or vfork */
9078 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9079 } else {
9080 pi->alive_cmds++;
9081#if ENABLE_HUSH_JOB
9082 /* Second and next children need to know pid of first one */
9083 if (pi->pgrp < 0)
9084 pi->pgrp = command->pid;
9085#endif
9086 }
9087
9088 if (cmd_no > 1)
9089 close(next_infd);
9090 if (cmd_no < pi->num_cmds)
9091 close(pipefds.wr);
9092 /* Pass read (output) pipe end to next iteration */
9093 next_infd = pipefds.rd;
9094 }
9095
9096 if (!pi->alive_cmds) {
9097 debug_leave();
9098 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9099 return 1;
9100 }
9101
9102 debug_leave();
9103 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9104 return -1;
9105}
9106
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009107/* NB: called by pseudo_exec, and therefore must not modify any
9108 * global data until exec/_exit (we can be a child after vfork!) */
9109static int run_list(struct pipe *pi)
9110{
9111#if ENABLE_HUSH_CASE
9112 char *case_word = NULL;
9113#endif
9114#if ENABLE_HUSH_LOOPS
9115 struct pipe *loop_top = NULL;
9116 char **for_lcur = NULL;
9117 char **for_list = NULL;
9118#endif
9119 smallint last_followup;
9120 smalluint rcode;
9121#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9122 smalluint cond_code = 0;
9123#else
9124 enum { cond_code = 0 };
9125#endif
9126#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009127 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009128 smallint last_rword; /* ditto */
9129#endif
9130
9131 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9132 debug_enter();
9133
9134#if ENABLE_HUSH_LOOPS
9135 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009136 {
9137 struct pipe *cpipe;
9138 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9139 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9140 continue;
9141 /* current word is FOR or IN (BOLD in comments below) */
9142 if (cpipe->next == NULL) {
9143 syntax_error("malformed for");
9144 debug_leave();
9145 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9146 return 1;
9147 }
9148 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9149 if (cpipe->next->res_word == RES_DO)
9150 continue;
9151 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9152 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9153 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9154 ) {
9155 syntax_error("malformed for");
9156 debug_leave();
9157 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9158 return 1;
9159 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009160 }
9161 }
9162#endif
9163
9164 /* Past this point, all code paths should jump to ret: label
9165 * in order to return, no direct "return" statements please.
9166 * This helps to ensure that no memory is leaked. */
9167
9168#if ENABLE_HUSH_JOB
9169 G.run_list_level++;
9170#endif
9171
9172#if HAS_KEYWORDS
9173 rword = RES_NONE;
9174 last_rword = RES_XXXX;
9175#endif
9176 last_followup = PIPE_SEQ;
9177 rcode = G.last_exitcode;
9178
9179 /* Go through list of pipes, (maybe) executing them. */
9180 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009181 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009182 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009183
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009184 if (G.flag_SIGINT)
9185 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009186 if (G_flag_return_in_progress == 1)
9187 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009188
9189 IF_HAS_KEYWORDS(rword = pi->res_word;)
9190 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9191 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009192
9193 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009194 if (
9195#if ENABLE_HUSH_IF
9196 rword == RES_IF || rword == RES_ELIF ||
9197#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009198 pi->followup != PIPE_SEQ
9199 ) {
9200 G.errexit_depth++;
9201 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009202#if ENABLE_HUSH_LOOPS
9203 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9204 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9205 ) {
9206 /* start of a loop: remember where loop starts */
9207 loop_top = pi;
9208 G.depth_of_loop++;
9209 }
9210#endif
9211 /* Still in the same "if...", "then..." or "do..." branch? */
9212 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9213 if ((rcode == 0 && last_followup == PIPE_OR)
9214 || (rcode != 0 && last_followup == PIPE_AND)
9215 ) {
9216 /* It is "<true> || CMD" or "<false> && CMD"
9217 * and we should not execute CMD */
9218 debug_printf_exec("skipped cmd because of || or &&\n");
9219 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009220 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009221 }
9222 }
9223 last_followup = pi->followup;
9224 IF_HAS_KEYWORDS(last_rword = rword;)
9225#if ENABLE_HUSH_IF
9226 if (cond_code) {
9227 if (rword == RES_THEN) {
9228 /* if false; then ... fi has exitcode 0! */
9229 G.last_exitcode = rcode = EXIT_SUCCESS;
9230 /* "if <false> THEN cmd": skip cmd */
9231 continue;
9232 }
9233 } else {
9234 if (rword == RES_ELSE || rword == RES_ELIF) {
9235 /* "if <true> then ... ELSE/ELIF cmd":
9236 * skip cmd and all following ones */
9237 break;
9238 }
9239 }
9240#endif
9241#if ENABLE_HUSH_LOOPS
9242 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9243 if (!for_lcur) {
9244 /* first loop through for */
9245
9246 static const char encoded_dollar_at[] ALIGN1 = {
9247 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9248 }; /* encoded representation of "$@" */
9249 static const char *const encoded_dollar_at_argv[] = {
9250 encoded_dollar_at, NULL
9251 }; /* argv list with one element: "$@" */
9252 char **vals;
9253
9254 vals = (char**)encoded_dollar_at_argv;
9255 if (pi->next->res_word == RES_IN) {
9256 /* if no variable values after "in" we skip "for" */
9257 if (!pi->next->cmds[0].argv) {
9258 G.last_exitcode = rcode = EXIT_SUCCESS;
9259 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9260 break;
9261 }
9262 vals = pi->next->cmds[0].argv;
9263 } /* else: "for var; do..." -> assume "$@" list */
9264 /* create list of variable values */
9265 debug_print_strings("for_list made from", vals);
9266 for_list = expand_strvec_to_strvec(vals);
9267 for_lcur = for_list;
9268 debug_print_strings("for_list", for_list);
9269 }
9270 if (!*for_lcur) {
9271 /* "for" loop is over, clean up */
9272 free(for_list);
9273 for_list = NULL;
9274 for_lcur = NULL;
9275 break;
9276 }
9277 /* Insert next value from for_lcur */
9278 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009279 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009280 continue;
9281 }
9282 if (rword == RES_IN) {
9283 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9284 }
9285 if (rword == RES_DONE) {
9286 continue; /* "done" has no cmds too */
9287 }
9288#endif
9289#if ENABLE_HUSH_CASE
9290 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009291 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009292 case_word = expand_string_to_string(pi->cmds->argv[0],
9293 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009294 debug_printf_exec("CASE word1:'%s'\n", case_word);
9295 //unbackslash(case_word);
9296 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009297 continue;
9298 }
9299 if (rword == RES_MATCH) {
9300 char **argv;
9301
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009302 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009303 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9304 break;
9305 /* all prev words didn't match, does this one match? */
9306 argv = pi->cmds->argv;
9307 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009308 char *pattern;
9309 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9310 pattern = expand_string_to_string(*argv,
9311 EXP_FLAG_ESC_GLOB_CHARS,
9312 /*unbackslash:*/ 0
9313 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009314 /* TODO: which FNM_xxx flags to use? */
9315 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009316 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9317 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009318 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009319 if (cond_code == 0) {
9320 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009321 free(case_word);
9322 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009323 break;
9324 }
9325 argv++;
9326 }
9327 continue;
9328 }
9329 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009330 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009331 if (cond_code != 0)
9332 continue; /* not matched yet, skip this pipe */
9333 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009334 if (rword == RES_ESAC) {
9335 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9336 if (case_word) {
9337 /* "case" did not match anything: still set $? (to 0) */
9338 G.last_exitcode = rcode = EXIT_SUCCESS;
9339 }
9340 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009341#endif
9342 /* Just pressing <enter> in shell should check for jobs.
9343 * OTOH, in non-interactive shell this is useless
9344 * and only leads to extra job checks */
9345 if (pi->num_cmds == 0) {
9346 if (G_interactive_fd)
9347 goto check_jobs_and_continue;
9348 continue;
9349 }
9350
9351 /* After analyzing all keywords and conditions, we decided
9352 * to execute this pipe. NB: have to do checkjobs(NULL)
9353 * after run_pipe to collect any background children,
9354 * even if list execution is to be stopped. */
9355 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009356#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009357 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009358#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009359 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9360 if (r != -1) {
9361 /* We ran a builtin, function, or group.
9362 * rcode is already known
9363 * and we don't need to wait for anything. */
9364 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9365 G.last_exitcode = rcode;
9366 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009367#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009368 /* Was it "break" or "continue"? */
9369 if (G.flag_break_continue) {
9370 smallint fbc = G.flag_break_continue;
9371 /* We might fall into outer *loop*,
9372 * don't want to break it too */
9373 if (loop_top) {
9374 G.depth_break_continue--;
9375 if (G.depth_break_continue == 0)
9376 G.flag_break_continue = 0;
9377 /* else: e.g. "continue 2" should *break* once, *then* continue */
9378 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9379 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009380 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009381 break;
9382 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009383 /* "continue": simulate end of loop */
9384 rword = RES_DONE;
9385 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009386 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009387#endif
9388 if (G_flag_return_in_progress == 1) {
9389 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9390 break;
9391 }
9392 } else if (pi->followup == PIPE_BG) {
9393 /* What does bash do with attempts to background builtins? */
9394 /* even bash 3.2 doesn't do that well with nested bg:
9395 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9396 * I'm NOT treating inner &'s as jobs */
9397#if ENABLE_HUSH_JOB
9398 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009399 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009400#endif
9401 /* Last command's pid goes to $! */
9402 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009403 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009404 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009405/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009406 rcode = EXIT_SUCCESS;
9407 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009408 } else {
9409#if ENABLE_HUSH_JOB
9410 if (G.run_list_level == 1 && G_interactive_fd) {
9411 /* Waits for completion, then fg's main shell */
9412 rcode = checkjobs_and_fg_shell(pi);
9413 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009414 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009415 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009416#endif
9417 /* This one just waits for completion */
9418 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9419 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9420 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009421 G.last_exitcode = rcode;
9422 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009423 }
9424
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009425 /* Handle "set -e" */
9426 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9427 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9428 if (G.errexit_depth == 0)
9429 hush_exit(rcode);
9430 }
9431 G.errexit_depth = sv_errexit_depth;
9432
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009433 /* Analyze how result affects subsequent commands */
9434#if ENABLE_HUSH_IF
9435 if (rword == RES_IF || rword == RES_ELIF)
9436 cond_code = rcode;
9437#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009438 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009439 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009440 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009441#if ENABLE_HUSH_LOOPS
9442 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009443 if (pi->next
9444 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009445 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009446 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009447 if (rword == RES_WHILE) {
9448 if (rcode) {
9449 /* "while false; do...done" - exitcode 0 */
9450 G.last_exitcode = rcode = EXIT_SUCCESS;
9451 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009452 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009453 }
9454 }
9455 if (rword == RES_UNTIL) {
9456 if (!rcode) {
9457 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009458 break;
9459 }
9460 }
9461 }
9462#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009463 } /* for (pi) */
9464
9465#if ENABLE_HUSH_JOB
9466 G.run_list_level--;
9467#endif
9468#if ENABLE_HUSH_LOOPS
9469 if (loop_top)
9470 G.depth_of_loop--;
9471 free(for_list);
9472#endif
9473#if ENABLE_HUSH_CASE
9474 free(case_word);
9475#endif
9476 debug_leave();
9477 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9478 return rcode;
9479}
9480
9481/* Select which version we will use */
9482static int run_and_free_list(struct pipe *pi)
9483{
9484 int rcode = 0;
9485 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009486 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009487 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9488 rcode = run_list(pi);
9489 }
9490 /* free_pipe_list has the side effect of clearing memory.
9491 * In the long run that function can be merged with run_list,
9492 * but doing that now would hobble the debugging effort. */
9493 free_pipe_list(pi);
9494 debug_printf_exec("run_and_free_list return %d\n", rcode);
9495 return rcode;
9496}
9497
9498
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009499static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009500{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009501 sighandler_t old_handler;
9502 unsigned sig = 0;
9503 while ((mask >>= 1) != 0) {
9504 sig++;
9505 if (!(mask & 1))
9506 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009507 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009508 /* POSIX allows shell to re-enable SIGCHLD
9509 * even if it was SIG_IGN on entry.
9510 * Therefore we skip IGN check for it:
9511 */
9512 if (sig == SIGCHLD)
9513 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009514 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9515 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9516 */
9517 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009518 if (old_handler == SIG_IGN) {
9519 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009520 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009521#if ENABLE_HUSH_TRAP
9522 if (!G_traps)
9523 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9524 free(G_traps[sig]);
9525 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9526#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009527 }
9528 }
9529}
9530
9531/* Called a few times only (or even once if "sh -c") */
9532static void install_special_sighandlers(void)
9533{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009534 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009535
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009536 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009537 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009538 if (G_interactive_fd) {
9539 mask |= SPECIAL_INTERACTIVE_SIGS;
9540 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009541 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009542 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009543 /* Careful, do not re-install handlers we already installed */
9544 if (G.special_sig_mask != mask) {
9545 unsigned diff = mask & ~G.special_sig_mask;
9546 G.special_sig_mask = mask;
9547 install_sighandlers(diff);
9548 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009549}
9550
9551#if ENABLE_HUSH_JOB
9552/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009553/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009554static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009555{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009556 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009557
9558 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009559 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009560 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9561 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009562 + (1 << SIGBUS ) * HUSH_DEBUG
9563 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009564 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009565 + (1 << SIGABRT)
9566 /* bash 3.2 seems to handle these just like 'fatal' ones */
9567 + (1 << SIGPIPE)
9568 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009569 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009570 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009571 * we never want to restore pgrp on exit, and this fn is not called
9572 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009573 /*+ (1 << SIGHUP )*/
9574 /*+ (1 << SIGTERM)*/
9575 /*+ (1 << SIGINT )*/
9576 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009577 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009578
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009579 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009580}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009581#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009582
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009583static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009584{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009585 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009586 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009587 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009588 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009589 break;
9590 case 'x':
9591 IF_HUSH_MODE_X(G_x_mode = state;)
9592 break;
9593 case 'o':
9594 if (!o_opt) {
9595 /* "set -+o" without parameter.
9596 * in bash, set -o produces this output:
9597 * pipefail off
9598 * and set +o:
9599 * set +o pipefail
9600 * We always use the second form.
9601 */
9602 const char *p = o_opt_strings;
9603 idx = 0;
9604 while (*p) {
9605 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9606 idx++;
9607 p += strlen(p) + 1;
9608 }
9609 break;
9610 }
9611 idx = index_in_strings(o_opt_strings, o_opt);
9612 if (idx >= 0) {
9613 G.o_opt[idx] = state;
9614 break;
9615 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009616 case 'e':
9617 G.o_opt[OPT_O_ERREXIT] = state;
9618 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009619 default:
9620 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009621 }
9622 return EXIT_SUCCESS;
9623}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009624
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009625int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009626int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009627{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009628 enum {
9629 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009630 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009631 };
9632 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009633 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009634 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009635 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009636 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009637
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009638 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009639 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009640 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009641
Denys Vlasenko10c01312011-05-11 11:49:21 +02009642#if ENABLE_HUSH_FAST
9643 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9644#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009645#if !BB_MMU
9646 G.argv0_for_re_execing = argv[0];
9647#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009648
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009649 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009650 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9651 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009652 shell_ver = xzalloc(sizeof(*shell_ver));
9653 shell_ver->flg_export = 1;
9654 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009655 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009656 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009657 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009658
Denys Vlasenko605067b2010-09-06 12:10:51 +02009659 /* Create shell local variables from the values
9660 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009661 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009662 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009663 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009664 if (e) while (*e) {
9665 char *value = strchr(*e, '=');
9666 if (value) { /* paranoia */
9667 cur_var->next = xzalloc(sizeof(*cur_var));
9668 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009669 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009670 cur_var->max_len = strlen(*e);
9671 cur_var->flg_export = 1;
9672 }
9673 e++;
9674 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009675 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009676 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9677 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009678
9679 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009680 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009681
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009682#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9683 /* Set (but not export) PS1/2 unless already set */
9684 if (!get_local_var_value("PS1"))
9685 set_local_var_from_halves("PS1", "\\w \\$ ");
9686 if (!get_local_var_value("PS2"))
9687 set_local_var_from_halves("PS2", "> ");
9688#endif
9689
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009690#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009691 /* Set (but not export) HOSTNAME unless already set */
9692 if (!get_local_var_value("HOSTNAME")) {
9693 struct utsname uts;
9694 uname(&uts);
9695 set_local_var_from_halves("HOSTNAME", uts.nodename);
9696 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009697 /* bash also exports SHLVL and _,
9698 * and sets (but doesn't export) the following variables:
9699 * BASH=/bin/bash
9700 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9701 * BASH_VERSION='3.2.0(1)-release'
9702 * HOSTTYPE=i386
9703 * MACHTYPE=i386-pc-linux-gnu
9704 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009705 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009706 * EUID=<NNNNN>
9707 * UID=<NNNNN>
9708 * GROUPS=()
9709 * LINES=<NNN>
9710 * COLUMNS=<NNN>
9711 * BASH_ARGC=()
9712 * BASH_ARGV=()
9713 * BASH_LINENO=()
9714 * BASH_SOURCE=()
9715 * DIRSTACK=()
9716 * PIPESTATUS=([0]="0")
9717 * HISTFILE=/<xxx>/.bash_history
9718 * HISTFILESIZE=500
9719 * HISTSIZE=500
9720 * MAILCHECK=60
9721 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9722 * SHELL=/bin/bash
9723 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9724 * TERM=dumb
9725 * OPTERR=1
9726 * OPTIND=1
9727 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009728 * PS4='+ '
9729 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009730#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009731
Denys Vlasenko5807e182018-02-08 19:19:04 +01009732#if ENABLE_HUSH_LINENO_VAR
9733 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009734 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9735 set_local_var(p, /*flags*/ 0);
9736 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9737 }
9738#endif
9739
Denis Vlasenko38f63192007-01-22 09:03:07 +00009740#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009741 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009742#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009743
Eric Andersen94ac2442001-05-22 19:05:18 +00009744 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009745 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009746
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009747 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009748
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009749 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009750 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009751 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009752 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009753 * in order to intercept (more) signals.
9754 */
9755
9756 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009757 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009758 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009759 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009760 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009761 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009762#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009763 "<:$:R:V:"
9764# if ENABLE_HUSH_FUNCTIONS
9765 "F:"
9766# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009767#endif
9768 );
9769 if (opt <= 0)
9770 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009771 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009772 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009773 /* Possibilities:
9774 * sh ... -c 'script'
9775 * sh ... -c 'script' ARG0 [ARG1...]
9776 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009777 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009778 * "" needs to be replaced with NULL
9779 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009780 * Note: the form without ARG0 never happens:
9781 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009782 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009783 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009784 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009785 G.root_ppid = getppid();
9786 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009787 G.global_argv = argv + optind;
9788 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009789 if (builtin_argc) {
9790 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9791 const struct built_in_command *x;
9792
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009793 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009794 x = find_builtin(optarg);
9795 if (x) { /* paranoia */
9796 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9797 G.global_argv += builtin_argc;
9798 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009799 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009800 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009801 }
9802 goto final_return;
9803 }
9804 if (!G.global_argv[0]) {
9805 /* -c 'script' (no params): prevent empty $0 */
9806 G.global_argv--; /* points to argv[i] of 'script' */
9807 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009808 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009809 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009810 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009811 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009812 goto final_return;
9813 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009814 /* Well, we cannot just declare interactiveness,
9815 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009816 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009817 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009818 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009819 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009820 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009821 case 'l':
9822 flags |= OPT_login;
9823 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009824#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009825 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009826 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009827 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009828 case '$': {
9829 unsigned long long empty_trap_mask;
9830
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009831 G.root_pid = bb_strtou(optarg, &optarg, 16);
9832 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009833 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9834 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009835 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9836 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009837 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009838 optarg++;
9839 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009840 optarg++;
9841 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9842 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009843 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009844 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009845# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009846 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009847 for (sig = 1; sig < NSIG; sig++) {
9848 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009849 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009850 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009851 }
9852 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009853# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009854 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009855# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009856 optarg++;
9857 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009858# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009859# if ENABLE_HUSH_FUNCTIONS
9860 /* nommu uses re-exec trick for "... | func | ...",
9861 * should allow "return".
9862 * This accidentally allows returns in subshells.
9863 */
9864 G_flag_return_in_progress = -1;
9865# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009866 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009867 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009868 case 'R':
9869 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009870 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009871 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009872# if ENABLE_HUSH_FUNCTIONS
9873 case 'F': {
9874 struct function *funcp = new_function(optarg);
9875 /* funcp->name is already set to optarg */
9876 /* funcp->body is set to NULL. It's a special case. */
9877 funcp->body_as_string = argv[optind];
9878 optind++;
9879 break;
9880 }
9881# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009882#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009883 case 'n':
9884 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009885 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009886 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009887 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009888 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009889#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009890 fprintf(stderr, "Usage: sh [FILE]...\n"
9891 " or: sh -c command [args]...\n\n");
9892 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009893#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009894 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009895#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009896 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009897 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009898
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009899 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9900 G.global_argc = argc - (optind - 1);
9901 G.global_argv = argv + (optind - 1);
9902 G.global_argv[0] = argv[0];
9903
Denys Vlasenkodea47882009-10-09 15:40:49 +02009904 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009905 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009906 G.root_ppid = getppid();
9907 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009908
9909 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009910 if (flags & OPT_login) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009911 HFILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009912 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009913 input = hfopen("/etc/profile");
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009914 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009915 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009916 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009917 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009918 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009919 /* bash: after sourcing /etc/profile,
9920 * tries to source (in the given order):
9921 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009922 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009923 * bash also sources ~/.bash_logout on exit.
9924 * If called as sh, skips .bash_XXX files.
9925 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009926 }
9927
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009928 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9929 if (!(flags & OPT_s) && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009930 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +00009931 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009932 * "bash <script>" (which is never interactive (unless -i?))
9933 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009934 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009935 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009936 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009937 G.global_argc--;
9938 G.global_argv++;
9939 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009940 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009941 input = hfopen(G.global_argv[0]);
9942 if (!input) {
9943 bb_simple_perror_msg_and_die(G.global_argv[0]);
9944 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009945 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009946 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009947 parse_and_run_file(input);
9948#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009949 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009950#endif
9951 goto final_return;
9952 }
9953
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009954 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009955 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009956 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009957
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009958 /* A shell is interactive if the '-i' flag was given,
9959 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009960 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009961 * no arguments remaining or the -s flag given
9962 * standard input is a terminal
9963 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009964 * Refer to Posix.2, the description of the 'sh' utility.
9965 */
9966#if ENABLE_HUSH_JOB
9967 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009968 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9969 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9970 if (G_saved_tty_pgrp < 0)
9971 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009972
9973 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009974 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009975 if (G_interactive_fd < 0) {
9976 /* try to dup to any fd */
9977 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009978 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009979 /* give up */
9980 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009981 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009982 }
9983 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009984// TODO: track & disallow any attempts of user
9985// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009986 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009987 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009988 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009989 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009990
Mike Frysinger38478a62009-05-20 04:48:06 -04009991 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009992 /* If we were run as 'hush &', sleep until we are
9993 * in the foreground (tty pgrp == our pgrp).
9994 * If we get started under a job aware app (like bash),
9995 * make sure we are now in charge so we don't fight over
9996 * who gets the foreground */
9997 while (1) {
9998 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009999 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10000 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010001 break;
10002 /* send TTIN to ourself (should stop us) */
10003 kill(- shell_pgrp, SIGTTIN);
10004 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010005 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010006
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010007 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010008 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010009
Mike Frysinger38478a62009-05-20 04:48:06 -040010010 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010011 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010012 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010013 /* Put ourselves in our own process group
10014 * (bash, too, does this only if ctty is available) */
10015 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10016 /* Grab control of the terminal */
10017 tcsetpgrp(G_interactive_fd, getpid());
10018 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010019 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010020
10021# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10022 {
10023 const char *hp = get_local_var_value("HISTFILE");
10024 if (!hp) {
10025 hp = get_local_var_value("HOME");
10026 if (hp)
10027 hp = concat_path_file(hp, ".hush_history");
10028 } else {
10029 hp = xstrdup(hp);
10030 }
10031 if (hp) {
10032 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010033 //set_local_var(xasprintf("HISTFILE=%s", ...));
10034 }
10035# if ENABLE_FEATURE_SH_HISTFILESIZE
10036 hp = get_local_var_value("HISTFILESIZE");
10037 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10038# endif
10039 }
10040# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010041 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010042 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010043 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010044#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010045 /* No job control compiled in, only prompt/line editing */
10046 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010047 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010048 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010049 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010050 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010051 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010052 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010053 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010054 }
10055 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010056 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010057 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010058 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010059 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010060#else
10061 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010062 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010063#endif
10064 /* bash:
10065 * if interactive but not a login shell, sources ~/.bashrc
10066 * (--norc turns this off, --rcfile <file> overrides)
10067 */
10068
10069 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +020010070 /* note: ash and hush share this string */
10071 printf("\n\n%s %s\n"
10072 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10073 "\n",
10074 bb_banner,
10075 "hush - the humble shell"
10076 );
Mike Frysingerb2705e12009-03-23 08:44:02 +000010077 }
10078
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010079 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010080
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010081 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010082 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010083}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010084
10085
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010086/*
10087 * Built-ins
10088 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010089static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010090{
10091 return 0;
10092}
10093
Denys Vlasenko265062d2017-01-10 15:13:30 +010010094#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010095static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010096{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010097 int argc = string_array_len(argv);
10098 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010099}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010100#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010101#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010102static int FAST_FUNC builtin_test(char **argv)
10103{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010104 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010105}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010106#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010107#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010108static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010109{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010110 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010111}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010112#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010113#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010114static int FAST_FUNC builtin_printf(char **argv)
10115{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010116 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010117}
10118#endif
10119
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010120#if ENABLE_HUSH_HELP
10121static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10122{
10123 const struct built_in_command *x;
10124
10125 printf(
10126 "Built-in commands:\n"
10127 "------------------\n");
10128 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10129 if (x->b_descr)
10130 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10131 }
10132 return EXIT_SUCCESS;
10133}
10134#endif
10135
10136#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10137static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10138{
10139 show_history(G.line_input_state);
10140 return EXIT_SUCCESS;
10141}
10142#endif
10143
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010144static char **skip_dash_dash(char **argv)
10145{
10146 argv++;
10147 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10148 argv++;
10149 return argv;
10150}
10151
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010152static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010153{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010154 const char *newdir;
10155
10156 argv = skip_dash_dash(argv);
10157 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010158 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010159 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010160 * bash says "bash: cd: HOME not set" and does nothing
10161 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010162 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010163 const char *home = get_local_var_value("HOME");
10164 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010165 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010166 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010167 /* Mimic bash message exactly */
10168 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010169 return EXIT_FAILURE;
10170 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010171 /* Read current dir (get_cwd(1) is inside) and set PWD.
10172 * Note: do not enforce exporting. If PWD was unset or unexported,
10173 * set it again, but do not export. bash does the same.
10174 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010175 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010176 return EXIT_SUCCESS;
10177}
10178
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010179static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10180{
10181 puts(get_cwd(0));
10182 return EXIT_SUCCESS;
10183}
10184
10185static int FAST_FUNC builtin_eval(char **argv)
10186{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010187 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010188
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010189 if (!argv[0])
10190 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010191
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010192 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010193 /* bash:
10194 * eval "echo Hi; done" ("done" is syntax error):
10195 * "echo Hi" will not execute too.
10196 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010197 parse_and_run_string(argv[0]);
10198 } else {
10199 /* "The eval utility shall construct a command by
10200 * concatenating arguments together, separating
10201 * each with a <space> character."
10202 */
10203 char *str, *p;
10204 unsigned len = 0;
10205 char **pp = argv;
10206 do
10207 len += strlen(*pp) + 1;
10208 while (*++pp);
10209 str = p = xmalloc(len);
10210 pp = argv;
10211 for (;;) {
10212 p = stpcpy(p, *pp);
10213 pp++;
10214 if (!*pp)
10215 break;
10216 *p++ = ' ';
10217 }
10218 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010219 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010220 }
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010221 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010222}
10223
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010224static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010225{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010226 argv = skip_dash_dash(argv);
10227 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010228 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010229
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010230 /* Careful: we can end up here after [v]fork. Do not restore
10231 * tty pgrp then, only top-level shell process does that */
10232 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10233 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10234
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010235 /* Saved-redirect fds, script fds and G_interactive_fd are still
10236 * open here. However, they are all CLOEXEC, and execv below
10237 * closes them. Try interactive "exec ls -l /proc/self/fd",
10238 * it should show no extra open fds in the "ls" process.
10239 * If we'd try to run builtins/NOEXECs, this would need improving.
10240 */
10241 //close_saved_fds_and_FILE_fds();
10242
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010243 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010244 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010245 * and tcsetpgrp, and this is inherently racy.
10246 */
10247 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010248}
10249
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010250static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010251{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010252 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010253
10254 /* interactive bash:
10255 * # trap "echo EEE" EXIT
10256 * # exit
10257 * exit
10258 * There are stopped jobs.
10259 * (if there are _stopped_ jobs, running ones don't count)
10260 * # exit
10261 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010262 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010263 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010264 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010265 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010266
10267 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010268 argv = skip_dash_dash(argv);
10269 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010270 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010271 /* mimic bash: exit 123abc == exit 255 + error msg */
10272 xfunc_error_retval = 255;
10273 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010274 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010275}
10276
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010277#if ENABLE_HUSH_TYPE
10278/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10279static int FAST_FUNC builtin_type(char **argv)
10280{
10281 int ret = EXIT_SUCCESS;
10282
10283 while (*++argv) {
10284 const char *type;
10285 char *path = NULL;
10286
10287 if (0) {} /* make conditional compile easier below */
10288 /*else if (find_alias(*argv))
10289 type = "an alias";*/
10290#if ENABLE_HUSH_FUNCTIONS
10291 else if (find_function(*argv))
10292 type = "a function";
10293#endif
10294 else if (find_builtin(*argv))
10295 type = "a shell builtin";
10296 else if ((path = find_in_path(*argv)) != NULL)
10297 type = path;
10298 else {
10299 bb_error_msg("type: %s: not found", *argv);
10300 ret = EXIT_FAILURE;
10301 continue;
10302 }
10303
10304 printf("%s is %s\n", *argv, type);
10305 free(path);
10306 }
10307
10308 return ret;
10309}
10310#endif
10311
10312#if ENABLE_HUSH_READ
10313/* Interruptibility of read builtin in bash
10314 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10315 *
10316 * Empty trap makes read ignore corresponding signal, for any signal.
10317 *
10318 * SIGINT:
10319 * - terminates non-interactive shell;
10320 * - interrupts read in interactive shell;
10321 * if it has non-empty trap:
10322 * - executes trap and returns to command prompt in interactive shell;
10323 * - executes trap and returns to read in non-interactive shell;
10324 * SIGTERM:
10325 * - is ignored (does not interrupt) read in interactive shell;
10326 * - terminates non-interactive shell;
10327 * if it has non-empty trap:
10328 * - executes trap and returns to read;
10329 * SIGHUP:
10330 * - terminates shell (regardless of interactivity);
10331 * if it has non-empty trap:
10332 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010333 * SIGCHLD from children:
10334 * - does not interrupt read regardless of interactivity:
10335 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010336 */
10337static int FAST_FUNC builtin_read(char **argv)
10338{
10339 const char *r;
10340 char *opt_n = NULL;
10341 char *opt_p = NULL;
10342 char *opt_t = NULL;
10343 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010344 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010345 const char *ifs;
10346 int read_flags;
10347
10348 /* "!": do not abort on errors.
10349 * Option string must start with "sr" to match BUILTIN_READ_xxx
10350 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010351 read_flags = getopt32(argv,
10352#if BASH_READ_D
10353 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10354#else
10355 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10356#endif
10357 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010358 if (read_flags == (uint32_t)-1)
10359 return EXIT_FAILURE;
10360 argv += optind;
10361 ifs = get_local_var_value("IFS"); /* can be NULL */
10362
10363 again:
10364 r = shell_builtin_read(set_local_var_from_halves,
10365 argv,
10366 ifs,
10367 read_flags,
10368 opt_n,
10369 opt_p,
10370 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010371 opt_u,
10372 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010373 );
10374
10375 if ((uintptr_t)r == 1 && errno == EINTR) {
10376 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010377 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010378 goto again;
10379 }
10380
10381 if ((uintptr_t)r > 1) {
10382 bb_error_msg("%s", r);
10383 r = (char*)(uintptr_t)1;
10384 }
10385
10386 return (uintptr_t)r;
10387}
10388#endif
10389
10390#if ENABLE_HUSH_UMASK
10391static int FAST_FUNC builtin_umask(char **argv)
10392{
10393 int rc;
10394 mode_t mask;
10395
10396 rc = 1;
10397 mask = umask(0);
10398 argv = skip_dash_dash(argv);
10399 if (argv[0]) {
10400 mode_t old_mask = mask;
10401
10402 /* numeric umasks are taken as-is */
10403 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10404 if (!isdigit(argv[0][0]))
10405 mask ^= 0777;
10406 mask = bb_parse_mode(argv[0], mask);
10407 if (!isdigit(argv[0][0]))
10408 mask ^= 0777;
10409 if ((unsigned)mask > 0777) {
10410 mask = old_mask;
10411 /* bash messages:
10412 * bash: umask: 'q': invalid symbolic mode operator
10413 * bash: umask: 999: octal number out of range
10414 */
10415 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10416 rc = 0;
10417 }
10418 } else {
10419 /* Mimic bash */
10420 printf("%04o\n", (unsigned) mask);
10421 /* fall through and restore mask which we set to 0 */
10422 }
10423 umask(mask);
10424
10425 return !rc; /* rc != 0 - success */
10426}
10427#endif
10428
Denys Vlasenko41ade052017-01-08 18:56:24 +010010429#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010430static void print_escaped(const char *s)
10431{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010432 if (*s == '\'')
10433 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010434 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010435 const char *p = strchrnul(s, '\'');
10436 /* print 'xxxx', possibly just '' */
10437 printf("'%.*s'", (int)(p - s), s);
10438 if (*p == '\0')
10439 break;
10440 s = p;
10441 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010442 /* s points to '; print "'''...'''" */
10443 putchar('"');
10444 do putchar('\''); while (*++s == '\'');
10445 putchar('"');
10446 } while (*s);
10447}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010448#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010449
Denys Vlasenko1e660422017-07-17 21:10:50 +020010450#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010451static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010452{
10453 do {
10454 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010455 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010456
10457 /* So far we do not check that name is valid (TODO?) */
10458
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010459 if (*name_end == '\0') {
10460 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010461
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010462 vpp = get_ptr_to_local_var(name, name_end - name);
10463 var = vpp ? *vpp : NULL;
10464
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010465 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010466 /* export -n NAME (without =VALUE) */
10467 if (var) {
10468 var->flg_export = 0;
10469 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10470 unsetenv(name);
10471 } /* else: export -n NOT_EXISTING_VAR: no-op */
10472 continue;
10473 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010474 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010475 /* export NAME (without =VALUE) */
10476 if (var) {
10477 var->flg_export = 1;
10478 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10479 putenv(var->varstr);
10480 continue;
10481 }
10482 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010483 if (flags & SETFLAG_MAKE_RO) {
10484 /* readonly NAME (without =VALUE) */
10485 if (var) {
10486 var->flg_read_only = 1;
10487 continue;
10488 }
10489 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010490# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010491 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010492 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010493 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10494 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010495 /* "local x=abc; ...; local x" - ignore second local decl */
10496 continue;
10497 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010498 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010499# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010500 /* Exporting non-existing variable.
10501 * bash does not put it in environment,
10502 * but remembers that it is exported,
10503 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010504 * We just set it to "" and export.
10505 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010506 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010507 * bash sets the value to "".
10508 */
10509 /* Or, it's "readonly NAME" (without =VALUE).
10510 * bash remembers NAME and disallows its creation
10511 * in the future.
10512 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010513 name = xasprintf("%s=", name);
10514 } else {
10515 /* (Un)exporting/making local NAME=VALUE */
10516 name = xstrdup(name);
10517 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010518 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010519 if (set_local_var(name, flags))
10520 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010521 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010522 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010523}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010524#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010525
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010526#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010527static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010528{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010529 unsigned opt_unexport;
10530
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010531#if ENABLE_HUSH_EXPORT_N
10532 /* "!": do not abort on errors */
10533 opt_unexport = getopt32(argv, "!n");
10534 if (opt_unexport == (uint32_t)-1)
10535 return EXIT_FAILURE;
10536 argv += optind;
10537#else
10538 opt_unexport = 0;
10539 argv++;
10540#endif
10541
10542 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010543 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010544 if (e) {
10545 while (*e) {
10546#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010547 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010548#else
10549 /* ash emits: export VAR='VAL'
10550 * bash: declare -x VAR="VAL"
10551 * we follow ash example */
10552 const char *s = *e++;
10553 const char *p = strchr(s, '=');
10554
10555 if (!p) /* wtf? take next variable */
10556 continue;
10557 /* export var= */
10558 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010559 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010560 putchar('\n');
10561#endif
10562 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010563 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010564 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010565 return EXIT_SUCCESS;
10566 }
10567
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010568 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010569}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010570#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010571
Denys Vlasenko295fef82009-06-03 12:47:26 +020010572#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010573static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010574{
10575 if (G.func_nest_level == 0) {
10576 bb_error_msg("%s: not in a function", argv[0]);
10577 return EXIT_FAILURE; /* bash compat */
10578 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010579 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010580 /* Since all builtins run in a nested variable level,
10581 * need to use level - 1 here. Or else the variable will be removed at once
10582 * after builtin returns.
10583 */
10584 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010585}
10586#endif
10587
Denys Vlasenko1e660422017-07-17 21:10:50 +020010588#if ENABLE_HUSH_READONLY
10589static int FAST_FUNC builtin_readonly(char **argv)
10590{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010591 argv++;
10592 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010593 /* bash: readonly [-p]: list all readonly VARs
10594 * (-p has no effect in bash)
10595 */
10596 struct variable *e;
10597 for (e = G.top_var; e; e = e->next) {
10598 if (e->flg_read_only) {
10599//TODO: quote value: readonly VAR='VAL'
10600 printf("readonly %s\n", e->varstr);
10601 }
10602 }
10603 return EXIT_SUCCESS;
10604 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010605 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010606}
10607#endif
10608
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010609#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010610/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10611static int FAST_FUNC builtin_unset(char **argv)
10612{
10613 int ret;
10614 unsigned opts;
10615
10616 /* "!": do not abort on errors */
10617 /* "+": stop at 1st non-option */
10618 opts = getopt32(argv, "!+vf");
10619 if (opts == (unsigned)-1)
10620 return EXIT_FAILURE;
10621 if (opts == 3) {
10622 bb_error_msg("unset: -v and -f are exclusive");
10623 return EXIT_FAILURE;
10624 }
10625 argv += optind;
10626
10627 ret = EXIT_SUCCESS;
10628 while (*argv) {
10629 if (!(opts & 2)) { /* not -f */
10630 if (unset_local_var(*argv)) {
10631 /* unset <nonexistent_var> doesn't fail.
10632 * Error is when one tries to unset RO var.
10633 * Message was printed by unset_local_var. */
10634 ret = EXIT_FAILURE;
10635 }
10636 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010637# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010638 else {
10639 unset_func(*argv);
10640 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010641# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010642 argv++;
10643 }
10644 return ret;
10645}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010646#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010647
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010648#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010649/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10650 * built-in 'set' handler
10651 * SUSv3 says:
10652 * set [-abCefhmnuvx] [-o option] [argument...]
10653 * set [+abCefhmnuvx] [+o option] [argument...]
10654 * set -- [argument...]
10655 * set -o
10656 * set +o
10657 * Implementations shall support the options in both their hyphen and
10658 * plus-sign forms. These options can also be specified as options to sh.
10659 * Examples:
10660 * Write out all variables and their values: set
10661 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10662 * Turn on the -x and -v options: set -xv
10663 * Unset all positional parameters: set --
10664 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10665 * Set the positional parameters to the expansion of x, even if x expands
10666 * with a leading '-' or '+': set -- $x
10667 *
10668 * So far, we only support "set -- [argument...]" and some of the short names.
10669 */
10670static int FAST_FUNC builtin_set(char **argv)
10671{
10672 int n;
10673 char **pp, **g_argv;
10674 char *arg = *++argv;
10675
10676 if (arg == NULL) {
10677 struct variable *e;
10678 for (e = G.top_var; e; e = e->next)
10679 puts(e->varstr);
10680 return EXIT_SUCCESS;
10681 }
10682
10683 do {
10684 if (strcmp(arg, "--") == 0) {
10685 ++argv;
10686 goto set_argv;
10687 }
10688 if (arg[0] != '+' && arg[0] != '-')
10689 break;
10690 for (n = 1; arg[n]; ++n) {
10691 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10692 goto error;
10693 if (arg[n] == 'o' && argv[1])
10694 argv++;
10695 }
10696 } while ((arg = *++argv) != NULL);
10697 /* Now argv[0] is 1st argument */
10698
10699 if (arg == NULL)
10700 return EXIT_SUCCESS;
10701 set_argv:
10702
10703 /* NB: G.global_argv[0] ($0) is never freed/changed */
10704 g_argv = G.global_argv;
10705 if (G.global_args_malloced) {
10706 pp = g_argv;
10707 while (*++pp)
10708 free(*pp);
10709 g_argv[1] = NULL;
10710 } else {
10711 G.global_args_malloced = 1;
10712 pp = xzalloc(sizeof(pp[0]) * 2);
10713 pp[0] = g_argv[0]; /* retain $0 */
10714 g_argv = pp;
10715 }
10716 /* This realloc's G.global_argv */
10717 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10718
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010719 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010720
10721 return EXIT_SUCCESS;
10722
10723 /* Nothing known, so abort */
10724 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010725 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010726 return EXIT_FAILURE;
10727}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010728#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010729
10730static int FAST_FUNC builtin_shift(char **argv)
10731{
10732 int n = 1;
10733 argv = skip_dash_dash(argv);
10734 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010735 n = bb_strtou(argv[0], NULL, 10);
10736 if (errno || n < 0) {
10737 /* shared string with ash.c */
10738 bb_error_msg("Illegal number: %s", argv[0]);
10739 /*
10740 * ash aborts in this case.
10741 * bash prints error message and set $? to 1.
10742 * Interestingly, for "shift 99999" bash does not
10743 * print error message, but does set $? to 1
10744 * (and does no shifting at all).
10745 */
10746 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010747 }
10748 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010749 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010750 int m = 1;
10751 while (m <= n)
10752 free(G.global_argv[m++]);
10753 }
10754 G.global_argc -= n;
10755 memmove(&G.global_argv[1], &G.global_argv[n+1],
10756 G.global_argc * sizeof(G.global_argv[0]));
10757 return EXIT_SUCCESS;
10758 }
10759 return EXIT_FAILURE;
10760}
10761
Denys Vlasenko74d40582017-08-11 01:32:46 +020010762#if ENABLE_HUSH_GETOPTS
10763static int FAST_FUNC builtin_getopts(char **argv)
10764{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010765/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10766
Denys Vlasenko74d40582017-08-11 01:32:46 +020010767TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010768If a required argument is not found, and getopts is not silent,
10769a question mark (?) is placed in VAR, OPTARG is unset, and a
10770diagnostic message is printed. If getopts is silent, then a
10771colon (:) is placed in VAR and OPTARG is set to the option
10772character found.
10773
10774Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010775
10776"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010777*/
10778 char cbuf[2];
10779 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010780 int c, n, exitcode, my_opterr;
10781 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010782
10783 optstring = *++argv;
10784 if (!optstring || !(var = *++argv)) {
10785 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10786 return EXIT_FAILURE;
10787 }
10788
Denys Vlasenko238ff982017-08-29 13:38:30 +020010789 if (argv[1])
10790 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10791 else
10792 argv = G.global_argv;
10793 cbuf[1] = '\0';
10794
10795 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010796 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010797 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010798 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010799 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010800 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010801
10802 /* getopts stops on first non-option. Add "+" to force that */
10803 /*if (optstring[0] != '+')*/ {
10804 char *s = alloca(strlen(optstring) + 2);
10805 sprintf(s, "+%s", optstring);
10806 optstring = s;
10807 }
10808
Denys Vlasenko238ff982017-08-29 13:38:30 +020010809 /* Naively, now we should just
10810 * cp = get_local_var_value("OPTIND");
10811 * optind = cp ? atoi(cp) : 0;
10812 * optarg = NULL;
10813 * opterr = my_opterr;
10814 * c = getopt(string_array_len(argv), argv, optstring);
10815 * and be done? Not so fast...
10816 * Unlike normal getopt() usage in C programs, here
10817 * each successive call will (usually) have the same argv[] CONTENTS,
10818 * but not the ADDRESSES. Worse yet, it's possible that between
10819 * invocations of "getopts", there will be calls to shell builtins
10820 * which use getopt() internally. Example:
10821 * while getopts "abc" RES -a -bc -abc de; do
10822 * unset -ff func
10823 * done
10824 * This would not work correctly: getopt() call inside "unset"
10825 * modifies internal libc state which is tracking position in
10826 * multi-option strings ("-abc"). At best, it can skip options
10827 * or return the same option infinitely. With glibc implementation
10828 * of getopt(), it would use outright invalid pointers and return
10829 * garbage even _without_ "unset" mangling internal state.
10830 *
10831 * We resort to resetting getopt() state and calling it N times,
10832 * until we get Nth result (or failure).
10833 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10834 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010835 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010836 count = 0;
10837 n = string_array_len(argv);
10838 do {
10839 optarg = NULL;
10840 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10841 c = getopt(n, argv, optstring);
10842 if (c < 0)
10843 break;
10844 count++;
10845 } while (count <= G.getopt_count);
10846
10847 /* Set OPTIND. Prevent resetting of the magic counter! */
10848 set_local_var_from_halves("OPTIND", utoa(optind));
10849 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010850 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010851
10852 /* Set OPTARG */
10853 /* Always set or unset, never left as-is, even on exit/error:
10854 * "If no option was found, or if the option that was found
10855 * does not have an option-argument, OPTARG shall be unset."
10856 */
10857 cp = optarg;
10858 if (c == '?') {
10859 /* If ":optstring" and unknown option is seen,
10860 * it is stored to OPTARG.
10861 */
10862 if (optstring[1] == ':') {
10863 cbuf[0] = optopt;
10864 cp = cbuf;
10865 }
10866 }
10867 if (cp)
10868 set_local_var_from_halves("OPTARG", cp);
10869 else
10870 unset_local_var("OPTARG");
10871
10872 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010873 exitcode = EXIT_SUCCESS;
10874 if (c < 0) { /* -1: end of options */
10875 exitcode = EXIT_FAILURE;
10876 c = '?';
10877 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010878
Denys Vlasenko238ff982017-08-29 13:38:30 +020010879 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010880 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010881 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010882
Denys Vlasenko74d40582017-08-11 01:32:46 +020010883 return exitcode;
10884}
10885#endif
10886
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010887static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010888{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010889 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010890 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010891 save_arg_t sv;
10892 char *args_need_save;
10893#if ENABLE_HUSH_FUNCTIONS
10894 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010895#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010896
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010897 argv = skip_dash_dash(argv);
10898 filename = argv[0];
10899 if (!filename) {
10900 /* bash says: "bash: .: filename argument required" */
10901 return 2; /* bash compat */
10902 }
10903 arg_path = NULL;
10904 if (!strchr(filename, '/')) {
10905 arg_path = find_in_path(filename);
10906 if (arg_path)
10907 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010908 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010909 errno = ENOENT;
10910 bb_simple_perror_msg(filename);
10911 return EXIT_FAILURE;
10912 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010913 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010914 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010915 free(arg_path);
10916 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010917 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010918 /* POSIX: non-interactive shell should abort here,
10919 * not merely fail. So far no one complained :)
10920 */
10921 return EXIT_FAILURE;
10922 }
10923
10924#if ENABLE_HUSH_FUNCTIONS
10925 sv_flg = G_flag_return_in_progress;
10926 /* "we are inside sourced file, ok to use return" */
10927 G_flag_return_in_progress = -1;
10928#endif
10929 args_need_save = argv[1]; /* used as a boolean variable */
10930 if (args_need_save)
10931 save_and_replace_G_args(&sv, argv);
10932
10933 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10934 G.last_exitcode = 0;
10935 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010936 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010937
10938 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10939 restore_G_args(&sv, argv);
10940#if ENABLE_HUSH_FUNCTIONS
10941 G_flag_return_in_progress = sv_flg;
10942#endif
10943
10944 return G.last_exitcode;
10945}
10946
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010947#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010948static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010949{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010950 int sig;
10951 char *new_cmd;
10952
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010953 if (!G_traps)
10954 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010955
10956 argv++;
10957 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010958 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010959 /* No args: print all trapped */
10960 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010961 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010962 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010963 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010964 /* note: bash adds "SIG", but only if invoked
10965 * as "bash". If called as "sh", or if set -o posix,
10966 * then it prints short signal names.
10967 * We are printing short names: */
10968 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010969 }
10970 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010971 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010972 return EXIT_SUCCESS;
10973 }
10974
10975 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010976 /* If first arg is a number: reset all specified signals */
10977 sig = bb_strtou(*argv, NULL, 10);
10978 if (errno == 0) {
10979 int ret;
10980 process_sig_list:
10981 ret = EXIT_SUCCESS;
10982 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010983 sighandler_t handler;
10984
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010985 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010986 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010987 ret = EXIT_FAILURE;
10988 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010989 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010990 continue;
10991 }
10992
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010993 free(G_traps[sig]);
10994 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010995
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010996 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010997 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010998
10999 /* There is no signal for 0 (EXIT) */
11000 if (sig == 0)
11001 continue;
11002
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011003 if (new_cmd)
11004 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11005 else
11006 /* We are removing trap handler */
11007 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011008 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011009 }
11010 return ret;
11011 }
11012
11013 if (!argv[1]) { /* no second arg */
11014 bb_error_msg("trap: invalid arguments");
11015 return EXIT_FAILURE;
11016 }
11017
11018 /* First arg is "-": reset all specified to default */
11019 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11020 /* Everything else: set arg as signal handler
11021 * (includes "" case, which ignores signal) */
11022 if (argv[0][0] == '-') {
11023 if (argv[0][1] == '\0') { /* "-" */
11024 /* new_cmd remains NULL: "reset these sigs" */
11025 goto reset_traps;
11026 }
11027 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11028 argv++;
11029 }
11030 /* else: "-something", no special meaning */
11031 }
11032 new_cmd = *argv;
11033 reset_traps:
11034 argv++;
11035 goto process_sig_list;
11036}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011037#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011038
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011039#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011040static struct pipe *parse_jobspec(const char *str)
11041{
11042 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011043 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011044
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011045 if (sscanf(str, "%%%u", &jobnum) != 1) {
11046 if (str[0] != '%'
11047 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11048 ) {
11049 bb_error_msg("bad argument '%s'", str);
11050 return NULL;
11051 }
11052 /* It is "%%", "%+" or "%" - current job */
11053 jobnum = G.last_jobid;
11054 if (jobnum == 0) {
11055 bb_error_msg("no current job");
11056 return NULL;
11057 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011058 }
11059 for (pi = G.job_list; pi; pi = pi->next) {
11060 if (pi->jobid == jobnum) {
11061 return pi;
11062 }
11063 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011064 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011065 return NULL;
11066}
11067
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011068static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11069{
11070 struct pipe *job;
11071 const char *status_string;
11072
11073 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11074 for (job = G.job_list; job; job = job->next) {
11075 if (job->alive_cmds == job->stopped_cmds)
11076 status_string = "Stopped";
11077 else
11078 status_string = "Running";
11079
11080 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11081 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011082
11083 clean_up_last_dead_job();
11084
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011085 return EXIT_SUCCESS;
11086}
11087
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011088/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011089static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011090{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011091 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011092 struct pipe *pi;
11093
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011094 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011095 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011096
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011097 /* If they gave us no args, assume they want the last backgrounded task */
11098 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011099 for (pi = G.job_list; pi; pi = pi->next) {
11100 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011101 goto found;
11102 }
11103 }
11104 bb_error_msg("%s: no current job", argv[0]);
11105 return EXIT_FAILURE;
11106 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011107
11108 pi = parse_jobspec(argv[1]);
11109 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011110 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011111 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011112 /* TODO: bash prints a string representation
11113 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011114 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011115 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011116 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011117 }
11118
11119 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011120 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11121 for (i = 0; i < pi->num_cmds; i++) {
11122 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011123 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011124 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011125
11126 i = kill(- pi->pgrp, SIGCONT);
11127 if (i < 0) {
11128 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011129 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011130 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011131 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011132 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011133 }
11134
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011135 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011136 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011137 return checkjobs_and_fg_shell(pi);
11138 }
11139 return EXIT_SUCCESS;
11140}
11141#endif
11142
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011143#if ENABLE_HUSH_KILL
11144static int FAST_FUNC builtin_kill(char **argv)
11145{
11146 int ret = 0;
11147
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011148# if ENABLE_HUSH_JOB
11149 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11150 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011151
11152 do {
11153 struct pipe *pi;
11154 char *dst;
11155 int j, n;
11156
11157 if (argv[i][0] != '%')
11158 continue;
11159 /*
11160 * "kill %N" - job kill
11161 * Converting to pgrp / pid kill
11162 */
11163 pi = parse_jobspec(argv[i]);
11164 if (!pi) {
11165 /* Eat bad jobspec */
11166 j = i;
11167 do {
11168 j++;
11169 argv[j - 1] = argv[j];
11170 } while (argv[j]);
11171 ret = 1;
11172 i--;
11173 continue;
11174 }
11175 /*
11176 * In jobs started under job control, we signal
11177 * entire process group by kill -PGRP_ID.
11178 * This happens, f.e., in interactive shell.
11179 *
11180 * Otherwise, we signal each child via
11181 * kill PID1 PID2 PID3.
11182 * Testcases:
11183 * sh -c 'sleep 1|sleep 1 & kill %1'
11184 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11185 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11186 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011187 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011188 dst = alloca(n * sizeof(int)*4);
11189 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011190 if (G_interactive_fd)
11191 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011192 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011193 struct command *cmd = &pi->cmds[j];
11194 /* Skip exited members of the job */
11195 if (cmd->pid == 0)
11196 continue;
11197 /*
11198 * kill_main has matching code to expect
11199 * leading space. Needed to not confuse
11200 * negative pids with "kill -SIGNAL_NO" syntax
11201 */
11202 dst += sprintf(dst, " %u", (int)cmd->pid);
11203 }
11204 *dst = '\0';
11205 } while (argv[++i]);
11206 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011207# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011208
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011209 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011210 ret = run_applet_main(argv, kill_main);
11211 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011212 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011213 return ret;
11214}
11215#endif
11216
11217#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011218/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011219#if !ENABLE_HUSH_JOB
11220# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11221#endif
11222static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011223{
11224 int ret = 0;
11225 for (;;) {
11226 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011227 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011228
Denys Vlasenko830ea352016-11-08 04:59:11 +010011229 if (!sigisemptyset(&G.pending_set))
11230 goto check_sig;
11231
Denys Vlasenko7e675362016-10-28 21:57:31 +020011232 /* waitpid is not interruptible by SA_RESTARTed
11233 * signals which we use. Thus, this ugly dance:
11234 */
11235
11236 /* Make sure possible SIGCHLD is stored in kernel's
11237 * pending signal mask before we call waitpid.
11238 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011239 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011240 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011241 sigfillset(&oldset); /* block all signals, remember old set */
11242 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011243
11244 if (!sigisemptyset(&G.pending_set)) {
11245 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011246 goto restore;
11247 }
11248
11249 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011250/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011251 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011252 debug_printf_exec("checkjobs:%d\n", ret);
11253#if ENABLE_HUSH_JOB
11254 if (waitfor_pipe) {
11255 int rcode = job_exited_or_stopped(waitfor_pipe);
11256 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11257 if (rcode >= 0) {
11258 ret = rcode;
11259 sigprocmask(SIG_SETMASK, &oldset, NULL);
11260 break;
11261 }
11262 }
11263#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011264 /* if ECHILD, there are no children (ret is -1 or 0) */
11265 /* if ret == 0, no children changed state */
11266 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011267 if (errno == ECHILD || ret) {
11268 ret--;
11269 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011270 ret = 0;
11271 sigprocmask(SIG_SETMASK, &oldset, NULL);
11272 break;
11273 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011274 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011275 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11276 /* Note: sigsuspend invokes signal handler */
11277 sigsuspend(&oldset);
11278 restore:
11279 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011280 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011281 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011282 sig = check_and_run_traps();
11283 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011284 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011285 ret = 128 + sig;
11286 break;
11287 }
11288 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11289 }
11290 return ret;
11291}
11292
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011293static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011294{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011295 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011296 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011297
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011298 argv = skip_dash_dash(argv);
11299 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011300 /* Don't care about wait results */
11301 /* Note 1: must wait until there are no more children */
11302 /* Note 2: must be interruptible */
11303 /* Examples:
11304 * $ sleep 3 & sleep 6 & wait
11305 * [1] 30934 sleep 3
11306 * [2] 30935 sleep 6
11307 * [1] Done sleep 3
11308 * [2] Done sleep 6
11309 * $ sleep 3 & sleep 6 & wait
11310 * [1] 30936 sleep 3
11311 * [2] 30937 sleep 6
11312 * [1] Done sleep 3
11313 * ^C <-- after ~4 sec from keyboard
11314 * $
11315 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011316 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011317 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011318
Denys Vlasenko7e675362016-10-28 21:57:31 +020011319 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011320 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011321 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011322#if ENABLE_HUSH_JOB
11323 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011324 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011325 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011326 wait_pipe = parse_jobspec(*argv);
11327 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011328 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011329 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011330 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011331 } else {
11332 /* waiting on "last dead job" removes it */
11333 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011334 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011335 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011336 /* else: parse_jobspec() already emitted error msg */
11337 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011338 }
11339#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011340 /* mimic bash message */
11341 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011342 ret = EXIT_FAILURE;
11343 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011344 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011345
Denys Vlasenko7e675362016-10-28 21:57:31 +020011346 /* Do we have such child? */
11347 ret = waitpid(pid, &status, WNOHANG);
11348 if (ret < 0) {
11349 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011350 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011351 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011352 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011353 /* "wait $!" but last bg task has already exited. Try:
11354 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11355 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011356 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011357 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011358 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011359 } else {
11360 /* Example: "wait 1". mimic bash message */
11361 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011362 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011363 } else {
11364 /* ??? */
11365 bb_perror_msg("wait %s", *argv);
11366 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011367 continue; /* bash checks all argv[] */
11368 }
11369 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011370 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011371 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011372 } else {
11373 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011374 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011375 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011376 if (WIFSIGNALED(status))
11377 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011378 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011379 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011380
11381 return ret;
11382}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011383#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011384
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011385#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11386static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11387{
11388 if (argv[1]) {
11389 def = bb_strtou(argv[1], NULL, 10);
11390 if (errno || def < def_min || argv[2]) {
11391 bb_error_msg("%s: bad arguments", argv[0]);
11392 def = UINT_MAX;
11393 }
11394 }
11395 return def;
11396}
11397#endif
11398
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011399#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011400static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011401{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011402 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011403 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011404 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011405 /* if we came from builtin_continue(), need to undo "= 1" */
11406 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011407 return EXIT_SUCCESS; /* bash compat */
11408 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011409 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011410
11411 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11412 if (depth == UINT_MAX)
11413 G.flag_break_continue = BC_BREAK;
11414 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011415 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011416
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011417 return EXIT_SUCCESS;
11418}
11419
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011420static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011421{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011422 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11423 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011424}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011425#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011426
11427#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011428static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011429{
11430 int rc;
11431
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011432 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011433 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11434 return EXIT_FAILURE; /* bash compat */
11435 }
11436
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011437 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011438
11439 /* bash:
11440 * out of range: wraps around at 256, does not error out
11441 * non-numeric param:
11442 * f() { false; return qwe; }; f; echo $?
11443 * bash: return: qwe: numeric argument required <== we do this
11444 * 255 <== we also do this
11445 */
11446 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11447 return rc;
11448}
11449#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011450
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011451#if ENABLE_HUSH_TIMES
11452static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11453{
11454 static const uint8_t times_tbl[] ALIGN1 = {
11455 ' ', offsetof(struct tms, tms_utime),
11456 '\n', offsetof(struct tms, tms_stime),
11457 ' ', offsetof(struct tms, tms_cutime),
11458 '\n', offsetof(struct tms, tms_cstime),
11459 0
11460 };
11461 const uint8_t *p;
11462 unsigned clk_tck;
11463 struct tms buf;
11464
11465 clk_tck = bb_clk_tck();
11466
11467 times(&buf);
11468 p = times_tbl;
11469 do {
11470 unsigned sec, frac;
11471 unsigned long t;
11472 t = *(clock_t *)(((char *) &buf) + p[1]);
11473 sec = t / clk_tck;
11474 frac = t % clk_tck;
11475 printf("%um%u.%03us%c",
11476 sec / 60, sec % 60,
11477 (frac * 1000) / clk_tck,
11478 p[0]);
11479 p += 2;
11480 } while (*p);
11481
11482 return EXIT_SUCCESS;
11483}
11484#endif
11485
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011486#if ENABLE_HUSH_MEMLEAK
11487static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11488{
11489 void *p;
11490 unsigned long l;
11491
11492# ifdef M_TRIM_THRESHOLD
11493 /* Optional. Reduces probability of false positives */
11494 malloc_trim(0);
11495# endif
11496 /* Crude attempt to find where "free memory" starts,
11497 * sans fragmentation. */
11498 p = malloc(240);
11499 l = (unsigned long)p;
11500 free(p);
11501 p = malloc(3400);
11502 if (l < (unsigned long)p) l = (unsigned long)p;
11503 free(p);
11504
11505
11506# if 0 /* debug */
11507 {
11508 struct mallinfo mi = mallinfo();
11509 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11510 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11511 }
11512# endif
11513
11514 if (!G.memleak_value)
11515 G.memleak_value = l;
11516
11517 l -= G.memleak_value;
11518 if ((long)l < 0)
11519 l = 0;
11520 l /= 1024;
11521 if (l > 127)
11522 l = 127;
11523
11524 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11525 return l;
11526}
11527#endif