blob: 534fabbd0beeffe43d899e8b200c303172b32d87 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * TODO:
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//config: hush is a small shell. It handles the normal flow control
100//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101//config: case/esac. Redirections, here documents, $((arithmetic))
102//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//config:config HUSH_BASH_SOURCE_CURDIR
127//config: bool "'source' and '.' builtins search current directory after $PATH"
128//config: default n # do not encourage non-standard behavior
129//config: depends on HUSH_BASH_COMPAT
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//config: Enable interactive mode (prompt and command editing).
139//config: Without this, hush simply reads and executes commands
140//config: from stdin just like a shell script from a file.
141//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154//config: command (not entire shell), fg/bg builtins work. Without this option,
155//config: "cmd &" still works by simply spawning a process and immediately
156//config: prompting for next command (or executing next command in a script),
157//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
360#ifndef F_DUPFD_CLOEXEC
361# define F_DUPFD_CLOEXEC F_DUPFD
362#endif
363#ifndef PIPE_BUF
364# define PIPE_BUF 4096 /* amount of buffering in a pipe */
365#endif
366
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000367
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100368/* So far, all bash compat is controlled by one config option */
369/* Separate defines document which part of code implements what */
370#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
371#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100372#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
373#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200374#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200375#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100376
377
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200378/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000379#define LEAK_HUNTING 0
380#define BUILD_AS_NOMMU 0
381/* Enable/disable sanity checks. Ok to enable in production,
382 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
383 * Keeping 1 for now even in released versions.
384 */
385#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200386/* Slightly bigger (+200 bytes), but faster hush.
387 * So far it only enables a trick with counting SIGCHLDs and forks,
388 * which allows us to do fewer waitpid's.
389 * (we can detect a case where neither forks were done nor SIGCHLDs happened
390 * and therefore waitpid will return the same result as last time)
391 */
392#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200393/* TODO: implement simplified code for users which do not need ${var%...} ops
394 * So far ${var%...} ops are always enabled:
395 */
396#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000397
398
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000399#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000400# undef BB_MMU
401# undef USE_FOR_NOMMU
402# undef USE_FOR_MMU
403# define BB_MMU 0
404# define USE_FOR_NOMMU(...) __VA_ARGS__
405# define USE_FOR_MMU(...)
406#endif
407
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200408#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100409#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000410/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000411# undef CONFIG_FEATURE_SH_STANDALONE
412# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000413# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100414# undef IF_NOT_FEATURE_SH_STANDALONE
415# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# define IF_FEATURE_SH_STANDALONE(...)
417# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000418#endif
419
Denis Vlasenko05743d72008-02-10 12:10:08 +0000420#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000421# undef ENABLE_FEATURE_EDITING
422# define ENABLE_FEATURE_EDITING 0
423# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
424# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200425# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
426# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000427#endif
428
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000429/* Do we support ANY keywords? */
430#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000431# define HAS_KEYWORDS 1
432# define IF_HAS_KEYWORDS(...) __VA_ARGS__
433# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000434#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000435# define HAS_KEYWORDS 0
436# define IF_HAS_KEYWORDS(...)
437# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000438#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000439
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000440/* If you comment out one of these below, it will be #defined later
441 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000442#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000443/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000444#define debug_printf_parse(...) do {} while (0)
445#define debug_print_tree(a, b) do {} while (0)
446#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000447#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000448#define debug_printf_jobs(...) do {} while (0)
449#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200450#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000451#define debug_printf_glob(...) do {} while (0)
Denys Vlasenko2db74612017-07-07 22:07:28 +0200452#define debug_printf_redir(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000453#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000454#define debug_printf_subst(...) do {} while (0)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200455#define debug_printf_prompt(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000456#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000457
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000458#define ERR_PTR ((void*)(long)1)
459
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100460#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000461
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200462#define _SPECIAL_VARS_STR "_*@$!?#"
463#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
464#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100465#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200466/* Support / and // replace ops */
467/* Note that // is stored as \ in "encoded" string representation */
468# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
469# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
470# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
471#else
472# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
473# define VAR_SUBST_OPS "%#:-=+?"
474# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
475#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200476
Denys Vlasenko932b9972018-01-11 12:39:48 +0100477#define SPECIAL_VAR_SYMBOL_STR "\3"
478#define SPECIAL_VAR_SYMBOL 3
479/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
480#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000481
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200482struct variable;
483
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000484static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
485
486/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000487 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000488 */
489#if !BB_MMU
490typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200491 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000492 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000493 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000494} nommu_save_t;
495#endif
496
Denys Vlasenko9b782552010-09-08 13:33:26 +0200497enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000498 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000499#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000500 RES_IF ,
501 RES_THEN ,
502 RES_ELIF ,
503 RES_ELSE ,
504 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000505#endif
506#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000507 RES_FOR ,
508 RES_WHILE ,
509 RES_UNTIL ,
510 RES_DO ,
511 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000512#endif
513#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000514 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000515#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000516#if ENABLE_HUSH_CASE
517 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200518 /* three pseudo-keywords support contrived "case" syntax: */
519 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
520 RES_MATCH , /* "word)" */
521 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000522 RES_ESAC ,
523#endif
524 RES_XXXX ,
525 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200526};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000527
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000528typedef struct o_string {
529 char *data;
530 int length; /* position where data is appended */
531 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200532 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000533 /* At least some part of the string was inside '' or "",
534 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200535 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000536 smallint has_empty_slot;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000537} o_string;
538enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200539 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
540 EXP_FLAG_GLOB = 0x2,
541 /* Protect newly added chars against globbing
542 * by prepending \ to *, ?, [, \ */
543 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
544};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000545/* Used for initialization: o_string foo = NULL_O_STRING; */
546#define NULL_O_STRING { NULL }
547
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200548#ifndef debug_printf_parse
549static const char *const assignment_flag[] = {
550 "MAYBE_ASSIGNMENT",
551 "DEFINITELY_ASSIGNMENT",
552 "NOT_ASSIGNMENT",
553 "WORD_IS_KEYWORD",
554};
555#endif
556
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000557typedef struct in_str {
558 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200559 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200560 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000561 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000562} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200564/* The descrip member of this structure is only used to make
565 * debugging output pretty */
566static const struct {
567 int mode;
568 signed char default_fd;
569 char descrip[3];
570} redir_table[] = {
571 { O_RDONLY, 0, "<" },
572 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
573 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
574 { O_CREAT|O_RDWR, 1, "<>" },
575 { O_RDONLY, 0, "<<" },
576/* Should not be needed. Bogus default_fd helps in debugging */
577/* { O_RDONLY, 77, "<<" }, */
578};
579
Eric Andersen25f27032001-04-26 23:22:31 +0000580struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000581 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000582 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000583 int rd_fd; /* fd to redirect */
584 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
585 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000586 smallint rd_type; /* (enum redir_type) */
587 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000588 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200589 * bit 0: do we need to trim leading tabs?
590 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000591 */
Eric Andersen25f27032001-04-26 23:22:31 +0000592};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000593typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200594 REDIRECT_INPUT = 0,
595 REDIRECT_OVERWRITE = 1,
596 REDIRECT_APPEND = 2,
597 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000598 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200599 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000600
601 REDIRFD_CLOSE = -3,
602 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000603 REDIRFD_TO_FILE = -1,
604 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000605
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000606 HEREDOC_SKIPTABS = 1,
607 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000608} redir_type;
609
Eric Andersen25f27032001-04-26 23:22:31 +0000610
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000611struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000612 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200613 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100614#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100615 unsigned lineno;
616#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200617 smallint cmd_type; /* CMD_xxx */
618#define CMD_NORMAL 0
619#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200620#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
621/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
622 * "export v=t*"
623 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200624# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000625#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200626#if ENABLE_HUSH_FUNCTIONS
627# define CMD_FUNCDEF 3
628#endif
629
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100630 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200631 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
632 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000633#if !BB_MMU
634 char *group_as_string;
635#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000636#if ENABLE_HUSH_FUNCTIONS
637 struct function *child_func;
638/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200639 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000640 * When we execute "f1() {a;}" cmd, we create new function and clear
641 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200642 * When we execute "f1() {b;}", we notice that f1 exists,
643 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000644 * we put those fields back into cmd->xxx
645 * (struct function has ->parent_cmd ptr to facilitate that).
646 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
647 * Without this trick, loop would execute a;b;b;b;...
648 * instead of correct sequence a;b;a;b;...
649 * When command is freed, it severs the link
650 * (sets ->child_func->parent_cmd to NULL).
651 */
652#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000653 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000654/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
655 * and on execution these are substituted with their values.
656 * Substitution can make _several_ words out of one argv[n]!
657 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000658 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000659 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660 struct redir_struct *redirects; /* I/O redirections */
661};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000662/* Is there anything in this command at all? */
663#define IS_NULL_CMD(cmd) \
664 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
665
Eric Andersen25f27032001-04-26 23:22:31 +0000666struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000667 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000668 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000669 int alive_cmds; /* number of commands running (not exited) */
670 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000671#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100672 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000673 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000674 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000675#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000676 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000677 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000678 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
679 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000680};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000681typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100682 PIPE_SEQ = 0,
683 PIPE_AND = 1,
684 PIPE_OR = 2,
685 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000686} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000687/* Is there anything in this pipe at all? */
688#define IS_NULL_PIPE(pi) \
689 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000690
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000691/* This holds pointers to the various results of parsing */
692struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000693 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000694 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000695 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000696 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000697 /* last command in pipe (being constructed right now) */
698 struct command *command;
699 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000700 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200701 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000702#if !BB_MMU
703 o_string as_string;
704#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200705 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000706#if HAS_KEYWORDS
707 smallint ctx_res_w;
708 smallint ctx_inverted; /* "! cmd | cmd" */
709#if ENABLE_HUSH_CASE
710 smallint ctx_dsemicolon; /* ";;" seen */
711#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000712 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
713 int old_flag;
714 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000715 * example: "if pipe1; pipe2; then pipe3; fi"
716 * when we see "if" or "then", we malloc and copy current context,
717 * and make ->stack point to it. then we parse pipeN.
718 * when closing "then" / fi" / whatever is found,
719 * we move list_head into ->stack->command->group,
720 * copy ->stack into current context, and delete ->stack.
721 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000722 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000723 struct parse_context *stack;
724#endif
725};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200726enum {
727 MAYBE_ASSIGNMENT = 0,
728 DEFINITELY_ASSIGNMENT = 1,
729 NOT_ASSIGNMENT = 2,
730 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
731 WORD_IS_KEYWORD = 3,
732};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000733
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000734/* On program start, environ points to initial environment.
735 * putenv adds new pointers into it, unsetenv removes them.
736 * Neither of these (de)allocates the strings.
737 * setenv allocates new strings in malloc space and does putenv,
738 * and thus setenv is unusable (leaky) for shell's purposes */
739#define setenv(...) setenv_is_leaky_dont_use()
740struct variable {
741 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000742 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000743 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200744 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000745 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000746 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000747};
748
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000749enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000750 BC_BREAK = 1,
751 BC_CONTINUE = 2,
752};
753
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000754#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000755struct function {
756 struct function *next;
757 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000758 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000759 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200760# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000761 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200762# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000763};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000764#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000765
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000766
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100767/* set -/+o OPT support. (TODO: make it optional)
768 * bash supports the following opts:
769 * allexport off
770 * braceexpand on
771 * emacs on
772 * errexit off
773 * errtrace off
774 * functrace off
775 * hashall on
776 * histexpand off
777 * history on
778 * ignoreeof off
779 * interactive-comments on
780 * keyword off
781 * monitor on
782 * noclobber off
783 * noexec off
784 * noglob off
785 * nolog off
786 * notify off
787 * nounset off
788 * onecmd off
789 * physical off
790 * pipefail off
791 * posix off
792 * privileged off
793 * verbose off
794 * vi off
795 * xtrace off
796 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800797static const char o_opt_strings[] ALIGN1 =
798 "pipefail\0"
799 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200800 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800801#if ENABLE_HUSH_MODE_X
802 "xtrace\0"
803#endif
804 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100805enum {
806 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800807 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200808 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800809#if ENABLE_HUSH_MODE_X
810 OPT_O_XTRACE,
811#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100812 NUM_OPT_O
813};
814
815
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200816struct FILE_list {
817 struct FILE_list *next;
818 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200819 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200820};
821
822
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000823/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000824/* Sorted roughly by size (smaller offsets == smaller code) */
825struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000826 /* interactive_fd != 0 means we are an interactive shell.
827 * If we are, then saved_tty_pgrp can also be != 0, meaning
828 * that controlling tty is available. With saved_tty_pgrp == 0,
829 * job control still works, but terminal signals
830 * (^C, ^Z, ^Y, ^\) won't work at all, and background
831 * process groups can only be created with "cmd &".
832 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
833 * to give tty to the foreground process group,
834 * and will take it back when the group is stopped (^Z)
835 * or killed (^C).
836 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000837#if ENABLE_HUSH_INTERACTIVE
838 /* 'interactive_fd' is a fd# open to ctty, if we have one
839 * _AND_ if we decided to act interactively */
840 int interactive_fd;
841 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200842 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000843# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000844#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000845# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000846#endif
847#if ENABLE_FEATURE_EDITING
848 line_input_t *line_input_state;
849#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000850 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200851 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000852 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200853#if ENABLE_HUSH_RANDOM_SUPPORT
854 random_t random_gen;
855#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000856#if ENABLE_HUSH_JOB
857 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100858 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000859 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000860 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400861# define G_saved_tty_pgrp (G.saved_tty_pgrp)
862#else
863# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000864#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200865 /* How deeply are we in context where "set -e" is ignored */
866 int errexit_depth;
867 /* "set -e" rules (do we follow them correctly?):
868 * Exit if pipe, list, or compound command exits with a non-zero status.
869 * Shell does not exit if failed command is part of condition in
870 * if/while, part of && or || list except the last command, any command
871 * in a pipe but the last, or if the command's return value is being
872 * inverted with !. If a compound command other than a subshell returns a
873 * non-zero status because a command failed while -e was being ignored, the
874 * shell does not exit. A trap on ERR, if set, is executed before the shell
875 * exits [ERR is a bashism].
876 *
877 * If a compound command or function executes in a context where -e is
878 * ignored, none of the commands executed within are affected by the -e
879 * setting. If a compound command or function sets -e while executing in a
880 * context where -e is ignored, that setting does not have any effect until
881 * the compound command or the command containing the function call completes.
882 */
883
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100884 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100885#if ENABLE_HUSH_MODE_X
886# define G_x_mode (G.o_opt[OPT_O_XTRACE])
887#else
888# define G_x_mode 0
889#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200890#if ENABLE_HUSH_INTERACTIVE
891 smallint promptmode; /* 0: PS1, 1: PS2 */
892#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000893 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000894#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000895 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000896#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000897#if ENABLE_HUSH_FUNCTIONS
898 /* 0: outside of a function (or sourced file)
899 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000900 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000901 */
902 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200903# define G_flag_return_in_progress (G.flag_return_in_progress)
904#else
905# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000906#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000907 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200908 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000909 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200910 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200911 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100912#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000913 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000914 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100915# define G_global_args_malloced (G.global_args_malloced)
916#else
917# define G_global_args_malloced 0
918#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000919 /* how many non-NULL argv's we have. NB: $# + 1 */
920 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000921 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000922#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000923 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000924#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000925#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000926 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000927 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000928#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200929#if ENABLE_HUSH_GETOPTS
930 unsigned getopt_count;
931#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000932 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200933 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000934 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200935 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200936 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200937 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200938 unsigned var_nest_level;
939#if ENABLE_HUSH_FUNCTIONS
940# if ENABLE_HUSH_LOCAL
941 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200942# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200943 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000944#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000945 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200946#if ENABLE_HUSH_FAST
947 unsigned count_SIGCHLD;
948 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200949 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200950#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100951#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100952 unsigned lineno;
953 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100954#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200955 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200956 /* Which signals have non-DFL handler (even with no traps set)?
957 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200958 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200959 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200960 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200961 * Other than these two times, never modified.
962 */
963 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200964#if ENABLE_HUSH_JOB
965 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100966# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200967#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200968# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200969#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100970#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000971 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100972# define G_traps G.traps
973#else
974# define G_traps ((char**)NULL)
975#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200976 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100977#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000978 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100979#endif
980#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000981 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000982#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200983 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200984#if ENABLE_FEATURE_EDITING
985 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
986#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000987};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000988#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000989/* Not #defining name to G.name - this quickly gets unwieldy
990 * (too many defines). Also, I actually prefer to see when a variable
991 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000992#define INIT_G() do { \
993 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200994 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
995 sigfillset(&G.sa.sa_mask); \
996 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000997} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000998
999
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001000/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001001static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001002#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001003static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001004#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001005static int builtin_eval(char **argv) FAST_FUNC;
1006static int builtin_exec(char **argv) FAST_FUNC;
1007static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001008#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001009static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001010#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001011#if ENABLE_HUSH_READONLY
1012static int builtin_readonly(char **argv) FAST_FUNC;
1013#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001014#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001015static int builtin_fg_bg(char **argv) FAST_FUNC;
1016static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001017#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001018#if ENABLE_HUSH_GETOPTS
1019static int builtin_getopts(char **argv) FAST_FUNC;
1020#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001021#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001022static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001023#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001024#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001025static int builtin_history(char **argv) FAST_FUNC;
1026#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001027#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001028static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001029#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001030#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001031static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001032#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001033#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001034static int builtin_printf(char **argv) FAST_FUNC;
1035#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001036static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001037#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001038static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001039#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001040#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001041static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001042#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001043static int builtin_shift(char **argv) FAST_FUNC;
1044static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001045#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001046static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001047#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001048#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001049static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001050#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001051#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001052static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001053#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001054#if ENABLE_HUSH_TIMES
1055static int builtin_times(char **argv) FAST_FUNC;
1056#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001057static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001058#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001060#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001061#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001062static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001063#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001064#if ENABLE_HUSH_KILL
1065static int builtin_kill(char **argv) FAST_FUNC;
1066#endif
1067#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001068static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001069#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001070#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001071static int builtin_break(char **argv) FAST_FUNC;
1072static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001073#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001074#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001075static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001076#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001077
1078/* Table of built-in functions. They can be forked or not, depending on
1079 * context: within pipes, they fork. As simple commands, they do not.
1080 * When used in non-forking context, they can change global variables
1081 * in the parent shell process. If forked, of course they cannot.
1082 * For example, 'unset foo | whatever' will parse and run, but foo will
1083 * still be set at the end. */
1084struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001085 const char *b_cmd;
1086 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001087#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001088 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001089# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001090#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001091# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001092#endif
1093};
1094
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001095static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001096 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001097 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001098#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001099 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001100#endif
1101#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001102 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001103#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001104 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001105#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001106 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001107#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001108 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1109 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001110 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001111#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001112 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001113#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001114#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001115 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001116#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001117#if ENABLE_HUSH_GETOPTS
1118 BLTIN("getopts" , builtin_getopts , NULL),
1119#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001120#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001121 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001122#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001123#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001124 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001125#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001126#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001127 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001128#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001129#if ENABLE_HUSH_KILL
1130 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1131#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001132#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001133 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001134#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001135#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001136 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001137#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001138#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001139 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001140#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001141#if ENABLE_HUSH_READONLY
1142 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1143#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001144#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001145 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001146#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001147#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001148 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001149#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001150 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001151#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001152 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001153#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001154#if ENABLE_HUSH_TIMES
1155 BLTIN("times" , builtin_times , NULL),
1156#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001157#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001158 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001159#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001160 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001161#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001162 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001163#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001164#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001165 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001166#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001167#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001168 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001169#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001170#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001171 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001172#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001173#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001174 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001175#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001176};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001177/* These builtins won't be used if we are on NOMMU and need to re-exec
1178 * (it's cheaper to run an external program in this case):
1179 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001180static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001181#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001182 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001183#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001184#if BASH_TEST2
1185 BLTIN("[[" , builtin_test , NULL),
1186#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001187#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001188 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001189#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001190#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001191 BLTIN("printf" , builtin_printf , NULL),
1192#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001193 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001194#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001195 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001196#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001197};
1198
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001199
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001200/* Debug printouts.
1201 */
1202#if HUSH_DEBUG
1203/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001204# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001205# define debug_enter() (G.debug_indent++)
1206# define debug_leave() (G.debug_indent--)
1207#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001208# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001209# define debug_enter() ((void)0)
1210# define debug_leave() ((void)0)
1211#endif
1212
1213#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001214# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001215#endif
1216
1217#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001218# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001219#endif
1220
1221#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001222#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001223#endif
1224
1225#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001226# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001227#endif
1228
1229#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001230# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001231# define DEBUG_JOBS 1
1232#else
1233# define DEBUG_JOBS 0
1234#endif
1235
1236#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001237# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001238# define DEBUG_EXPAND 1
1239#else
1240# define DEBUG_EXPAND 0
1241#endif
1242
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001243#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001244# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001245#endif
1246
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001247#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001248# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001249# define DEBUG_GLOB 1
1250#else
1251# define DEBUG_GLOB 0
1252#endif
1253
Denys Vlasenko2db74612017-07-07 22:07:28 +02001254#ifndef debug_printf_redir
1255# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1256#endif
1257
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001259# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001260#endif
1261
1262#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001263# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001264#endif
1265
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001266#ifndef debug_printf_prompt
1267# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1268#endif
1269
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001270#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001271# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001272# define DEBUG_CLEAN 1
1273#else
1274# define DEBUG_CLEAN 0
1275#endif
1276
1277#if DEBUG_EXPAND
1278static void debug_print_strings(const char *prefix, char **vv)
1279{
1280 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001281 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001282 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001283 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001284}
1285#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001286# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001287#endif
1288
1289
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001290/* Leak hunting. Use hush_leaktool.sh for post-processing.
1291 */
1292#if LEAK_HUNTING
1293static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001294{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001295 void *ptr = xmalloc((size + 0xff) & ~0xff);
1296 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1297 return ptr;
1298}
1299static void *xxrealloc(int lineno, void *ptr, size_t size)
1300{
1301 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1302 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1303 return ptr;
1304}
1305static char *xxstrdup(int lineno, const char *str)
1306{
1307 char *ptr = xstrdup(str);
1308 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1309 return ptr;
1310}
1311static void xxfree(void *ptr)
1312{
1313 fdprintf(2, "free %p\n", ptr);
1314 free(ptr);
1315}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001316# define xmalloc(s) xxmalloc(__LINE__, s)
1317# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1318# define xstrdup(s) xxstrdup(__LINE__, s)
1319# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001320#endif
1321
1322
1323/* Syntax and runtime errors. They always abort scripts.
1324 * In interactive use they usually discard unparsed and/or unexecuted commands
1325 * and return to the prompt.
1326 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1327 */
1328#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001329# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001330# define syntax_error(lineno, msg) syntax_error(msg)
1331# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1332# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1333# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1334# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001335#endif
1336
Denys Vlasenko39701202017-08-02 19:44:05 +02001337static void die_if_script(void)
1338{
1339 if (!G_interactive_fd) {
1340 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1341 xfunc_error_retval = G.last_exitcode;
1342 xfunc_die();
1343 }
1344}
1345
1346static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001347{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001348 va_list p;
1349
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001350#if HUSH_DEBUG >= 2
1351 bb_error_msg("hush.c:%u", lineno);
1352#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001353 va_start(p, fmt);
1354 bb_verror_msg(fmt, p, NULL);
1355 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001356 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001357}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001358
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001359static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001360{
1361 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001362 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001363 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001364 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001365 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001366}
1367
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001368static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001369{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001370 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001371 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001372}
1373
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001374static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001375{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001376 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001377//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1378// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001379}
1380
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001381static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001382{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001383 char msg[2] = { ch, '\0' };
1384 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001385}
1386
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001387static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001388{
1389 char msg[2];
1390 msg[0] = ch;
1391 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001392#if HUSH_DEBUG >= 2
1393 bb_error_msg("hush.c:%u", lineno);
1394#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001395 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001396 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001397}
1398
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001399#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001400# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001401# undef syntax_error
1402# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001403# undef syntax_error_unterm_ch
1404# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001405# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001406#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001407# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001408# define syntax_error(msg) syntax_error(__LINE__, msg)
1409# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1410# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1411# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1412# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001413#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001414
Denis Vlasenko552433b2009-04-04 19:29:21 +00001415
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001416#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001417static void cmdedit_update_prompt(void);
1418#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001419# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001420#endif
1421
1422
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001423/* Utility functions
1424 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001425/* Replace each \x with x in place, return ptr past NUL. */
1426static char *unbackslash(char *src)
1427{
Denys Vlasenko71885402009-09-24 01:44:13 +02001428 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001429 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001430 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001431 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001432 if (*src != '\0') {
1433 /* \x -> x */
1434 *dst++ = *src++;
1435 continue;
1436 }
1437 /* else: "\<nul>". Do not delete this backslash.
1438 * Testcase: eval 'echo ok\'
1439 */
1440 *dst++ = '\\';
1441 /* fallthrough */
1442 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001443 if ((*dst++ = *src++) == '\0')
1444 break;
1445 }
1446 return dst;
1447}
1448
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001449static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001450{
1451 int i;
1452 unsigned count1;
1453 unsigned count2;
1454 char **v;
1455
1456 v = strings;
1457 count1 = 0;
1458 if (v) {
1459 while (*v) {
1460 count1++;
1461 v++;
1462 }
1463 }
1464 count2 = 0;
1465 v = add;
1466 while (*v) {
1467 count2++;
1468 v++;
1469 }
1470 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1471 v[count1 + count2] = NULL;
1472 i = count2;
1473 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001474 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001475 return v;
1476}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001477#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001478static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1479{
1480 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1481 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1482 return ptr;
1483}
1484#define add_strings_to_strings(strings, add, need_to_dup) \
1485 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1486#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001487
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001488/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001489static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001490{
1491 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001492 v[0] = add;
1493 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001494 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001495}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001496#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001497static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1498{
1499 char **ptr = add_string_to_strings(strings, add);
1500 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1501 return ptr;
1502}
1503#define add_string_to_strings(strings, add) \
1504 xx_add_string_to_strings(__LINE__, strings, add)
1505#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001506
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001507static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001508{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001509 char **v;
1510
1511 if (!strings)
1512 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001513 v = strings;
1514 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001515 free(*v);
1516 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001517 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001518 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001519}
1520
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001521static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001522{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001523 int newfd;
1524 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001525 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1526 if (newfd >= 0) {
1527 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1528 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1529 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001530 if (errno == EBUSY)
1531 goto repeat;
1532 if (errno == EINTR)
1533 goto repeat;
1534 }
1535 return newfd;
1536}
1537
Denys Vlasenko657e9002017-07-30 23:34:04 +02001538static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001539{
1540 int newfd;
1541 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001542 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001543 if (newfd < 0) {
1544 if (errno == EBUSY)
1545 goto repeat;
1546 if (errno == EINTR)
1547 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001548 /* fd was not open? */
1549 if (errno == EBADF)
1550 return fd;
1551 xfunc_die();
1552 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001553 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1554 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001555 close(fd);
1556 return newfd;
1557}
1558
1559
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001560/* Manipulating the list of open FILEs */
1561static FILE *remember_FILE(FILE *fp)
1562{
1563 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001564 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001565 n->next = G.FILE_list;
1566 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001567 n->fp = fp;
1568 n->fd = fileno(fp);
1569 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001570 }
1571 return fp;
1572}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001573static void fclose_and_forget(FILE *fp)
1574{
1575 struct FILE_list **pp = &G.FILE_list;
1576 while (*pp) {
1577 struct FILE_list *cur = *pp;
1578 if (cur->fp == fp) {
1579 *pp = cur->next;
1580 free(cur);
1581 break;
1582 }
1583 pp = &cur->next;
1584 }
1585 fclose(fp);
1586}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001587static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001588{
1589 struct FILE_list *fl = G.FILE_list;
1590 while (fl) {
1591 if (fd == fl->fd) {
1592 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001593 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001594 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001595 return 1;
1596 }
1597 fl = fl->next;
1598 }
1599 return 0;
1600}
1601static void restore_redirected_FILEs(void)
1602{
1603 struct FILE_list *fl = G.FILE_list;
1604 while (fl) {
1605 int should_be = fileno(fl->fp);
1606 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001607 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001608 xmove_fd(fl->fd, should_be);
1609 fl->fd = should_be;
1610 }
1611 fl = fl->next;
1612 }
1613}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001614#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001615static void close_all_FILE_list(void)
1616{
1617 struct FILE_list *fl = G.FILE_list;
1618 while (fl) {
1619 /* fclose would also free FILE object.
1620 * It is disastrous if we share memory with a vforked parent.
1621 * I'm not sure we never come here after vfork.
1622 * Therefore just close fd, nothing more.
1623 */
1624 /*fclose(fl->fp); - unsafe */
1625 close(fl->fd);
1626 fl = fl->next;
1627 }
1628}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001629#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001630static int fd_in_FILEs(int fd)
1631{
1632 struct FILE_list *fl = G.FILE_list;
1633 while (fl) {
1634 if (fl->fd == fd)
1635 return 1;
1636 fl = fl->next;
1637 }
1638 return 0;
1639}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001640
1641
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001642/* Helpers for setting new $n and restoring them back
1643 */
1644typedef struct save_arg_t {
1645 char *sv_argv0;
1646 char **sv_g_argv;
1647 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001648 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001649} save_arg_t;
1650
1651static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1652{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001653 sv->sv_argv0 = argv[0];
1654 sv->sv_g_argv = G.global_argv;
1655 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001656 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001657
1658 argv[0] = G.global_argv[0]; /* retain $0 */
1659 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001660 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001661
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001662 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001663}
1664
1665static void restore_G_args(save_arg_t *sv, char **argv)
1666{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001667#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001668 if (G.global_args_malloced) {
1669 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001670 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001671 while (*++pp) /* note: does not free $0 */
1672 free(*pp);
1673 free(G.global_argv);
1674 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001675#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001676 argv[0] = sv->sv_argv0;
1677 G.global_argv = sv->sv_g_argv;
1678 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001679 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001680}
1681
1682
Denis Vlasenkod5762932009-03-31 11:22:57 +00001683/* Basic theory of signal handling in shell
1684 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001685 * This does not describe what hush does, rather, it is current understanding
1686 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001687 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1688 *
1689 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1690 * is finished or backgrounded. It is the same in interactive and
1691 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001692 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001693 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001694 * backgrounds (i.e. stops) or kills all members of currently running
1695 * pipe.
1696 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001697 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001698 * or by SIGINT in interactive shell.
1699 *
1700 * Trap handlers will execute even within trap handlers. (right?)
1701 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001702 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1703 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001704 *
1705 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001706 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001707 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001708 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001709 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001710 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001711 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001712 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001713 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001714 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001715 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001716 *
1717 * SIGQUIT: ignore
1718 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001719 * SIGHUP (interactive):
1720 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001721 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001722 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1723 * that all pipe members are stopped. Try this in bash:
1724 * while :; do :; done - ^Z does not background it
1725 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001726 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001727 * of the command line, show prompt. NB: ^C does not send SIGINT
1728 * to interactive shell while shell is waiting for a pipe,
1729 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001730 * Example 1: this waits 5 sec, but does not execute ls:
1731 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1732 * Example 2: this does not wait and does not execute ls:
1733 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1734 * Example 3: this does not wait 5 sec, but executes ls:
1735 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001736 * Example 4: this does not wait and does not execute ls:
1737 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001738 *
1739 * (What happens to signals which are IGN on shell start?)
1740 * (What happens with signal mask on shell start?)
1741 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001742 * Old implementation
1743 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001744 * We use in-kernel pending signal mask to determine which signals were sent.
1745 * We block all signals which we don't want to take action immediately,
1746 * i.e. we block all signals which need to have special handling as described
1747 * above, and all signals which have traps set.
1748 * After each pipe execution, we extract any pending signals via sigtimedwait()
1749 * and act on them.
1750 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001751 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001752 * sigset_t blocked_set: current blocked signal set
1753 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001754 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001755 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001756 * "trap 'cmd' SIGxxx":
1757 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001758 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001759 * unblock signals with special interactive handling
1760 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001761 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001762 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001763 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001764 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001765 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001766 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001767 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001768 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001769 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001770 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001771 * Standard says "When a subshell is entered, traps that are not being ignored
1772 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001773 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001774 *
1775 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001776 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001777 * masked signals are not visible!
1778 *
1779 * New implementation
1780 * ==================
1781 * We record each signal we are interested in by installing signal handler
1782 * for them - a bit like emulating kernel pending signal mask in userspace.
1783 * We are interested in: signals which need to have special handling
1784 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001785 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001786 * After each pipe execution, we extract any pending signals
1787 * and act on them.
1788 *
1789 * unsigned special_sig_mask: a mask of shell-special signals.
1790 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1791 * char *traps[sig] if trap for sig is set (even if it's '').
1792 * sigset_t pending_set: set of sigs we received.
1793 *
1794 * "trap - SIGxxx":
1795 * if sig is in special_sig_mask, set handler back to:
1796 * record_pending_signo, or to IGN if it's a tty stop signal
1797 * if sig is in fatal_sig_mask, set handler back to sigexit.
1798 * else: set handler back to SIG_DFL
1799 * "trap 'cmd' SIGxxx":
1800 * set handler to record_pending_signo.
1801 * "trap '' SIGxxx":
1802 * set handler to SIG_IGN.
1803 * after [v]fork, if we plan to be a shell:
1804 * set signals with special interactive handling to SIG_DFL
1805 * (because child shell is not interactive),
1806 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1807 * after [v]fork, if we plan to exec:
1808 * POSIX says fork clears pending signal mask in child - no need to clear it.
1809 *
1810 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1811 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1812 *
1813 * Note (compat):
1814 * Standard says "When a subshell is entered, traps that are not being ignored
1815 * are set to the default actions". bash interprets it so that traps which
1816 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001817 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001818enum {
1819 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001820 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001821 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001822 | (1 << SIGHUP)
1823 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001824 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001825#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001826 | (1 << SIGTTIN)
1827 | (1 << SIGTTOU)
1828 | (1 << SIGTSTP)
1829#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001830 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001831};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001832
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001833static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001834{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001835 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001836#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001837 if (sig == SIGCHLD) {
1838 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001839//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 +02001840 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001841#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001842}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001843
Denys Vlasenko0806e402011-05-12 23:06:20 +02001844static sighandler_t install_sighandler(int sig, sighandler_t handler)
1845{
1846 struct sigaction old_sa;
1847
1848 /* We could use signal() to install handlers... almost:
1849 * except that we need to mask ALL signals while handlers run.
1850 * I saw signal nesting in strace, race window isn't small.
1851 * SA_RESTART is also needed, but in Linux, signal()
1852 * sets SA_RESTART too.
1853 */
1854 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1855 /* sigfillset(&G.sa.sa_mask); - already done */
1856 /* G.sa.sa_flags = SA_RESTART; - already done */
1857 G.sa.sa_handler = handler;
1858 sigaction(sig, &G.sa, &old_sa);
1859 return old_sa.sa_handler;
1860}
1861
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001862static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001863
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001864static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001865static void restore_ttypgrp_and__exit(void)
1866{
1867 /* xfunc has failed! die die die */
1868 /* no EXIT traps, this is an escape hatch! */
1869 G.exiting = 1;
1870 hush_exit(xfunc_error_retval);
1871}
1872
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001873#if ENABLE_HUSH_JOB
1874
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001875/* Needed only on some libc:
1876 * It was observed that on exit(), fgetc'ed buffered data
1877 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1878 * With the net effect that even after fork(), not vfork(),
1879 * exit() in NOEXECed applet in "sh SCRIPT":
1880 * noexec_applet_here
1881 * echo END_OF_SCRIPT
1882 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1883 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001884 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001885 * and in `cmd` handling.
1886 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1887 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001888static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001889static void fflush_and__exit(void)
1890{
1891 fflush_all();
1892 _exit(xfunc_error_retval);
1893}
1894
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001895/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001896# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001897/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001898# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001899
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001900/* Restores tty foreground process group, and exits.
1901 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001902 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001903 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001904 * We also call it if xfunc is exiting.
1905 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001906static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001907static void sigexit(int sig)
1908{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001909 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001910 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001911 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1912 /* Disable all signals: job control, SIGPIPE, etc.
1913 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1914 */
1915 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001916 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001917 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001918
1919 /* Not a signal, just exit */
1920 if (sig <= 0)
1921 _exit(- sig);
1922
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001923 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001924}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001925#else
1926
Denys Vlasenko8391c482010-05-22 17:50:43 +02001927# define disable_restore_tty_pgrp_on_exit() ((void)0)
1928# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001929
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001930#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001931
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001932static sighandler_t pick_sighandler(unsigned sig)
1933{
1934 sighandler_t handler = SIG_DFL;
1935 if (sig < sizeof(unsigned)*8) {
1936 unsigned sigmask = (1 << sig);
1937
1938#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001939 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001940 if (G_fatal_sig_mask & sigmask)
1941 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001942 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001943#endif
1944 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001945 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001946 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001947 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001948 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001949 * in an endless loop when we try to do some
1950 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001951 */
1952 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1953 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001954 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001955 }
1956 return handler;
1957}
1958
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001959/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001960static void hush_exit(int exitcode)
1961{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001962#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1963 save_history(G.line_input_state);
1964#endif
1965
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001966 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001967 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001968 char *argv[3];
1969 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001970 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001971 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001972 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001973 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001974 * "trap" will still show it, if executed
1975 * in the handler */
1976 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001977 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001978
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001979#if ENABLE_FEATURE_CLEAN_UP
1980 {
1981 struct variable *cur_var;
1982 if (G.cwd != bb_msg_unknown)
1983 free((char*)G.cwd);
1984 cur_var = G.top_var;
1985 while (cur_var) {
1986 struct variable *tmp = cur_var;
1987 if (!cur_var->max_len)
1988 free(cur_var->varstr);
1989 cur_var = cur_var->next;
1990 free(tmp);
1991 }
1992 }
1993#endif
1994
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001995 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001996#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001997 sigexit(- (exitcode & 0xff));
1998#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001999 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002000#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002001}
2002
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002003
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002004//TODO: return a mask of ALL handled sigs?
2005static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002006{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002007 int last_sig = 0;
2008
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002009 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002010 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002011
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002012 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002013 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002014 sig = 0;
2015 do {
2016 sig++;
2017 if (sigismember(&G.pending_set, sig)) {
2018 sigdelset(&G.pending_set, sig);
2019 goto got_sig;
2020 }
2021 } while (sig < NSIG);
2022 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002023 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002024 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002025 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002026 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002027 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002028 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002029 char *argv[3];
2030 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002031 argv[1] = xstrdup(G_traps[sig]);
2032 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002033 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002034 save_rcode = G.last_exitcode;
2035 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002036 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002037//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002038 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002039 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002040 } /* else: "" trap, ignoring signal */
2041 continue;
2042 }
2043 /* not a trap: special action */
2044 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002045 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002046 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002047 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002048 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002049 break;
2050#if ENABLE_HUSH_JOB
2051 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002052//TODO: why are we doing this? ash and dash don't do this,
2053//they have no handler for SIGHUP at all,
2054//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002055 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002056 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002057 /* bash is observed to signal whole process groups,
2058 * not individual processes */
2059 for (job = G.job_list; job; job = job->next) {
2060 if (job->pgrp <= 0)
2061 continue;
2062 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2063 if (kill(- job->pgrp, SIGHUP) == 0)
2064 kill(- job->pgrp, SIGCONT);
2065 }
2066 sigexit(SIGHUP);
2067 }
2068#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002069#if ENABLE_HUSH_FAST
2070 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002071 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002072 G.count_SIGCHLD++;
2073//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2074 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002075 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002076 * This simplifies wait builtin a bit.
2077 */
2078 break;
2079#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002080 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002081 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002082 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002083 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002084 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002085 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002086 * in interactive shell, because TERM is ignored.
2087 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002088 break;
2089 }
2090 }
2091 return last_sig;
2092}
2093
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002094
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002095static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002096{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002097 if (force || G.cwd == NULL) {
2098 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2099 * we must not try to free(bb_msg_unknown) */
2100 if (G.cwd == bb_msg_unknown)
2101 G.cwd = NULL;
2102 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2103 if (!G.cwd)
2104 G.cwd = bb_msg_unknown;
2105 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002106 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002107}
2108
Denis Vlasenko83506862007-11-23 13:11:42 +00002109
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002110/*
2111 * Shell and environment variable support
2112 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002113static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002114{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002115 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002116 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002117
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002118 pp = &G.top_var;
2119 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002120 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002121 return pp;
2122 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002123 }
2124 return NULL;
2125}
2126
Denys Vlasenko03dad222010-01-12 23:29:57 +01002127static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002128{
Denys Vlasenko29082232010-07-16 13:52:32 +02002129 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002130 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002131
2132 if (G.expanded_assignments) {
2133 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002134 while (*cpp) {
2135 char *cp = *cpp;
2136 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2137 return cp + len + 1;
2138 cpp++;
2139 }
2140 }
2141
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002142 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002143 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002144 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002145
Denys Vlasenkodea47882009-10-09 15:40:49 +02002146 if (strcmp(name, "PPID") == 0)
2147 return utoa(G.root_ppid);
2148 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002149#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002150 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002151 return utoa(next_random(&G.random_gen));
2152#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002153 return NULL;
2154}
2155
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002156static void handle_changed_special_names(const char *name, unsigned name_len)
2157{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002158 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2159 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2160 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002161 cmdedit_update_prompt();
2162 return;
2163 }
2164
2165 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2166 && name_len == 6
2167 ) {
2168#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002169 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002170 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002171 return;
2172 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002173#endif
2174#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002175 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002176 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002177 return;
2178 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002179#endif
2180 }
2181}
2182
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002183/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002184 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002185 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002186#define SETFLAG_EXPORT (1 << 0)
2187#define SETFLAG_UNEXPORT (1 << 1)
2188#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002189#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002190static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002191{
Denys Vlasenko61407802018-04-04 21:14:28 +02002192 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002193 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002194 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002195 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002196 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002197 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002198
Denis Vlasenko950bd722009-04-21 11:23:56 +00002199 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002200 if (HUSH_DEBUG && !eq_sign)
2201 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202
Denis Vlasenko950bd722009-04-21 11:23:56 +00002203 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002204 cur_pp = &G.top_var;
2205 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002206 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002207 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002208 continue;
2209 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002210
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002211 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002212 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002213 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002214 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002215//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2216//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002217 return -1;
2218 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002219 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002220 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2221 *eq_sign = '\0';
2222 unsetenv(str);
2223 *eq_sign = '=';
2224 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002225 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002226 /* bash 3.2.33(1) and exported vars:
2227 * # export z=z
2228 * # f() { local z=a; env | grep ^z; }
2229 * # f
2230 * z=a
2231 * # env | grep ^z
2232 * z=z
2233 */
2234 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002235 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002236 /* New variable is local ("local VAR=VAL" or
2237 * "VAR=VAL cmd")
2238 * and existing one is global, or local
2239 * on a lower level that new one.
2240 * Remove it from global variable list:
2241 */
2242 *cur_pp = cur->next;
2243 if (G.shadowed_vars_pp) {
2244 /* Save in "shadowed" list */
2245 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2246 cur->flg_export ? "exported " : "",
2247 cur->varstr, cur->var_nest_level, str, local_lvl
2248 );
2249 cur->next = *G.shadowed_vars_pp;
2250 *G.shadowed_vars_pp = cur;
2251 } else {
2252 /* Came from pseudo_exec_argv(), no need to save: delete it */
2253 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2254 cur->flg_export ? "exported " : "",
2255 cur->varstr, cur->var_nest_level, str, local_lvl
2256 );
2257 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2258 free_me = cur->varstr; /* then free it later */
2259 free(cur);
2260 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002261 break;
2262 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002263
Denis Vlasenko950bd722009-04-21 11:23:56 +00002264 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002265 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266 free_and_exp:
2267 free(str);
2268 goto exp;
2269 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002270
2271 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002272 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002273 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002274 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002275 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002276 strcpy(cur->varstr, str);
2277 goto free_and_exp;
2278 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002279 /* Can't reuse */
2280 cur->max_len = 0;
2281 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002282 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002283 /* max_len == 0 signifies "malloced" var, which we can
2284 * (and have to) free. But we can't free(cur->varstr) here:
2285 * if cur->flg_export is 1, it is in the environment.
2286 * We should either unsetenv+free, or wait until putenv,
2287 * then putenv(new)+free(old).
2288 */
2289 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002290 goto set_str_and_exp;
2291 }
2292
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002293 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002294 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002295 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002296 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002297 cur->next = *cur_pp;
2298 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002299
2300 set_str_and_exp:
2301 cur->varstr = str;
2302 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002303#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002304 if (flags & SETFLAG_MAKE_RO) {
2305 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002306 }
2307#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002308 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002309 cur->flg_export = 1;
2310 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002311 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002312 cur->flg_export = 0;
2313 /* unsetenv was already done */
2314 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002315 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002316 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002317 i = putenv(cur->varstr);
2318 /* only now we can free old exported malloced string */
2319 free(free_me);
2320 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002321 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002322 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002323 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002324
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002325 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002326
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002327 return 0;
2328}
2329
Denys Vlasenko6db47842009-09-05 20:15:17 +02002330/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002331static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002332{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002333 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002334}
2335
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002336#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002337static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002338{
2339 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002340 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002341
Denys Vlasenko61407802018-04-04 21:14:28 +02002342 cur_pp = &G.top_var;
2343 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002344 if (strncmp(cur->varstr, name, name_len) == 0
2345 && cur->varstr[name_len] == '='
2346 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002347 if (cur->flg_read_only) {
2348 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002349 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002350 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002351
Denys Vlasenko61407802018-04-04 21:14:28 +02002352 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002353 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2354 bb_unsetenv(cur->varstr);
2355 if (!cur->max_len)
2356 free(cur->varstr);
2357 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002358
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002359 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002360 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002361 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002362 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002363
2364 /* Handle "unset PS1" et al even if did not find the variable to unset */
2365 handle_changed_special_names(name, name_len);
2366
Mike Frysingerd690f682009-03-30 06:50:54 +00002367 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002368}
2369
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002370static int unset_local_var(const char *name)
2371{
2372 return unset_local_var_len(name, strlen(name));
2373}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002374#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002375
Denys Vlasenkob2b14cb2018-06-26 18:09:22 +02002376#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2377 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002378static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002379{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002380 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002381 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002382}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002383#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002384
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002385
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002386/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002387 * Helpers for "var1=val1 var2=val2 cmd" feature
2388 */
2389static void add_vars(struct variable *var)
2390{
2391 struct variable *next;
2392
2393 while (var) {
2394 next = var->next;
2395 var->next = G.top_var;
2396 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002397 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002398 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002399 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002400 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002401 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002402 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002403 var = next;
2404 }
2405}
2406
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002407/* We put strings[i] into variable table and possibly putenv them.
2408 * If variable is read only, we can free the strings[i]
2409 * which attempts to overwrite it.
2410 * The strings[] vector itself is freed.
2411 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002412static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002413{
2414 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002415
2416 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002417 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002418
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002419 s = strings;
2420 while (*s) {
2421 struct variable *var_p;
2422 struct variable **var_pp;
2423 char *eq;
2424
2425 eq = strchr(*s, '=');
2426 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002427 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002428 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002429 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002430 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002431 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002432 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002433 /*
2434 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2435 * If VAR is readonly, leaving it in the list
2436 * after asssignment error (msg above)
2437 * causes doubled error message later, on unset.
2438 */
2439 debug_printf_env("removing/freeing '%s' element\n", *s);
2440 free(*s);
2441 p = s;
2442 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002443 goto next;
2444 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002445 /* below, set_local_var() with nest level will
2446 * "shadow" (remove) this variable from
2447 * global linked list.
2448 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002449 }
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002450 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002451 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2452 } else if (HUSH_DEBUG) {
2453 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002454 }
2455 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002456 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002457 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002458 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002459}
2460
2461
2462/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002463 * Unicode helper
2464 */
2465static void reinit_unicode_for_hush(void)
2466{
2467 /* Unicode support should be activated even if LANG is set
2468 * _during_ shell execution, not only if it was set when
2469 * shell was started. Therefore, re-check LANG every time:
2470 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002471 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2472 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002473 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002474 const char *s = get_local_var_value("LC_ALL");
2475 if (!s) s = get_local_var_value("LC_CTYPE");
2476 if (!s) s = get_local_var_value("LANG");
2477 reinit_unicode(s);
2478 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002479}
2480
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002481/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002482 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002484
2485#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002486/* To test correct lineedit/interactive behavior, type from command line:
2487 * echo $P\
2488 * \
2489 * AT\
2490 * H\
2491 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002492 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002493 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002494# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002495static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002496{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002497 G.PS1 = get_local_var_value("PS1");
2498 if (G.PS1 == NULL)
2499 G.PS1 = "";
2500 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002501 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002502 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002503}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002504# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002505static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002506{
2507 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002508
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002509 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002510
2511 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2512 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002513 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002514 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2515 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002516 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002517 /* bash uses $PWD value, even if it is set by user.
2518 * It uses current dir only if PWD is unset.
2519 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002520 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002521 }
2522 prompt_str = G.PS1;
2523 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002524 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002525 return prompt_str;
2526}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002527static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002528{
2529 int r;
2530 const char *prompt_str;
2531
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002532 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002533# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002534 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002535 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002536 if (G.flag_SIGINT) {
2537 /* There was ^C'ed, make it look prettier: */
2538 bb_putchar('\n');
2539 G.flag_SIGINT = 0;
2540 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002541 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002542 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002543 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002544 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002545 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002546 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002547 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002548 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002549 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002550 if (r != 0 && !G.flag_SIGINT)
2551 break;
2552 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002553 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2554 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002555 G.last_exitcode = 128 + SIGINT;
2556 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002557 if (r < 0) {
2558 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002559 i->p = NULL;
2560 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002561 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002562 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002563 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002564 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002565# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002566 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002567 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002568 if (i->last_char == '\0' || i->last_char == '\n') {
2569 /* Why check_and_run_traps here? Try this interactively:
2570 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2571 * $ <[enter], repeatedly...>
2572 * Without check_and_run_traps, handler never runs.
2573 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002574 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002575 fputs(prompt_str, stdout);
2576 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002577 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002578//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002579 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002580 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2581 * no ^C masking happens during fgetc, no special code for ^C:
2582 * it generates SIGINT as usual.
2583 */
2584 check_and_run_traps();
2585 if (G.flag_SIGINT)
2586 G.last_exitcode = 128 + SIGINT;
2587 if (r != '\0')
2588 break;
2589 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002590 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002591# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002592}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002593/* This is the magic location that prints prompts
2594 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002595static int fgetc_interactive(struct in_str *i)
2596{
2597 int ch;
2598 /* If it's interactive stdin, get new line. */
2599 if (G_interactive_fd && i->file == stdin) {
2600 /* Returns first char (or EOF), the rest is in i->p[] */
2601 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002602 G.promptmode = 1; /* PS2 */
2603 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002604 } else {
2605 /* Not stdin: script file, sourced file, etc */
2606 do ch = fgetc(i->file); while (ch == '\0');
2607 }
2608 return ch;
2609}
2610#else
2611static inline int fgetc_interactive(struct in_str *i)
2612{
2613 int ch;
2614 do ch = fgetc(i->file); while (ch == '\0');
2615 return ch;
2616}
2617#endif /* INTERACTIVE */
2618
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002619static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002620{
2621 int ch;
2622
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002623 if (!i->file) {
2624 /* string-based in_str */
2625 ch = (unsigned char)*i->p;
2626 if (ch != '\0') {
2627 i->p++;
2628 i->last_char = ch;
2629 return ch;
2630 }
2631 return EOF;
2632 }
2633
2634 /* FILE-based in_str */
2635
Denys Vlasenko4074d492016-09-30 01:49:53 +02002636#if ENABLE_FEATURE_EDITING
2637 /* This can be stdin, check line editing char[] buffer */
2638 if (i->p && *i->p != '\0') {
2639 ch = (unsigned char)*i->p++;
2640 goto out;
2641 }
2642#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002643 /* peek_buf[] is an int array, not char. Can contain EOF. */
2644 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002645 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002646 int ch2 = i->peek_buf[1];
2647 i->peek_buf[0] = ch2;
2648 if (ch2 == 0) /* very likely, avoid redundant write */
2649 goto out;
2650 i->peek_buf[1] = 0;
2651 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002652 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002653
Denys Vlasenko4074d492016-09-30 01:49:53 +02002654 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002655 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002656 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002657 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002658#if ENABLE_HUSH_LINENO_VAR
2659 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002660 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002661 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2662 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002663#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002664 return ch;
2665}
2666
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002667static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002668{
2669 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002670
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002671 if (!i->file) {
2672 /* string-based in_str */
2673 /* Doesn't report EOF on NUL. None of the callers care. */
2674 return (unsigned char)*i->p;
2675 }
2676
2677 /* FILE-based in_str */
2678
Denys Vlasenko4074d492016-09-30 01:49:53 +02002679#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002680 /* This can be stdin, check line editing char[] buffer */
2681 if (i->p && *i->p != '\0')
2682 return (unsigned char)*i->p;
2683#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002684 /* peek_buf[] is an int array, not char. Can contain EOF. */
2685 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002686 if (ch != 0)
2687 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002688
Denys Vlasenko4074d492016-09-30 01:49:53 +02002689 /* Need to get a new char */
2690 ch = fgetc_interactive(i);
2691 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2692
2693 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2694#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2695 if (i->p) {
2696 i->p -= 1;
2697 return ch;
2698 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002699#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002700 i->peek_buf[0] = ch;
2701 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002702 return ch;
2703}
2704
Denys Vlasenko4074d492016-09-30 01:49:53 +02002705/* Only ever called if i_peek() was called, and did not return EOF.
2706 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2707 * not end-of-line. Therefore we never need to read a new editing line here.
2708 */
2709static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002710{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002711 int ch;
2712
2713 /* There are two cases when i->p[] buffer exists.
2714 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002715 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002716 * In both cases, we know that i->p[0] exists and not NUL, and
2717 * the peek2 result is in i->p[1].
2718 */
2719 if (i->p)
2720 return (unsigned char)i->p[1];
2721
2722 /* Now we know it is a file-based in_str. */
2723
2724 /* peek_buf[] is an int array, not char. Can contain EOF. */
2725 /* Is there 2nd char? */
2726 ch = i->peek_buf[1];
2727 if (ch == 0) {
2728 /* We did not read it yet, get it now */
2729 do ch = fgetc(i->file); while (ch == '\0');
2730 i->peek_buf[1] = ch;
2731 }
2732
2733 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2734 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002735}
2736
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002737static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2738{
2739 for (;;) {
2740 int ch, ch2;
2741
2742 ch = i_getch(input);
2743 if (ch != '\\')
2744 return ch;
2745 ch2 = i_peek(input);
2746 if (ch2 != '\n')
2747 return ch;
2748 /* backslash+newline, skip it */
2749 i_getch(input);
2750 }
2751}
2752
2753/* Note: this function _eats_ \<newline> pairs, safe to use plain
2754 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2755 */
2756static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2757{
2758 for (;;) {
2759 int ch, ch2;
2760
2761 ch = i_peek(input);
2762 if (ch != '\\')
2763 return ch;
2764 ch2 = i_peek2(input);
2765 if (ch2 != '\n')
2766 return ch;
2767 /* backslash+newline, skip it */
2768 i_getch(input);
2769 i_getch(input);
2770 }
2771}
2772
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002773static void setup_file_in_str(struct in_str *i, FILE *f)
2774{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002775 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002776 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002777 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002778}
2779
2780static void setup_string_in_str(struct in_str *i, const char *s)
2781{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002782 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002783 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002784 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002785}
2786
2787
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002788/*
2789 * o_string support
2790 */
2791#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002792
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002793static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002794{
2795 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002796 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002797 if (o->data)
2798 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002799}
2800
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002801static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002802{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002803 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002804 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002805}
2806
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002807static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2808{
2809 free(o->data);
2810}
2811
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002812static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002813{
2814 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002815 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002816 o->data = xrealloc(o->data, 1 + o->maxlen);
2817 }
2818}
2819
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002820static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002821{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002822 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002823 if (o->length < o->maxlen) {
2824 /* likely. avoid o_grow_by() call */
2825 add:
2826 o->data[o->length] = ch;
2827 o->length++;
2828 o->data[o->length] = '\0';
2829 return;
2830 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002831 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002832 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002833}
2834
Denys Vlasenko657086a2016-09-29 18:07:42 +02002835#if 0
2836/* Valid only if we know o_string is not empty */
2837static void o_delchr(o_string *o)
2838{
2839 o->length--;
2840 o->data[o->length] = '\0';
2841}
2842#endif
2843
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002844static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002845{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002846 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002847 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002848 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002849}
2850
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002851static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002852{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002853 o_addblock(o, str, strlen(str));
2854}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002855
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002856#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002857static void nommu_addchr(o_string *o, int ch)
2858{
2859 if (o)
2860 o_addchr(o, ch);
2861}
2862#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002863# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002864#endif
2865
2866static void o_addstr_with_NUL(o_string *o, const char *str)
2867{
2868 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002869}
2870
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002871/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002872 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002873 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2874 * Apparently, on unquoted $v bash still does globbing
2875 * ("v='*.txt'; echo $v" prints all .txt files),
2876 * but NOT brace expansion! Thus, there should be TWO independent
2877 * quoting mechanisms on $v expansion side: one protects
2878 * $v from brace expansion, and other additionally protects "$v" against globbing.
2879 * We have only second one.
2880 */
2881
Denys Vlasenko9e800222010-10-03 14:28:04 +02002882#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002883# define MAYBE_BRACES "{}"
2884#else
2885# define MAYBE_BRACES ""
2886#endif
2887
Eric Andersen25f27032001-04-26 23:22:31 +00002888/* My analysis of quoting semantics tells me that state information
2889 * is associated with a destination, not a source.
2890 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002891static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002892{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002893 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002894 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002895 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002896 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002897 o_grow_by(o, sz);
2898 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002899 o->data[o->length] = '\\';
2900 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002901 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002902 o->data[o->length] = ch;
2903 o->length++;
2904 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002905}
2906
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002907static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002908{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002909 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002910 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2911 && strchr("*?[\\" MAYBE_BRACES, ch)
2912 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002913 sz++;
2914 o->data[o->length] = '\\';
2915 o->length++;
2916 }
2917 o_grow_by(o, sz);
2918 o->data[o->length] = ch;
2919 o->length++;
2920 o->data[o->length] = '\0';
2921}
2922
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002923static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002924{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002925 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002926 char ch;
2927 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002928 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002929 if (ordinary_cnt > len) /* paranoia */
2930 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002931 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002932 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002933 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002934 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002935 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002936
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002937 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002938 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002939 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002940 sz++;
2941 o->data[o->length] = '\\';
2942 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002943 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002944 o_grow_by(o, sz);
2945 o->data[o->length] = ch;
2946 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002947 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002948 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002949}
2950
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002951static void o_addQblock(o_string *o, const char *str, int len)
2952{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002953 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002954 o_addblock(o, str, len);
2955 return;
2956 }
2957 o_addqblock(o, str, len);
2958}
2959
Denys Vlasenko38292b62010-09-05 14:49:40 +02002960static void o_addQstr(o_string *o, const char *str)
2961{
2962 o_addQblock(o, str, strlen(str));
2963}
2964
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002965/* A special kind of o_string for $VAR and `cmd` expansion.
2966 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002967 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002968 * list[i] contains an INDEX (int!) into this string data.
2969 * It means that if list[] needs to grow, data needs to be moved higher up
2970 * but list[i]'s need not be modified.
2971 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002972 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002973 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2974 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002975#if DEBUG_EXPAND || DEBUG_GLOB
2976static void debug_print_list(const char *prefix, o_string *o, int n)
2977{
2978 char **list = (char**)o->data;
2979 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2980 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002981
2982 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002983 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 +02002984 prefix, list, n, string_start, o->length, o->maxlen,
2985 !!(o->o_expflags & EXP_FLAG_GLOB),
2986 o->has_quoted_part,
2987 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002988 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002989 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002990 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2991 o->data + (int)(uintptr_t)list[i] + string_start,
2992 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002993 i++;
2994 }
2995 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002996 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002997 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002998 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002999 }
3000}
3001#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003002# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003003#endif
3004
3005/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3006 * in list[n] so that it points past last stored byte so far.
3007 * It returns n+1. */
3008static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003009{
3010 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003011 int string_start;
3012 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003013
3014 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003015 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3016 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003017 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003018 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003019 /* list[n] points to string_start, make space for 16 more pointers */
3020 o->maxlen += 0x10 * sizeof(list[0]);
3021 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003022 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003023 memmove(list + n + 0x10, list + n, string_len);
3024 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003025 } else {
3026 debug_printf_list("list[%d]=%d string_start=%d\n",
3027 n, string_len, string_start);
3028 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003029 } else {
3030 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003031 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3032 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003033 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3034 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003035 o->has_empty_slot = 0;
3036 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003037 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003038 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003039 return n + 1;
3040}
3041
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003042/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003043static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003044{
3045 char **list = (char**)o->data;
3046 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3047
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003048 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003049}
3050
Denys Vlasenko9e800222010-10-03 14:28:04 +02003051#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003052/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3053 * first, it processes even {a} (no commas), second,
3054 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003055 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003056 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003057
3058/* Helper */
3059static int glob_needed(const char *s)
3060{
3061 while (*s) {
3062 if (*s == '\\') {
3063 if (!s[1])
3064 return 0;
3065 s += 2;
3066 continue;
3067 }
3068 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3069 return 1;
3070 s++;
3071 }
3072 return 0;
3073}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003074/* Return pointer to next closing brace or to comma */
3075static const char *next_brace_sub(const char *cp)
3076{
3077 unsigned depth = 0;
3078 cp++;
3079 while (*cp != '\0') {
3080 if (*cp == '\\') {
3081 if (*++cp == '\0')
3082 break;
3083 cp++;
3084 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003085 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003086 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003087 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003088 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003089 depth++;
3090 }
3091
3092 return *cp != '\0' ? cp : NULL;
3093}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003094/* Recursive brace globber. Note: may garble pattern[]. */
3095static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003096{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003097 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003098 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003099 const char *next;
3100 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003101 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003102 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003103
3104 debug_printf_glob("glob_brace('%s')\n", pattern);
3105
3106 begin = pattern;
3107 while (1) {
3108 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003109 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003110 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003111 /* Find the first sub-pattern and at the same time
3112 * find the rest after the closing brace */
3113 next = next_brace_sub(begin);
3114 if (next == NULL) {
3115 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003116 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003117 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003118 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003119 /* "{abc}" with no commas - illegal
3120 * brace expr, disregard and skip it */
3121 begin = next + 1;
3122 continue;
3123 }
3124 break;
3125 }
3126 if (*begin == '\\' && begin[1] != '\0')
3127 begin++;
3128 begin++;
3129 }
3130 debug_printf_glob("begin:%s\n", begin);
3131 debug_printf_glob("next:%s\n", next);
3132
3133 /* Now find the end of the whole brace expression */
3134 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003135 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003136 rest = next_brace_sub(rest);
3137 if (rest == NULL) {
3138 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003139 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003140 }
3141 debug_printf_glob("rest:%s\n", rest);
3142 }
3143 rest_len = strlen(++rest) + 1;
3144
3145 /* We are sure the brace expression is well-formed */
3146
3147 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003148 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003149
3150 /* We have a brace expression. BEGIN points to the opening {,
3151 * NEXT points past the terminator of the first element, and REST
3152 * points past the final }. We will accumulate result names from
3153 * recursive runs for each brace alternative in the buffer using
3154 * GLOB_APPEND. */
3155
3156 p = begin + 1;
3157 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003158 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003159 memcpy(
3160 mempcpy(
3161 mempcpy(new_pattern_buf,
3162 /* We know the prefix for all sub-patterns */
3163 pattern, begin - pattern),
3164 p, next - p),
3165 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003166
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003167 /* Note: glob_brace() may garble new_pattern_buf[].
3168 * That's why we re-copy prefix every time (1st memcpy above).
3169 */
3170 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003171 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003172 /* We saw the last entry */
3173 break;
3174 }
3175 p = next + 1;
3176 next = next_brace_sub(next);
3177 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003178 free(new_pattern_buf);
3179 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003180
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003181 simple_glob:
3182 {
3183 int gr;
3184 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003185
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003186 memset(&globdata, 0, sizeof(globdata));
3187 gr = glob(pattern, 0, NULL, &globdata);
3188 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3189 if (gr != 0) {
3190 if (gr == GLOB_NOMATCH) {
3191 globfree(&globdata);
3192 /* NB: garbles parameter */
3193 unbackslash(pattern);
3194 o_addstr_with_NUL(o, pattern);
3195 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3196 return o_save_ptr_helper(o, n);
3197 }
3198 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003199 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003200 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3201 * but we didn't specify it. Paranoia again. */
3202 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3203 }
3204 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3205 char **argv = globdata.gl_pathv;
3206 while (1) {
3207 o_addstr_with_NUL(o, *argv);
3208 n = o_save_ptr_helper(o, n);
3209 argv++;
3210 if (!*argv)
3211 break;
3212 }
3213 }
3214 globfree(&globdata);
3215 }
3216 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003217}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003218/* Performs globbing on last list[],
3219 * saving each result as a new list[].
3220 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003221static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003222{
3223 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003224
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003225 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003226 if (!o->data)
3227 return o_save_ptr_helper(o, n);
3228 pattern = o->data + o_get_last_ptr(o, n);
3229 debug_printf_glob("glob pattern '%s'\n", pattern);
3230 if (!glob_needed(pattern)) {
3231 /* unbackslash last string in o in place, fix length */
3232 o->length = unbackslash(pattern) - o->data;
3233 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3234 return o_save_ptr_helper(o, n);
3235 }
3236
3237 copy = xstrdup(pattern);
3238 /* "forget" pattern in o */
3239 o->length = pattern - o->data;
3240 n = glob_brace(copy, o, n);
3241 free(copy);
3242 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003243 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003244 return n;
3245}
3246
Denys Vlasenko238081f2010-10-03 14:26:26 +02003247#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003248
3249/* Helper */
3250static int glob_needed(const char *s)
3251{
3252 while (*s) {
3253 if (*s == '\\') {
3254 if (!s[1])
3255 return 0;
3256 s += 2;
3257 continue;
3258 }
3259 if (*s == '*' || *s == '[' || *s == '?')
3260 return 1;
3261 s++;
3262 }
3263 return 0;
3264}
3265/* 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)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003269{
3270 glob_t globdata;
3271 int gr;
3272 char *pattern;
3273
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003274 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003275 if (!o->data)
3276 return o_save_ptr_helper(o, n);
3277 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003278 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003279 if (!glob_needed(pattern)) {
3280 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003281 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003282 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003283 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003284 return o_save_ptr_helper(o, n);
3285 }
3286
3287 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003288 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3289 * If we glob "*.\*" and don't find anything, we need
3290 * to fall back to using literal "*.*", but GLOB_NOCHECK
3291 * will return "*.\*"!
3292 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003293 gr = glob(pattern, 0, NULL, &globdata);
3294 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003295 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003296 if (gr == GLOB_NOMATCH) {
3297 globfree(&globdata);
3298 goto literal;
3299 }
3300 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003301 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003302 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3303 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003304 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003305 }
3306 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3307 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003308 /* "forget" pattern in o */
3309 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003310 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003311 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003312 n = o_save_ptr_helper(o, n);
3313 argv++;
3314 if (!*argv)
3315 break;
3316 }
3317 }
3318 globfree(&globdata);
3319 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003320 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003321 return n;
3322}
3323
Denys Vlasenko238081f2010-10-03 14:26:26 +02003324#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003325
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003326/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003327 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003328static int o_save_ptr(o_string *o, int n)
3329{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003330 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003331 /* If o->has_empty_slot, list[n] was already globbed
3332 * (if it was requested back then when it was filled)
3333 * so don't do that again! */
3334 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003335 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003336 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003337 return o_save_ptr_helper(o, n);
3338}
3339
3340/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003341static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003342{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003343 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003344 int string_start;
3345
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003346 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3347 if (DEBUG_EXPAND)
3348 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003349 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003350 list = (char**)o->data;
3351 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3352 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003353 while (n) {
3354 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003355 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003356 }
3357 return list;
3358}
3359
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003360static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003361
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003362/* Returns pi->next - next pipe in the list */
3363static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003364{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003365 struct pipe *next;
3366 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003367
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003368 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003369 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003370 struct command *command;
3371 struct redir_struct *r, *rnext;
3372
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003373 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003374 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003375 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003376 if (DEBUG_CLEAN) {
3377 int a;
3378 char **p;
3379 for (a = 0, p = command->argv; *p; a++, p++) {
3380 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3381 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003382 }
3383 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003384 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003385 }
3386 /* not "else if": on syntax error, we may have both! */
3387 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003388 debug_printf_clean(" begin group (cmd_type:%d)\n",
3389 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003390 free_pipe_list(command->group);
3391 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003392 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003393 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003394 /* else is crucial here.
3395 * If group != NULL, child_func is meaningless */
3396#if ENABLE_HUSH_FUNCTIONS
3397 else if (command->child_func) {
3398 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3399 command->child_func->parent_cmd = NULL;
3400 }
3401#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003402#if !BB_MMU
3403 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003404 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003405#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003406 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003407 debug_printf_clean(" redirect %d%s",
3408 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003409 /* guard against the case >$FOO, where foo is unset or blank */
3410 if (r->rd_filename) {
3411 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3412 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003413 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003414 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003415 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003416 rnext = r->next;
3417 free(r);
3418 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003419 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003420 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003421 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003422 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003423#if ENABLE_HUSH_JOB
3424 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003425 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003426#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003427
3428 next = pi->next;
3429 free(pi);
3430 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003431}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003432
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003433static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003434{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003435 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003436#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003437 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003438#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003439 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003440 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003441 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003442}
3443
3444
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003445/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003446
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003447#ifndef debug_print_tree
3448static void debug_print_tree(struct pipe *pi, int lvl)
3449{
3450 static const char *const PIPE[] = {
3451 [PIPE_SEQ] = "SEQ",
3452 [PIPE_AND] = "AND",
3453 [PIPE_OR ] = "OR" ,
3454 [PIPE_BG ] = "BG" ,
3455 };
3456 static const char *RES[] = {
3457 [RES_NONE ] = "NONE" ,
3458# if ENABLE_HUSH_IF
3459 [RES_IF ] = "IF" ,
3460 [RES_THEN ] = "THEN" ,
3461 [RES_ELIF ] = "ELIF" ,
3462 [RES_ELSE ] = "ELSE" ,
3463 [RES_FI ] = "FI" ,
3464# endif
3465# if ENABLE_HUSH_LOOPS
3466 [RES_FOR ] = "FOR" ,
3467 [RES_WHILE] = "WHILE",
3468 [RES_UNTIL] = "UNTIL",
3469 [RES_DO ] = "DO" ,
3470 [RES_DONE ] = "DONE" ,
3471# endif
3472# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3473 [RES_IN ] = "IN" ,
3474# endif
3475# if ENABLE_HUSH_CASE
3476 [RES_CASE ] = "CASE" ,
3477 [RES_CASE_IN ] = "CASE_IN" ,
3478 [RES_MATCH] = "MATCH",
3479 [RES_CASE_BODY] = "CASE_BODY",
3480 [RES_ESAC ] = "ESAC" ,
3481# endif
3482 [RES_XXXX ] = "XXXX" ,
3483 [RES_SNTX ] = "SNTX" ,
3484 };
3485 static const char *const CMDTYPE[] = {
3486 "{}",
3487 "()",
3488 "[noglob]",
3489# if ENABLE_HUSH_FUNCTIONS
3490 "func()",
3491# endif
3492 };
3493
3494 int pin, prn;
3495
3496 pin = 0;
3497 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003498 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3499 lvl*2, "",
3500 pin,
3501 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3502 RES[pi->res_word],
3503 pi->followup, PIPE[pi->followup]
3504 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003505 prn = 0;
3506 while (prn < pi->num_cmds) {
3507 struct command *command = &pi->cmds[prn];
3508 char **argv = command->argv;
3509
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003510 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003511 lvl*2, "", prn,
3512 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003513#if ENABLE_HUSH_LINENO_VAR
3514 fdprintf(2, " LINENO:%u", command->lineno);
3515#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003516 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003517 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003518 CMDTYPE[command->cmd_type],
3519 argv
3520# if !BB_MMU
3521 , " group_as_string:", command->group_as_string
3522# else
3523 , "", ""
3524# endif
3525 );
3526 debug_print_tree(command->group, lvl+1);
3527 prn++;
3528 continue;
3529 }
3530 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003531 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003532 argv++;
3533 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003534 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003535 prn++;
3536 }
3537 pi = pi->next;
3538 pin++;
3539 }
3540}
3541#endif /* debug_print_tree */
3542
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003543static struct pipe *new_pipe(void)
3544{
Eric Andersen25f27032001-04-26 23:22:31 +00003545 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003546 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003547 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003548 return pi;
3549}
3550
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003551/* Command (member of a pipe) is complete, or we start a new pipe
3552 * if ctx->command is NULL.
3553 * No errors possible here.
3554 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003555static int done_command(struct parse_context *ctx)
3556{
3557 /* The command is really already in the pipe structure, so
3558 * advance the pipe counter and make a new, null command. */
3559 struct pipe *pi = ctx->pipe;
3560 struct command *command = ctx->command;
3561
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003562#if 0 /* Instead we emit error message at run time */
3563 if (ctx->pending_redirect) {
3564 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003565 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003566 ctx->pending_redirect = NULL;
3567 }
3568#endif
3569
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003570 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003571 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003572 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003573 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003574 }
3575 pi->num_cmds++;
3576 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003577 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003578 } else {
3579 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3580 }
3581
3582 /* Only real trickiness here is that the uncommitted
3583 * command structure is not counted in pi->num_cmds. */
3584 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003585 ctx->command = command = &pi->cmds[pi->num_cmds];
3586 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003587 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003588#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003589 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003590 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003591#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003592 return pi->num_cmds; /* used only for 0/nonzero check */
3593}
3594
3595static void done_pipe(struct parse_context *ctx, pipe_style type)
3596{
3597 int not_null;
3598
3599 debug_printf_parse("done_pipe entered, followup %d\n", type);
3600 /* Close previous command */
3601 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003602#if HAS_KEYWORDS
3603 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3604 ctx->ctx_inverted = 0;
3605 ctx->pipe->res_word = ctx->ctx_res_w;
3606#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003607 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3608 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003609 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3610 * in a backgrounded subshell.
3611 */
3612 struct pipe *pi;
3613 struct command *command;
3614
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003615 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003616 pi = ctx->list_head;
3617 while (pi != ctx->pipe) {
3618 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3619 goto no_conv;
3620 pi = pi->next;
3621 }
3622
3623 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3624 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3625 pi = xzalloc(sizeof(*pi));
3626 pi->followup = PIPE_BG;
3627 pi->num_cmds = 1;
3628 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3629 command = &pi->cmds[0];
3630 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3631 command->cmd_type = CMD_NORMAL;
3632 command->group = ctx->list_head;
3633#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003634 command->group_as_string = xstrndup(
3635 ctx->as_string.data,
3636 ctx->as_string.length - 1 /* do not copy last char, "&" */
3637 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003638#endif
3639 /* Replace all pipes in ctx with one newly created */
3640 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003641 } else {
3642 no_conv:
3643 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003644 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003645
3646 /* Without this check, even just <enter> on command line generates
3647 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003648 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003649 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003650#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003651 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003652#endif
3653#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003654 || ctx->ctx_res_w == RES_DONE
3655 || ctx->ctx_res_w == RES_FOR
3656 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003657#endif
3658#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003659 || ctx->ctx_res_w == RES_ESAC
3660#endif
3661 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003662 struct pipe *new_p;
3663 debug_printf_parse("done_pipe: adding new pipe: "
3664 "not_null:%d ctx->ctx_res_w:%d\n",
3665 not_null, ctx->ctx_res_w);
3666 new_p = new_pipe();
3667 ctx->pipe->next = new_p;
3668 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003669 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003670 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003671 * This is used to control execution.
3672 * RES_FOR and RES_IN are NOT sticky (needed to support
3673 * cases where variable or value happens to match a keyword):
3674 */
3675#if ENABLE_HUSH_LOOPS
3676 if (ctx->ctx_res_w == RES_FOR
3677 || ctx->ctx_res_w == RES_IN)
3678 ctx->ctx_res_w = RES_NONE;
3679#endif
3680#if ENABLE_HUSH_CASE
3681 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003682 ctx->ctx_res_w = RES_CASE_BODY;
3683 if (ctx->ctx_res_w == RES_CASE)
3684 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003685#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003686 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003687 /* Create the memory for command, roughly:
3688 * ctx->pipe->cmds = new struct command;
3689 * ctx->command = &ctx->pipe->cmds[0];
3690 */
3691 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003692 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003693 }
3694 debug_printf_parse("done_pipe return\n");
3695}
3696
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003697static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003698{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003699 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003700 if (MAYBE_ASSIGNMENT != 0)
3701 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003702 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003703 /* Create the memory for command, roughly:
3704 * ctx->pipe->cmds = new struct command;
3705 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003706 */
3707 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003708}
3709
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003710/* If a reserved word is found and processed, parse context is modified
3711 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003712 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003713#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003714struct reserved_combo {
3715 char literal[6];
3716 unsigned char res;
3717 unsigned char assignment_flag;
3718 int flag;
3719};
3720enum {
3721 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003722# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003723 FLAG_IF = (1 << RES_IF ),
3724 FLAG_THEN = (1 << RES_THEN ),
3725 FLAG_ELIF = (1 << RES_ELIF ),
3726 FLAG_ELSE = (1 << RES_ELSE ),
3727 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003728# endif
3729# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003730 FLAG_FOR = (1 << RES_FOR ),
3731 FLAG_WHILE = (1 << RES_WHILE),
3732 FLAG_UNTIL = (1 << RES_UNTIL),
3733 FLAG_DO = (1 << RES_DO ),
3734 FLAG_DONE = (1 << RES_DONE ),
3735 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003736# endif
3737# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003738 FLAG_MATCH = (1 << RES_MATCH),
3739 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003740# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003741 FLAG_START = (1 << RES_XXXX ),
3742};
3743
3744static const struct reserved_combo* match_reserved_word(o_string *word)
3745{
Eric Andersen25f27032001-04-26 23:22:31 +00003746 /* Mostly a list of accepted follow-up reserved words.
3747 * FLAG_END means we are done with the sequence, and are ready
3748 * to turn the compound list into a command.
3749 * FLAG_START means the word must start a new compound list.
3750 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003751 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003752# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003753 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3754 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3755 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3756 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3757 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3758 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003759# endif
3760# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003761 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3762 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3763 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3764 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3765 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3766 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003767# endif
3768# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003769 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3770 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003771# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003772 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003773 const struct reserved_combo *r;
3774
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003775 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003776 if (strcmp(word->data, r->literal) == 0)
3777 return r;
3778 }
3779 return NULL;
3780}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003781/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003782 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003783static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003784{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003785# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003786 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003787 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003788 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003789# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003790 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003791
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003792 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003793 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003794 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003795 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003796 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003797
3798 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003799# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003800 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3801 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003802 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003803 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003804# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003805 if (r->flag == 0) { /* '!' */
3806 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003807 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003808 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003809 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003810 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003811 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003812 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003813 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003814 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003815
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003816 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003817 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003818 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003819 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003820 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003821 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003822 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003823 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003824 } else {
3825 /* "{...} fi" is ok. "{...} if" is not
3826 * Example:
3827 * if { echo foo; } then { echo bar; } fi */
3828 if (ctx->command->group)
3829 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003830 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003831
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003832 ctx->ctx_res_w = r->res;
3833 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003834 ctx->is_assignment = r->assignment_flag;
3835 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003836
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003837 if (ctx->old_flag & FLAG_END) {
3838 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003839
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003840 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003841 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003842 old = ctx->stack;
3843 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003844 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003845# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003846 /* At this point, the compound command's string is in
3847 * ctx->as_string... except for the leading keyword!
3848 * Consider this example: "echo a | if true; then echo a; fi"
3849 * ctx->as_string will contain "true; then echo a; fi",
3850 * with "if " remaining in old->as_string!
3851 */
3852 {
3853 char *str;
3854 int len = old->as_string.length;
3855 /* Concatenate halves */
3856 o_addstr(&old->as_string, ctx->as_string.data);
3857 o_free_unsafe(&ctx->as_string);
3858 /* Find where leading keyword starts in first half */
3859 str = old->as_string.data + len;
3860 if (str > old->as_string.data)
3861 str--; /* skip whitespace after keyword */
3862 while (str > old->as_string.data && isalpha(str[-1]))
3863 str--;
3864 /* Ugh, we're done with this horrid hack */
3865 old->command->group_as_string = xstrdup(str);
3866 debug_printf_parse("pop, remembering as:'%s'\n",
3867 old->command->group_as_string);
3868 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003869# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003870 *ctx = *old; /* physical copy */
3871 free(old);
3872 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003873 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003874}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003875#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003876
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003877/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003878 * Normal return is 0. Syntax errors return 1.
3879 * Note: on return, word is reset, but not o_free'd!
3880 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003881static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003882{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003883 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003884
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003885 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3886 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003887 debug_printf_parse("done_word return 0: true null, ignored\n");
3888 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003889 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003890
Eric Andersen25f27032001-04-26 23:22:31 +00003891 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003892 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3893 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003894 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003895 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003896 * If the redirection operator is "<<" or "<<-", the word
3897 * that follows the redirection operator shall be
3898 * subjected to quote removal; it is unspecified whether
3899 * any of the other expansions occur. For the other
3900 * redirection operators, the word that follows the
3901 * redirection operator shall be subjected to tilde
3902 * expansion, parameter expansion, command substitution,
3903 * arithmetic expansion, and quote removal.
3904 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003905 * on the word by a non-interactive shell; an interactive
3906 * shell may perform it, but shall do so only when
3907 * the expansion would result in one word."
3908 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003909//bash does not do parameter/command substitution or arithmetic expansion
3910//for _heredoc_ redirection word: these constructs look for exact eof marker
3911// as written:
3912// <<EOF$t
3913// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003914// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3915
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003916 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003917 /* Cater for >\file case:
3918 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3919 * Same with heredocs:
3920 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3921 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003922 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3923 unbackslash(ctx->pending_redirect->rd_filename);
3924 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003925 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003926 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3927 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003928 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003929 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003930 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003931 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003932#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003933# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003934 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003935 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003936 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003937 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003938 /* ctx->ctx_res_w = RES_MATCH; */
3939 ctx->ctx_dsemicolon = 0;
3940 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003941# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003942 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003943# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003944 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3945 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003946# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003947# if ENABLE_HUSH_CASE
3948 && ctx->ctx_res_w != RES_CASE
3949# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003950 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003951 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003952 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003953 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003954 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003955# if ENABLE_HUSH_LINENO_VAR
3956/* Case:
3957 * "while ...; do
3958 * cmd ..."
3959 * If we don't close the pipe _now_, immediately after "do", lineno logic
3960 * sees "cmd" as starting at "do" - i.e., at the previous line.
3961 */
3962 if (0
3963 IF_HUSH_IF(|| reserved->res == RES_THEN)
3964 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3965 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3966 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3967 ) {
3968 done_pipe(ctx, PIPE_SEQ);
3969 }
3970# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003971 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003972 debug_printf_parse("done_word return %d\n",
3973 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003974 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003975 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003976# if defined(CMD_SINGLEWORD_NOGLOB)
3977 if (0
3978# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003979 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02003980# endif
3981 /* In bash, local/export/readonly are special, args
3982 * are assignments and therefore expansion of them
3983 * should be "one-word" expansion:
3984 * $ export i=`echo 'a b'` # one arg: "i=a b"
3985 * compare with:
3986 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3987 * ls: cannot access i=a: No such file or directory
3988 * ls: cannot access b: No such file or directory
3989 * Note: bash 3.2.33(1) does this only if export word
3990 * itself is not quoted:
3991 * $ export i=`echo 'aaa bbb'`; echo "$i"
3992 * aaa bbb
3993 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3994 * aaa
3995 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003996 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
3997 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
3998 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02003999 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004000 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4001 }
4002 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004003# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004004 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004005#endif /* HAS_KEYWORDS */
4006
Denis Vlasenkobb929512009-04-16 10:59:40 +00004007 if (command->group) {
4008 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004009 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004010 debug_printf_parse("done_word return 1: syntax error, "
4011 "groups and arglists don't mix\n");
4012 return 1;
4013 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004014
4015 /* If this word wasn't an assignment, next ones definitely
4016 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004017 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4018 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004019 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004020 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004021 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004022 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004023 command->assignment_cnt++;
4024 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4025 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004026 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4027 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004028 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004029 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4030 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004031 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004032 }
Eric Andersen25f27032001-04-26 23:22:31 +00004033
Denis Vlasenko06810332007-05-21 23:30:54 +00004034#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004035 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004036 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004037 || !is_well_formed_var_name(command->argv[0], '\0')
4038 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004039 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004040 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004041 return 1;
4042 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004043 /* Force FOR to have just one word (variable name) */
4044 /* NB: basically, this makes hush see "for v in ..."
4045 * syntax as if it is "for v; in ...". FOR and IN become
4046 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004047 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004048 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004049#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004050#if ENABLE_HUSH_CASE
4051 /* Force CASE to have just one word */
4052 if (ctx->ctx_res_w == RES_CASE) {
4053 done_pipe(ctx, PIPE_SEQ);
4054 }
4055#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004056
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004057 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004058
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004059 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004060 return 0;
4061}
4062
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004063
4064/* Peek ahead in the input to find out if we have a "&n" construct,
4065 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004066 * Return:
4067 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4068 * REDIRFD_SYNTAX_ERR if syntax error,
4069 * REDIRFD_TO_FILE if no & was seen,
4070 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004071 */
4072#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004073#define parse_redir_right_fd(as_string, input) \
4074 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004075#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004076static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004077{
4078 int ch, d, ok;
4079
4080 ch = i_peek(input);
4081 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004082 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004083
4084 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004085 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004086 ch = i_peek(input);
4087 if (ch == '-') {
4088 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004089 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004090 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004091 }
4092 d = 0;
4093 ok = 0;
4094 while (ch != EOF && isdigit(ch)) {
4095 d = d*10 + (ch-'0');
4096 ok = 1;
4097 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004098 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004099 ch = i_peek(input);
4100 }
4101 if (ok) return d;
4102
4103//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4104
4105 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004106 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004107}
4108
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004109/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004110 */
4111static int parse_redirect(struct parse_context *ctx,
4112 int fd,
4113 redir_type style,
4114 struct in_str *input)
4115{
4116 struct command *command = ctx->command;
4117 struct redir_struct *redir;
4118 struct redir_struct **redirp;
4119 int dup_num;
4120
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004121 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004122 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004123 /* Check for a '>&1' type redirect */
4124 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4125 if (dup_num == REDIRFD_SYNTAX_ERR)
4126 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004127 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004128 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004129 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004130 if (dup_num) { /* <<-... */
4131 ch = i_getch(input);
4132 nommu_addchr(&ctx->as_string, ch);
4133 ch = i_peek(input);
4134 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004135 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004136
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004137 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004138 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004139 if (ch == '|') {
4140 /* >|FILE redirect ("clobbering" >).
4141 * Since we do not support "set -o noclobber" yet,
4142 * >| and > are the same for now. Just eat |.
4143 */
4144 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004145 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004146 }
4147 }
4148
4149 /* Create a new redir_struct and append it to the linked list */
4150 redirp = &command->redirects;
4151 while ((redir = *redirp) != NULL) {
4152 redirp = &(redir->next);
4153 }
4154 *redirp = redir = xzalloc(sizeof(*redir));
4155 /* redir->next = NULL; */
4156 /* redir->rd_filename = NULL; */
4157 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004158 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004159
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004160 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4161 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004162
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004163 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004164 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004165 /* Erik had a check here that the file descriptor in question
4166 * is legit; I postpone that to "run time"
4167 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004168 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4169 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004170 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004171#if 0 /* Instead we emit error message at run time */
4172 if (ctx->pending_redirect) {
4173 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004174 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004175 }
4176#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004177 /* Set ctx->pending_redirect, so we know what to do at the
4178 * end of the next parsed word. */
4179 ctx->pending_redirect = redir;
4180 }
4181 return 0;
4182}
4183
Eric Andersen25f27032001-04-26 23:22:31 +00004184/* If a redirect is immediately preceded by a number, that number is
4185 * supposed to tell which file descriptor to redirect. This routine
4186 * looks for such preceding numbers. In an ideal world this routine
4187 * needs to handle all the following classes of redirects...
4188 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4189 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4190 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4191 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004192 *
4193 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4194 * "2.7 Redirection
4195 * ... If n is quoted, the number shall not be recognized as part of
4196 * the redirection expression. For example:
4197 * echo \2>a
4198 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004199 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004200 *
4201 * A -1 return means no valid number was found,
4202 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004203 */
4204static int redirect_opt_num(o_string *o)
4205{
4206 int num;
4207
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004208 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004209 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004210 num = bb_strtou(o->data, NULL, 10);
4211 if (errno || num < 0)
4212 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004213 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004214 return num;
4215}
4216
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004217#if BB_MMU
4218#define fetch_till_str(as_string, input, word, skip_tabs) \
4219 fetch_till_str(input, word, skip_tabs)
4220#endif
4221static char *fetch_till_str(o_string *as_string,
4222 struct in_str *input,
4223 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004224 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004225{
4226 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004227 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004228 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004229 int ch;
4230
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004231 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004232
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004233 while (1) {
4234 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004235 if (ch != EOF)
4236 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004237 if (ch == '\n' || ch == EOF) {
4238 check_heredoc_end:
4239 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4240 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4241 heredoc.data[past_EOL] = '\0';
4242 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4243 return heredoc.data;
4244 }
4245 if (ch == '\n') {
4246 /* This is a new line.
4247 * Remember position and backslash-escaping status.
4248 */
4249 o_addchr(&heredoc, ch);
4250 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004251 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004252 past_EOL = heredoc.length;
4253 /* Get 1st char of next line, possibly skipping leading tabs */
4254 do {
4255 ch = i_getch(input);
4256 if (ch != EOF)
4257 nommu_addchr(as_string, ch);
4258 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4259 /* If this immediately ended the line,
4260 * go back to end-of-line checks.
4261 */
4262 if (ch == '\n')
4263 goto check_heredoc_end;
4264 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004265 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004266 }
4267 if (ch == EOF) {
4268 o_free_unsafe(&heredoc);
4269 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004270 }
4271 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004272 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004273 if (prev == '\\' && ch == '\\')
4274 /* Correctly handle foo\\<eol> (not a line cont.) */
4275 prev = 0; /* not \ */
4276 else
4277 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004278 }
4279}
4280
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004281/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4282 * and load them all. There should be exactly heredoc_cnt of them.
4283 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004284static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4285{
4286 struct pipe *pi = ctx->list_head;
4287
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004288 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004289 int i;
4290 struct command *cmd = pi->cmds;
4291
4292 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4293 pi->num_cmds,
4294 cmd->argv ? cmd->argv[0] : "NONE");
4295 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004296 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004297
4298 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4299 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004300 while (redir) {
4301 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004302 char *p;
4303
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004304 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004305 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004306 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004307 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004308 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004309 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004310 return 1;
4311 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004312 free(redir->rd_filename);
4313 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004314 heredoc_cnt--;
4315 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004316 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004317 }
4318 cmd++;
4319 }
4320 pi = pi->next;
4321 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004322#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004323 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004324 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004325 bb_error_msg_and_die("heredoc BUG 2");
4326#endif
4327 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004328}
4329
4330
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004331static int run_list(struct pipe *pi);
4332#if BB_MMU
4333#define parse_stream(pstring, input, end_trigger) \
4334 parse_stream(input, end_trigger)
4335#endif
4336static struct pipe *parse_stream(char **pstring,
4337 struct in_str *input,
4338 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004339
Eric Andersen25f27032001-04-26 23:22:31 +00004340
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004341static int parse_group(struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004342 struct in_str *input, int ch)
4343{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004344 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004345 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004346 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004347#if BB_MMU
4348# define as_string NULL
4349#else
4350 char *as_string = NULL;
4351#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004352 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004353 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004354 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004355
4356 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004357#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004358 if (ch == '(' && !ctx->word.has_quoted_part) {
4359 if (ctx->word.length)
4360 if (done_word(ctx))
Denis Vlasenkobb929512009-04-16 10:59:40 +00004361 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004362 if (!command->argv)
4363 goto skip; /* (... */
4364 if (command->argv[1]) { /* word word ... (... */
4365 syntax_error_unexpected_ch('(');
4366 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004367 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004368 /* it is "word(..." or "word (..." */
4369 do
4370 ch = i_getch(input);
4371 while (ch == ' ' || ch == '\t');
4372 if (ch != ')') {
4373 syntax_error_unexpected_ch(ch);
4374 return 1;
4375 }
4376 nommu_addchr(&ctx->as_string, ch);
4377 do
4378 ch = i_getch(input);
4379 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004380 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004381 syntax_error_unexpected_ch(ch);
4382 return 1;
4383 }
4384 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004385 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004386 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004387 }
4388#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004389
4390#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004391 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004392 || ctx->word.length /* word{... */
4393 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004394 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004395 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004396 debug_printf_parse("parse_group return 1: "
4397 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004398 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004399 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004400#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004401
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004402 IF_HUSH_FUNCTIONS(skip:)
4403
Denis Vlasenko240c2552009-04-03 03:45:05 +00004404 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004405 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004406 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004407 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4408 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004409 } else {
4410 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004411 ch = i_peek(input);
4412 if (ch != ' ' && ch != '\t' && ch != '\n'
4413 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4414 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004415 syntax_error_unexpected_ch(ch);
4416 return 1;
4417 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004418 if (ch != '(') {
4419 ch = i_getch(input);
4420 nommu_addchr(&ctx->as_string, ch);
4421 }
Eric Andersen25f27032001-04-26 23:22:31 +00004422 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004423
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004424 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004425#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004426 if (as_string)
4427 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004428#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004429
4430 /* empty ()/{} or parse error? */
4431 if (!pipe_list || pipe_list == ERR_PTR) {
4432 /* parse_stream already emitted error msg */
4433 if (!BB_MMU)
4434 free(as_string);
4435 debug_printf_parse("parse_group return 1: "
4436 "parse_stream returned %p\n", pipe_list);
4437 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004438 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004439#if !BB_MMU
4440 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4441 command->group_as_string = as_string;
4442 debug_printf_parse("end of group, remembering as:'%s'\n",
4443 command->group_as_string);
4444#endif
4445
4446#if ENABLE_HUSH_FUNCTIONS
4447 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4448 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4449 struct command *cmd2;
4450
4451 cmd2 = xzalloc(sizeof(*cmd2));
4452 cmd2->cmd_type = CMD_SUBSHELL;
4453 cmd2->group = pipe_list;
4454# if !BB_MMU
4455//UNTESTED!
4456 cmd2->group_as_string = command->group_as_string;
4457 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4458# endif
4459
4460 pipe_list = new_pipe();
4461 pipe_list->cmds = cmd2;
4462 pipe_list->num_cmds = 1;
4463 }
4464#endif
4465
4466 command->group = pipe_list;
4467
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004468 debug_printf_parse("parse_group return 0\n");
4469 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004470 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004471#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004472}
4473
Denys Vlasenko0b883582016-12-23 16:49:07 +01004474#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004475/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004476static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004477/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004478static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004479{
4480 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004481 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004482 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004483 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004484 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004485 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004486 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004487 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004488 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004489 }
4490}
4491/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004492static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004493{
4494 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004495 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004496 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004497 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004498 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004499 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004500 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004501 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004502 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004503 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004504 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004505 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004506 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004507 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004508 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4509 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004510 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004511 continue;
4512 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004513 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004514 }
4515}
4516/* Process `cmd` - copy contents until "`" is seen. Complicated by
4517 * \` quoting.
4518 * "Within the backquoted style of command substitution, backslash
4519 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4520 * The search for the matching backquote shall be satisfied by the first
4521 * backquote found without a preceding backslash; during this search,
4522 * if a non-escaped backquote is encountered within a shell comment,
4523 * a here-document, an embedded command substitution of the $(command)
4524 * form, or a quoted string, undefined results occur. A single-quoted
4525 * or double-quoted string that begins, but does not end, within the
4526 * "`...`" sequence produces undefined results."
4527 * Example Output
4528 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4529 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004530static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004531{
4532 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004533 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004534 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004535 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004536 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004537 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4538 ch = i_getch(input);
4539 if (ch != '`'
4540 && ch != '$'
4541 && ch != '\\'
4542 && (!in_dquote || ch != '"')
4543 ) {
4544 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004545 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004546 }
4547 if (ch == EOF) {
4548 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004549 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004550 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004551 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004552 }
4553}
4554/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4555 * quoting and nested ()s.
4556 * "With the $(command) style of command substitution, all characters
4557 * following the open parenthesis to the matching closing parenthesis
4558 * constitute the command. Any valid shell script can be used for command,
4559 * except a script consisting solely of redirections which produces
4560 * unspecified results."
4561 * Example Output
4562 * echo $(echo '(TEST)' BEST) (TEST) BEST
4563 * echo $(echo 'TEST)' BEST) TEST) BEST
4564 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004565 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004566 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004567 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004568 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4569 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004570 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004571#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004572static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004573{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004574 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004575 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004576# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004577 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004578# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004579 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4580
Denys Vlasenko817a2022018-06-26 15:35:17 +02004581#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004582 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004583#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004584 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4585
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004586 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004587 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004588 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004589 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004590 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004591 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004592 if (ch == end_ch
4593# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004594 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004595# endif
4596 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004597 if (!dbl)
4598 break;
4599 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004600 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004601 i_getch(input); /* eat second ')' */
4602 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004603 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004604 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004605 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004606 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004607 if (ch == '(' || ch == '{') {
4608 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004609 if (!add_till_closing_bracket(dest, input, ch))
4610 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004611 o_addchr(dest, ch);
4612 continue;
4613 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004614 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004615 if (!add_till_single_quote(dest, input))
4616 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004617 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004618 continue;
4619 }
4620 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004621 if (!add_till_double_quote(dest, input))
4622 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004623 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004624 continue;
4625 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004626 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004627 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4628 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004629 o_addchr(dest, ch);
4630 continue;
4631 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004632 if (ch == '\\') {
4633 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004634 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004635 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004636 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004637 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004638 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004639#if 0
4640 if (ch == '\n') {
4641 /* "backslash+newline", ignore both */
4642 o_delchr(dest); /* undo insertion of '\' */
4643 continue;
4644 }
4645#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004646 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004647 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004648 continue;
4649 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004650 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004651 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004652 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004653}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004654#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004655
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004656/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004657#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004658#define parse_dollar(as_string, dest, input, quote_mask) \
4659 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004660#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004661#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004662static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004663 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004664 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004665{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004666 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004667
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004668 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004669 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004670 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004671 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004672 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004673 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004674 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004675 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004676 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004677 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004678 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004679 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004680 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004681 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004682 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004683 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004684 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004685 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004686 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004687 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004688 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004689 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004690 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004691 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004692 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004693 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004694 o_addchr(dest, ch | quote_mask);
4695 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004696 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004697 case '$': /* pid */
4698 case '!': /* last bg pid */
4699 case '?': /* last exit code */
4700 case '#': /* number of args */
4701 case '*': /* args */
4702 case '@': /* args */
4703 goto make_one_char_var;
4704 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004705 char len_single_ch;
4706
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004707 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4708
Denys Vlasenko74369502010-05-21 19:52:01 +02004709 ch = i_getch(input); /* eat '{' */
4710 nommu_addchr(as_string, ch);
4711
Denys Vlasenko46e64982016-09-29 19:50:55 +02004712 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004713 /* It should be ${?}, or ${#var},
4714 * or even ${?+subst} - operator acting on a special variable,
4715 * or the beginning of variable name.
4716 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004717 if (ch == EOF
4718 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4719 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004720 bad_dollar_syntax:
4721 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004722 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4723 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004724 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004725 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004726 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004727 ch |= quote_mask;
4728
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004729 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004730 * However, this regresses some of our testsuite cases
4731 * which check invalid constructs like ${%}.
4732 * Oh well... let's check that the var name part is fine... */
4733
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004734 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004735 unsigned pos;
4736
Denys Vlasenko74369502010-05-21 19:52:01 +02004737 o_addchr(dest, ch);
4738 debug_printf_parse(": '%c'\n", ch);
4739
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004740 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004741 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004742 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004743 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004744
Denys Vlasenko74369502010-05-21 19:52:01 +02004745 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004746 unsigned end_ch;
4747 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004748 /* handle parameter expansions
4749 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4750 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004751 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4752 if (len_single_ch != '#'
4753 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4754 || i_peek(input) != '}'
4755 ) {
4756 goto bad_dollar_syntax;
4757 }
4758 /* else: it's "length of C" ${#C} op,
4759 * where C is a single char
4760 * special var name, e.g. ${#!}.
4761 */
4762 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004763 /* Eat everything until closing '}' (or ':') */
4764 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004765 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004766 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004767 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004768 ) {
4769 /* It's ${var:N[:M]} thing */
4770 end_ch = '}' * 0x100 + ':';
4771 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004772 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004773 && ch == '/'
4774 ) {
4775 /* It's ${var/[/]pattern[/repl]} thing */
4776 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4777 i_getch(input);
4778 nommu_addchr(as_string, '/');
4779 ch = '\\';
4780 }
4781 end_ch = '}' * 0x100 + '/';
4782 }
4783 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004784 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004785 if (!BB_MMU)
4786 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004787#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004788 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004789 if (last_ch == 0) /* error? */
4790 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004791#else
4792#error Simple code to only allow ${var} is not implemented
4793#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004794 if (as_string) {
4795 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004796 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004797 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004798
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004799 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4800 && (end_ch & 0xff00)
4801 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004802 /* close the first block: */
4803 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004804 /* while parsing N from ${var:N[:M]}
4805 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004806 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004807 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004808 end_ch = '}';
4809 goto again;
4810 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004811 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004812 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004813 /* it's ${var:N} - emulate :999999999 */
4814 o_addstr(dest, "999999999");
4815 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004816 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004817 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004818 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004819 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004820 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004821 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4822 break;
4823 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004824#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004825 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004826 unsigned pos;
4827
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004828 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004829 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004830# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004831 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004832 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004833 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004834 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4835 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004836 if (!BB_MMU)
4837 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004838 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4839 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004840 if (as_string) {
4841 o_addstr(as_string, dest->data + pos);
4842 o_addchr(as_string, ')');
4843 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004844 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004845 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004846 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004847 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004848# endif
4849# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004850 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4851 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004852 if (!BB_MMU)
4853 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004854 if (!add_till_closing_bracket(dest, input, ')'))
4855 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004856 if (as_string) {
4857 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004858 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004859 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004860 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004861# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004862 break;
4863 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004864#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004865 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004866 goto make_var;
4867#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004868 /* TODO: $_ and $-: */
4869 /* $_ Shell or shell script name; or last argument of last command
4870 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4871 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004872 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004873 ch = i_getch(input);
4874 nommu_addchr(as_string, ch);
4875 ch = i_peek_and_eat_bkslash_nl(input);
4876 if (isalnum(ch)) { /* it's $_name or $_123 */
4877 ch = '_';
4878 goto make_var1;
4879 }
4880 /* else: it's $_ */
4881#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004882 default:
4883 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004884 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004885 debug_printf_parse("parse_dollar return 1 (ok)\n");
4886 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004887#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004888}
4889
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004890#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02004891#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004892 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004893#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004894#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004895static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004896 o_string *dest,
4897 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02004898 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004899{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004900 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004901 int next;
4902
4903 again:
4904 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004905 if (ch != EOF)
4906 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004907 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004908 debug_printf_parse("encode_string return 1 (ok)\n");
4909 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004910 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004911 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004912 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004913 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004914 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004915 }
4916 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004917 if (ch != '\n') {
4918 next = i_peek(input);
4919 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004920 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004921 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02004922 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004923 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02004924 /* Testcase: in interactive shell a file with
4925 * echo "unterminated string\<eof>
4926 * is sourced.
4927 */
4928 syntax_error_unterm_ch('"');
4929 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004930 }
4931 /* bash:
4932 * "The backslash retains its special meaning [in "..."]
4933 * only when followed by one of the following characters:
4934 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004935 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004936 * NB: in (unquoted) heredoc, above does not apply to ",
4937 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004938 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004939 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004940 ch = i_getch(input); /* eat next */
4941 if (ch == '\n')
4942 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004943 } /* else: ch remains == '\\', and we double it below: */
4944 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004945 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004946 goto again;
4947 }
4948 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004949 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4950 debug_printf_parse("encode_string return 0: "
4951 "parse_dollar returned 0 (error)\n");
4952 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004953 }
4954 goto again;
4955 }
4956#if ENABLE_HUSH_TICK
4957 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004958 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004959 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4960 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004961 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4962 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004963 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4964 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004965 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004966 }
4967#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004968 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004969 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004970#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004971}
4972
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004973/*
4974 * Scan input until EOF or end_trigger char.
4975 * Return a list of pipes to execute, or NULL on EOF
4976 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004977 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004978 * reset parsing machinery and start parsing anew,
4979 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004980 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004981static struct pipe *parse_stream(char **pstring,
4982 struct in_str *input,
4983 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004984{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004985 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004986 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004987
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004988 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004989 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004990 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004991 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004992 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004993 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004994
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004995 initialize_context(&ctx);
4996
4997 /* If very first arg is "" or '', ctx.word.data may end up NULL.
4998 * Preventing this:
4999 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005000 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005001
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005002 /* We used to separate words on $IFS here. This was wrong.
5003 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005004 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005005 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005006
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005007 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005008 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005009 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005010 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005011 int ch;
5012 int next;
5013 int redir_fd;
5014 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005015
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005016 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005017 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005018 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005019 if (ch == EOF) {
5020 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005021
5022 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005023 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005024 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005025 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005026 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005027 syntax_error_unterm_ch('(');
5028 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005029 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005030 if (end_trigger == '}') {
5031 syntax_error_unterm_ch('{');
5032 goto parse_error;
5033 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005034
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005035 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005036 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005037 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005038 o_free(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005039 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005040 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005041 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005042 /* (this makes bare "&" cmd a no-op.
5043 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005044 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005045 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005046 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005047 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005048 pi = NULL;
5049 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005050#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005051 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005052 if (pstring)
5053 *pstring = ctx.as_string.data;
5054 else
5055 o_free_unsafe(&ctx.as_string);
5056#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005057 debug_leave();
5058 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005059 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005060 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005061
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005062 /* Handle "'" and "\" first, as they won't play nice with
5063 * i_peek_and_eat_bkslash_nl() anyway:
5064 * echo z\\
5065 * and
5066 * echo '\
5067 * '
5068 * would break.
5069 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005070 if (ch == '\\') {
5071 ch = i_getch(input);
5072 if (ch == '\n')
5073 continue; /* drop \<newline>, get next char */
5074 nommu_addchr(&ctx.as_string, '\\');
5075 o_addchr(&ctx.word, '\\');
5076 if (ch == EOF) {
5077 /* Testcase: eval 'echo Ok\' */
5078 /* bash-4.3.43 was removing backslash,
5079 * but 4.4.19 retains it, most other shells too
5080 */
5081 continue; /* get next char */
5082 }
5083 /* Example: echo Hello \2>file
5084 * we need to know that word 2 is quoted
5085 */
5086 ctx.word.has_quoted_part = 1;
5087 nommu_addchr(&ctx.as_string, ch);
5088 o_addchr(&ctx.word, ch);
5089 continue; /* get next char */
5090 }
5091 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005092 if (ch == '\'') {
5093 ctx.word.has_quoted_part = 1;
5094 next = i_getch(input);
5095 if (next == '\'' && !ctx.pending_redirect)
5096 goto insert_empty_quoted_str_marker;
5097
5098 ch = next;
5099 while (1) {
5100 if (ch == EOF) {
5101 syntax_error_unterm_ch('\'');
5102 goto parse_error;
5103 }
5104 nommu_addchr(&ctx.as_string, ch);
5105 if (ch == '\'')
5106 break;
5107 if (ch == SPECIAL_VAR_SYMBOL) {
5108 /* Convert raw ^C to corresponding special variable reference */
5109 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5110 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5111 }
5112 o_addqchr(&ctx.word, ch);
5113 ch = i_getch(input);
5114 }
5115 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005116 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005117
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005118 next = '\0';
5119 if (ch != '\n')
5120 next = i_peek_and_eat_bkslash_nl(input);
5121
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005122 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005123 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005124 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005125 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005126 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005127 || ctx.word.length /* word{... - non-special */
5128 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005129 || (next != ';' /* }; - special */
5130 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005131 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005132 && next != '&' /* }& and }&& ... - special */
5133 && next != '|' /* }|| ... - special */
5134 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005135 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005136 ) {
5137 /* They are not special, skip "{}" */
5138 is_special += 2;
5139 }
5140 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005141 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005142
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005143 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005144 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005145 o_addQchr(&ctx.word, ch);
5146 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5147 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005148 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005149 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005150 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005151 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5152 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005153 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005154 continue;
5155 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005156
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005157 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005158#if ENABLE_HUSH_LINENO_VAR
5159/* Case:
5160 * "while ...; do<whitespace><newline>
5161 * cmd ..."
5162 * would think that "cmd" starts in <whitespace> -
5163 * i.e., at the previous line.
5164 * We need to skip all whitespace before newlines.
5165 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005166 while (ch != '\n') {
5167 next = i_peek(input);
5168 if (next != ' ' && next != '\t' && next != '\n')
5169 break; /* next char is not ws */
5170 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005171 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005172 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005173#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005174 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005175 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005176 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005177 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005178 /* Is this a case when newline is simply ignored?
5179 * Some examples:
5180 * "cmd | <newline> cmd ..."
5181 * "case ... in <newline> word) ..."
5182 */
5183 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005184 && ctx.word.length == 0 && !ctx.word.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005185 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005186 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005187 * Without check #1, interactive shell
5188 * ignores even bare <newline>,
5189 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005190 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005191 * ps2> _ <=== wrong, should be ps1
5192 * Without check #2, "cmd & <newline>"
5193 * is similarly mistreated.
5194 * (BTW, this makes "cmd & cmd"
5195 * and "cmd && cmd" non-orthogonal.
5196 * Really, ask yourself, why
5197 * "cmd && <newline>" doesn't start
5198 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005199 * The only reason is that it might be
5200 * a "cmd1 && <nl> cmd2 &" construct,
5201 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005202 */
5203 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005204 if (pi->num_cmds != 0 /* check #1 */
5205 && pi->followup != PIPE_BG /* check #2 */
5206 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005207 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005208 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005209 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005210 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005211 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005212 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5213 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005214 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005215 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005216 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005217 heredoc_cnt = 0;
5218 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005219 ctx.is_assignment = MAYBE_ASSIGNMENT;
5220 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005221 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005222 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005223 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005224 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005225 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005226
5227 /* "cmd}" or "cmd }..." without semicolon or &:
5228 * } is an ordinary char in this case, even inside { cmd; }
5229 * Pathological example: { ""}; } should exec "}" cmd
5230 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005231 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005232 if (ctx.word.length != 0 /* word} */
5233 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005234 ) {
5235 goto ordinary_char;
5236 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005237 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5238 /* Generally, there should be semicolon: "cmd; }"
5239 * However, bash allows to omit it if "cmd" is
5240 * a group. Examples:
5241 * { { echo 1; } }
5242 * {(echo 1)}
5243 * { echo 0 >&2 | { echo 1; } }
5244 * { while false; do :; done }
5245 * { case a in b) ;; esac }
5246 */
5247 if (ctx.command->group)
5248 goto term_group;
5249 goto ordinary_char;
5250 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005251 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005252 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005253 goto skip_end_trigger;
5254 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005255 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005256 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005257 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005258 && (ch != ';' || heredoc_cnt == 0)
5259#if ENABLE_HUSH_CASE
5260 && (ch != ')'
5261 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005262 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005263 )
5264#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005265 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005266 if (heredoc_cnt) {
5267 /* This is technically valid:
5268 * { cat <<HERE; }; echo Ok
5269 * heredoc
5270 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005271 * HERE
5272 * but we don't support this.
5273 * We require heredoc to be in enclosing {}/(),
5274 * if any.
5275 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005276 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005277 goto parse_error;
5278 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005279 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005280 goto parse_error;
5281 }
5282 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005283 ctx.is_assignment = MAYBE_ASSIGNMENT;
5284 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005285 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005286 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005287 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005288 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005289 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005290#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005291 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005292 if (pstring)
5293 *pstring = ctx.as_string.data;
5294 else
5295 o_free_unsafe(&ctx.as_string);
5296#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005297 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5298 /* Example: bare "{ }", "()" */
5299 G.last_exitcode = 2; /* bash compat */
5300 syntax_error_unexpected_ch(ch);
5301 goto parse_error2;
5302 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005303 debug_printf_parse("parse_stream return %p: "
5304 "end_trigger char found\n",
5305 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005306 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005307 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005308 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005309 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005310
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005311 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005312 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005313
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005314 /* Catch <, > before deciding whether this word is
5315 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5316 switch (ch) {
5317 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005318 redir_fd = redirect_opt_num(&ctx.word);
5319 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005320 goto parse_error;
5321 }
5322 redir_style = REDIRECT_OVERWRITE;
5323 if (next == '>') {
5324 redir_style = REDIRECT_APPEND;
5325 ch = i_getch(input);
5326 nommu_addchr(&ctx.as_string, ch);
5327 }
5328#if 0
5329 else if (next == '(') {
5330 syntax_error(">(process) not supported");
5331 goto parse_error;
5332 }
5333#endif
5334 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5335 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005336 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005337 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005338 redir_fd = redirect_opt_num(&ctx.word);
5339 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005340 goto parse_error;
5341 }
5342 redir_style = REDIRECT_INPUT;
5343 if (next == '<') {
5344 redir_style = REDIRECT_HEREDOC;
5345 heredoc_cnt++;
5346 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5347 ch = i_getch(input);
5348 nommu_addchr(&ctx.as_string, ch);
5349 } else if (next == '>') {
5350 redir_style = REDIRECT_IO;
5351 ch = i_getch(input);
5352 nommu_addchr(&ctx.as_string, ch);
5353 }
5354#if 0
5355 else if (next == '(') {
5356 syntax_error("<(process) not supported");
5357 goto parse_error;
5358 }
5359#endif
5360 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5361 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005362 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005363 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005364 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005365 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005366 /* note: we do not add it to &ctx.as_string */
5367/* TODO: in bash:
5368 * comment inside $() goes to the next \n, even inside quoted string (!):
5369 * cmd "$(cmd2 #comment)" - syntax error
5370 * cmd "`cmd2 #comment`" - ok
5371 * We accept both (comment ends where command subst ends, in both cases).
5372 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005373 while (1) {
5374 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005375 if (ch == '\n') {
5376 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005377 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005378 }
5379 ch = i_getch(input);
5380 if (ch == EOF)
5381 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005382 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005383 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005384 }
5385 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005386 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005387 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005388
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005389 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005390 /* check that we are not in word in "a=1 2>word b=1": */
5391 && !ctx.pending_redirect
5392 ) {
5393 /* ch is a special char and thus this word
5394 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005395 ctx.is_assignment = NOT_ASSIGNMENT;
5396 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005397 }
5398
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005399 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5400
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005401 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005402 case SPECIAL_VAR_SYMBOL:
5403 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005404 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5405 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005406 /* fall through */
5407 case '#':
5408 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005409 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005410 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005411 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005412 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005413 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005414 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005415 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005416 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005417 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005418 case '"':
5419 ctx.word.has_quoted_part = 1;
5420 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005421 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005422 insert_empty_quoted_str_marker:
5423 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005424 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5425 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005426 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005427 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005428 if (ctx.is_assignment == NOT_ASSIGNMENT)
5429 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005430 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005431 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005432 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005433 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005434#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005435 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005436 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005437
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005438 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5439 o_addchr(&ctx.word, '`');
5440 USE_FOR_NOMMU(pos = ctx.word.length;)
5441 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005442 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005443# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005444 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005445 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005446# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005447 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5448 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005449 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005450 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005451#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005452 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005453#if ENABLE_HUSH_CASE
5454 case_semi:
5455#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005456 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005457 goto parse_error;
5458 }
5459 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005460#if ENABLE_HUSH_CASE
5461 /* Eat multiple semicolons, detect
5462 * whether it means something special */
5463 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005464 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005465 if (ch != ';')
5466 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005467 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005468 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005469 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005470 ctx.ctx_dsemicolon = 1;
5471 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005472 break;
5473 }
5474 }
5475#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005476 new_cmd:
5477 /* We just finished a cmd. New one may start
5478 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005479 ctx.is_assignment = MAYBE_ASSIGNMENT;
5480 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005481 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005482 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005483 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005484 goto parse_error;
5485 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005486 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005487 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005488 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005489 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005490 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005491 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005492 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005493 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005494 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005495 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005496 goto parse_error;
5497 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005498#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005499 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005500 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005501#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005502 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005503 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005504 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005505 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005506 } else {
5507 /* we could pick up a file descriptor choice here
5508 * with redirect_opt_num(), but bash doesn't do it.
5509 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005510 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005511 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005512 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005513 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005514#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005515 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005516 if (ctx.ctx_res_w == RES_MATCH
5517 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005518 && ctx.word.length == 0 /* not word(... */
5519 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005520 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005521 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005522 }
5523#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005524 case '{':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005525 if (parse_group(&ctx, input, ch) != 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005526 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005527 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005528 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005529 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005530#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005531 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005532 goto case_semi;
5533#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005534 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005535 /* proper use of this character is caught by end_trigger:
5536 * if we see {, we call parse_group(..., end_trigger='}')
5537 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005538 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005539 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005540 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005541 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005542 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005543 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005544 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005545 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005546
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005547 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005548 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005549 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005550 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005551 struct parse_context *pctx;
5552 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005553
5554 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005555 * Sample for finding leaks on syntax error recovery path.
5556 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005557 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005558 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005559 * while if (true | { true;}); then echo ok; fi; do break; done
5560 * 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 +00005561 */
5562 pctx = &ctx;
5563 do {
5564 /* Update pipe/command counts,
5565 * otherwise freeing may miss some */
5566 done_pipe(pctx, PIPE_SEQ);
5567 debug_printf_clean("freeing list %p from ctx %p\n",
5568 pctx->list_head, pctx);
5569 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005570 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005571 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005572#if !BB_MMU
5573 o_free_unsafe(&pctx->as_string);
5574#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005575 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005576 if (pctx != &ctx) {
5577 free(pctx);
5578 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005579 IF_HAS_KEYWORDS(pctx = p2;)
5580 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005581
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005582 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005583#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005584 if (pstring)
5585 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005586#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005587 debug_leave();
5588 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005589 }
Eric Andersen25f27032001-04-26 23:22:31 +00005590}
5591
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005592
5593/*** Execution routines ***/
5594
5595/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005596#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005597#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005598 expand_string_to_string(str)
5599#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005600static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005601#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005602static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005603#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005604
5605/* expand_strvec_to_strvec() takes a list of strings, expands
5606 * all variable references within and returns a pointer to
5607 * a list of expanded strings, possibly with larger number
5608 * of strings. (Think VAR="a b"; echo $VAR).
5609 * This new list is allocated as a single malloc block.
5610 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005611 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005612 * Caller can deallocate entire list by single free(list). */
5613
Denys Vlasenko238081f2010-10-03 14:26:26 +02005614/* A horde of its helpers come first: */
5615
5616static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5617{
5618 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005619 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005620
Denys Vlasenko9e800222010-10-03 14:28:04 +02005621#if ENABLE_HUSH_BRACE_EXPANSION
5622 if (c == '{' || c == '}') {
5623 /* { -> \{, } -> \} */
5624 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005625 /* And now we want to add { or } and continue:
5626 * o_addchr(o, c);
5627 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005628 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005629 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005630 }
5631#endif
5632 o_addchr(o, c);
5633 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005634 /* \z -> \\\z; \<eol> -> \\<eol> */
5635 o_addchr(o, '\\');
5636 if (len) {
5637 len--;
5638 o_addchr(o, '\\');
5639 o_addchr(o, *str++);
5640 }
5641 }
5642 }
5643}
5644
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005645/* Store given string, finalizing the word and starting new one whenever
5646 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005647 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5648 * Return in *ended_with_ifs:
5649 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5650 */
5651static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005652{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005653 int last_is_ifs = 0;
5654
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005655 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005656 int word_len;
5657
5658 if (!*str) /* EOL - do not finalize word */
5659 break;
5660 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005661 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005662 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005663 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005664 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005665 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005666 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005667 * Example: "v='\*'; echo b$v" prints "b\*"
5668 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005669 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005670 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005671 /*/ Why can't we do it easier? */
5672 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5673 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5674 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005675 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005676 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005677 if (!*str) /* EOL - do not finalize word */
5678 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005679 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005680
5681 /* We know str here points to at least one IFS char */
5682 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005683 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005684 if (!*str) /* EOL - do not finalize word */
5685 break;
5686
Denys Vlasenko96786362018-04-11 16:02:58 +02005687 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5688 && strchr(G.ifs, *str) /* the second check would fail */
5689 ) {
5690 /* This is a non-whitespace $IFS char */
5691 /* Skip it and IFS whitespace chars, start new word */
5692 str++;
5693 str += strspn(str, G.ifs_whitespace);
5694 goto new_word;
5695 }
5696
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005697 /* Start new word... but not always! */
5698 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005699 if (output->has_quoted_part
5700 /* Case "v=' a'; echo $v":
5701 * here nothing precedes the space in $v expansion,
5702 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005703 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005704 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005705 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005706 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005707 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005708 o_addchr(output, '\0');
5709 debug_print_list("expand_on_ifs", output, n);
5710 n = o_save_ptr(output, n);
5711 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005712 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005713
5714 if (ended_with_ifs)
5715 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005716 debug_print_list("expand_on_ifs[1]", output, n);
5717 return n;
5718}
5719
5720/* Helper to expand $((...)) and heredoc body. These act as if
5721 * they are in double quotes, with the exception that they are not :).
5722 * Just the rules are similar: "expand only $var and `cmd`"
5723 *
5724 * Returns malloced string.
5725 * As an optimization, we return NULL if expansion is not needed.
5726 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005727static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005728{
5729 char *exp_str;
5730 struct in_str input;
5731 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005732 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005733
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005734 cp = str;
5735 for (;;) {
5736 if (!*cp) return NULL; /* string has no special chars */
5737 if (*cp == '$') break;
5738 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005739#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005740 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005741#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005742 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005743 }
5744
5745 /* We need to expand. Example:
5746 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5747 */
5748 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005749 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005750//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005751 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005752 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005753 EXP_FLAG_ESC_GLOB_CHARS,
5754 /*unbackslash:*/ 1
5755 );
5756 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5757 o_free_unsafe(&dest);
5758 return exp_str;
5759}
5760
5761#if !BASH_PATTERN_SUBST
5762#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5763 encode_then_expand_vararg(str, handle_squotes)
5764#endif
5765static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5766{
5767#if !BASH_PATTERN_SUBST
5768 const int do_unbackslash = 0;
5769#endif
5770 char *exp_str;
5771 struct in_str input;
5772 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005773 const char *cp;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005774
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005775 cp = str;
5776 for (;;) {
5777 if (!*cp) return NULL; /* string has no special chars */
5778 if (*cp == '$') break;
5779 if (*cp == '\\') break;
5780 if (*cp == '\'') break;
5781 if (*cp == '"') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005782#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005783 if (*cp == '`') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005784#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005785 cp++;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005786 }
5787
5788 /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5789 * These can contain single- and double-quoted strings,
5790 * and treated as if the ARG string is initially unquoted. IOW:
5791 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5792 * a dquoted string: "${var#"zz"}"), the difference only comes later
5793 * (word splitting and globbing of the ${var...} result).
5794 */
5795
5796 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005797 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005798 exp_str = NULL;
5799
5800 for (;;) {
5801 int ch;
5802 int next;
5803
5804 ch = i_getch(&input);
5805 if (ch == EOF) {
5806 if (dest.o_expflags) { /* EXP_FLAG_ESC_GLOB_CHARS set? */
5807 syntax_error_unterm_ch('"');
5808 goto ret; /* error */
5809 }
5810 break;
5811 }
5812 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5813 __func__, ch, ch, !!dest.o_expflags);
5814 if (ch == '\'' && handle_squotes && !dest.o_expflags) {
5815//quoting version of add_till_single_quote() (try to merge?):
5816 for (;;) {
5817 ch = i_getch(&input);
5818 if (ch == EOF) {
5819 syntax_error_unterm_ch('\'');
5820 goto ret; /* error */
5821 }
5822 if (ch == '\'')
5823 break;
5824 o_addqchr(&dest, ch);
5825 }
5826 continue;
5827 }
5828 if (ch == '"') {
5829 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5830 continue;
5831 }
5832 if (ch == '\\') {
5833 ch = i_getch(&input);
5834 if (ch == EOF) {
5835//example? error message? syntax_error_unterm_ch('"');
5836 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5837 goto ret;
5838 }
5839 o_addqchr(&dest, ch);
5840 continue;
5841 }
5842 next = '\0';
5843 if (ch != '\n') {
5844 next = i_peek(&input);
5845 }
5846 if (ch == '$') {
5847 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5848 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5849 goto ret;
5850 }
5851 continue;
5852 }
5853#if ENABLE_HUSH_TICK
5854 if (ch == '`') {
5855 //unsigned pos = dest->length;
5856 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5857 o_addchr(&dest, 0x80 | '`');
5858 if (!add_till_backquote(&dest, &input,
5859 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5860 )
5861 ) {
5862 goto ret; /* error */
5863 }
5864 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5865 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5866 continue;
5867 }
5868#endif
5869 o_addQchr(&dest, ch);
5870 } /* for (;;) */
5871
5872 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5873 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02005874 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5875 do_unbackslash
5876 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02005877 ret:
5878 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005879 o_free_unsafe(&dest);
5880 return exp_str;
5881}
5882
Denys Vlasenko0b883582016-12-23 16:49:07 +01005883#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005884static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005885{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005886 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005887 arith_t res;
5888 char *exp_str;
5889
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005890 math_state.lookupvar = get_local_var_value;
5891 math_state.setvar = set_local_var_from_halves;
5892 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005893 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005894 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005895 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005896 if (errmsg_p)
5897 *errmsg_p = math_state.errmsg;
5898 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005899 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005900 return res;
5901}
5902#endif
5903
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005904#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005905/* ${var/[/]pattern[/repl]} helpers */
5906static char *strstr_pattern(char *val, const char *pattern, int *size)
5907{
5908 while (1) {
5909 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5910 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5911 if (end) {
5912 *size = end - val;
5913 return val;
5914 }
5915 if (*val == '\0')
5916 return NULL;
5917 /* Optimization: if "*pat" did not match the start of "string",
5918 * we know that "tring", "ring" etc will not match too:
5919 */
5920 if (pattern[0] == '*')
5921 return NULL;
5922 val++;
5923 }
5924}
5925static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5926{
5927 char *result = NULL;
5928 unsigned res_len = 0;
5929 unsigned repl_len = strlen(repl);
5930
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005931 /* Null pattern never matches, including if "var" is empty */
5932 if (!pattern[0])
5933 return result; /* NULL, no replaces happened */
5934
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005935 while (1) {
5936 int size;
5937 char *s = strstr_pattern(val, pattern, &size);
5938 if (!s)
5939 break;
5940
5941 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005942 strcpy(mempcpy(result + res_len, val, s - val), repl);
5943 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005944 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5945
5946 val = s + size;
5947 if (exp_op == '/')
5948 break;
5949 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005950 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005951 result = xrealloc(result, res_len + strlen(val) + 1);
5952 strcpy(result + res_len, val);
5953 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5954 }
5955 debug_printf_varexp("result:'%s'\n", result);
5956 return result;
5957}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005958#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005959
5960/* Helper:
5961 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5962 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005963static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005964{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005965 const char *val;
5966 char *to_be_freed;
5967 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005968 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005969 char exp_op;
5970 char exp_save = exp_save; /* for compiler */
5971 char *exp_saveptr; /* points to expansion operator */
5972 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005973 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005974
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005975 val = NULL;
5976 to_be_freed = NULL;
5977 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005978 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005979 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005980 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005981 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02005982 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005983 exp_op = 0;
5984
Denys Vlasenkob762c782018-07-17 14:21:38 +02005985 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005986 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5987 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5988 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005989 ) {
5990 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005991 var++;
5992 exp_op = 'L';
5993 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005994 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005995 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005996 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005997 ) {
5998 /* ${?:0}, ${#[:]%0} etc */
5999 exp_saveptr = var + 1;
6000 } else {
6001 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6002 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6003 }
6004 exp_op = exp_save = *exp_saveptr;
6005 if (exp_op) {
6006 exp_word = exp_saveptr + 1;
6007 if (exp_op == ':') {
6008 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006009//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006010 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006011 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006012 ) {
6013 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6014 exp_op = ':';
6015 exp_word--;
6016 }
6017 }
6018 *exp_saveptr = '\0';
6019 } /* else: it's not an expansion op, but bare ${var} */
6020 }
6021
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006022 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006023 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006024 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006025 int n = xatoi_positive(var);
6026 if (n < G.global_argc)
6027 val = G.global_argv[n];
6028 /* else val remains NULL: $N with too big N */
6029 } else {
6030 switch (var[0]) {
6031 case '$': /* pid */
6032 val = utoa(G.root_pid);
6033 break;
6034 case '!': /* bg pid */
6035 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6036 break;
6037 case '?': /* exitcode */
6038 val = utoa(G.last_exitcode);
6039 break;
6040 case '#': /* argc */
6041 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6042 break;
6043 default:
6044 val = get_local_var_value(var);
6045 }
6046 }
6047
6048 /* Handle any expansions */
6049 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006050 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006051 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006052 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006053 debug_printf_expand("%s\n", val);
6054 } else if (exp_op) {
6055 if (exp_op == '%' || exp_op == '#') {
6056 /* Standard-mandated substring removal ops:
6057 * ${parameter%word} - remove smallest suffix pattern
6058 * ${parameter%%word} - remove largest suffix pattern
6059 * ${parameter#word} - remove smallest prefix pattern
6060 * ${parameter##word} - remove largest prefix pattern
6061 *
6062 * Word is expanded to produce a glob pattern.
6063 * Then var's value is matched to it and matching part removed.
6064 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006065//FIXME: ${x#...${...}...}
6066//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6067//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006068 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006069 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006070 char *exp_exp_word;
6071 char *loc;
6072 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006073 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006074 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006075 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006076 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006077 if (exp_exp_word)
6078 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006079 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6080 /*
6081 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006082 * G.global_argv and results of utoa and get_local_var_value
6083 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006084 * scan_and_match momentarily stores NULs there.
6085 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006086 t = (char*)val;
6087 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006088 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 +02006089 free(exp_exp_word);
6090 if (loc) { /* match was found */
6091 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006092 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006093 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006094 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006095 }
6096 }
6097 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006098#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006099 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006100 /* It's ${var/[/]pattern[/repl]} thing.
6101 * Note that in encoded form it has TWO parts:
6102 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006103 * and if // is used, it is encoded as \:
6104 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006105 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006106 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006107 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006108 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006109 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006110 * >az >bz
6111 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6112 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6113 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6114 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006115 * (note that a*z _pattern_ is never globbed!)
6116 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006117 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006118 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006119 if (!pattern)
6120 pattern = xstrdup(exp_word);
6121 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6122 *p++ = SPECIAL_VAR_SYMBOL;
6123 exp_word = p;
6124 p = strchr(p, SPECIAL_VAR_SYMBOL);
6125 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006126 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006127 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6128 /* HACK ALERT. We depend here on the fact that
6129 * G.global_argv and results of utoa and get_local_var_value
6130 * are actually in writable memory:
6131 * replace_pattern momentarily stores NULs there. */
6132 t = (char*)val;
6133 to_be_freed = replace_pattern(t,
6134 pattern,
6135 (repl ? repl : exp_word),
6136 exp_op);
6137 if (to_be_freed) /* at least one replace happened */
6138 val = to_be_freed;
6139 free(pattern);
6140 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006141 } else {
6142 /* Empty variable always gives nothing */
6143 // "v=''; echo ${v/*/w}" prints "", not "w"
6144 /* Just skip "replace" part */
6145 *p++ = SPECIAL_VAR_SYMBOL;
6146 p = strchr(p, SPECIAL_VAR_SYMBOL);
6147 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006148 }
6149 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006150#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006151 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006152#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006153 /* It's ${var:N[:M]} bashism.
6154 * Note that in encoded form it has TWO parts:
6155 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6156 */
6157 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006158 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006159
Denys Vlasenko063847d2010-09-15 13:33:02 +02006160 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6161 if (errmsg)
6162 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006163 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6164 *p++ = SPECIAL_VAR_SYMBOL;
6165 exp_word = p;
6166 p = strchr(p, SPECIAL_VAR_SYMBOL);
6167 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006168 len = expand_and_evaluate_arith(exp_word, &errmsg);
6169 if (errmsg)
6170 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006171 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006172 if (beg < 0) {
6173 /* negative beg counts from the end */
6174 beg = (arith_t)strlen(val) + beg;
6175 if (beg < 0) /* ${v: -999999} is "" */
6176 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006177 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006178 debug_printf_varexp("from val:'%s'\n", val);
6179 if (len < 0) {
6180 /* in bash, len=-n means strlen()-n */
6181 len = (arith_t)strlen(val) - beg + len;
6182 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006183 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006184 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006185 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006186 arith_err:
6187 val = NULL;
6188 } else {
6189 /* Paranoia. What if user entered 9999999999999
6190 * which fits in arith_t but not int? */
6191 if (len >= INT_MAX)
6192 len = INT_MAX;
6193 val = to_be_freed = xstrndup(val + beg, len);
6194 }
6195 debug_printf_varexp("val:'%s'\n", val);
6196#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006197 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006198 val = NULL;
6199#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006200 } else { /* one of "-=+?" */
6201 /* Standard-mandated substitution ops:
6202 * ${var?word} - indicate error if unset
6203 * If var is unset, word (or a message indicating it is unset
6204 * if word is null) is written to standard error
6205 * and the shell exits with a non-zero exit status.
6206 * Otherwise, the value of var is substituted.
6207 * ${var-word} - use default value
6208 * If var is unset, word is substituted.
6209 * ${var=word} - assign and use default value
6210 * If var is unset, word is assigned to var.
6211 * In all cases, final value of var is substituted.
6212 * ${var+word} - use alternative value
6213 * If var is unset, null is substituted.
6214 * Otherwise, word is substituted.
6215 *
6216 * Word is subjected to tilde expansion, parameter expansion,
6217 * command substitution, and arithmetic expansion.
6218 * If word is not needed, it is not expanded.
6219 *
6220 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6221 * but also treat null var as if it is unset.
6222 */
6223 int use_word = (!val || ((exp_save == ':') && !val[0]));
6224 if (exp_op == '+')
6225 use_word = !use_word;
6226 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6227 (exp_save == ':') ? "true" : "false", use_word);
6228 if (use_word) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02006229//FIXME: unquoted ${x:+"b c" d} and ${x:+'b c' d} should expand to two words
6230//currently it expands to three.
6231 to_be_freed = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ !(arg0 & 0x80), /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006232 if (to_be_freed)
6233 exp_word = to_be_freed;
6234 if (exp_op == '?') {
6235 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006236 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006237 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02006238 exp_word[0]
6239 ? exp_word
6240 : "parameter null or not set"
6241 /* ash has more specific messages, a-la: */
6242 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006243 );
6244//TODO: how interactive bash aborts expansion mid-command?
6245 } else {
6246 val = exp_word;
6247 }
6248
6249 if (exp_op == '=') {
6250 /* ${var=[word]} or ${var:=[word]} */
6251 if (isdigit(var[0]) || var[0] == '#') {
6252 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006253 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006254 val = NULL;
6255 } else {
6256 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02006257 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006258 }
6259 }
6260 }
6261 } /* one of "-=+?" */
6262
6263 *exp_saveptr = exp_save;
6264 } /* if (exp_op) */
6265
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006266 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006267
6268 *pp = p;
6269 *to_be_freed_pp = to_be_freed;
6270 return val;
6271}
6272
6273/* Expand all variable references in given string, adding words to list[]
6274 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6275 * to be filled). This routine is extremely tricky: has to deal with
6276 * variables/parameters with whitespace, $* and $@, and constructs like
6277 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006278static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006279{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006280 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006281 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006282 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006283 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006284 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006285 char *p;
6286
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006287 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6288 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006289 debug_print_list("expand_vars_to_list", output, n);
6290 n = o_save_ptr(output, n);
6291 debug_print_list("expand_vars_to_list[0]", output, n);
6292
6293 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6294 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006295 char *to_be_freed = NULL;
6296 const char *val = NULL;
6297#if ENABLE_HUSH_TICK
6298 o_string subst_result = NULL_O_STRING;
6299#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006300#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006301 char arith_buf[sizeof(arith_t)*3 + 2];
6302#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006303
6304 if (ended_in_ifs) {
6305 o_addchr(output, '\0');
6306 n = o_save_ptr(output, n);
6307 ended_in_ifs = 0;
6308 }
6309
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006310 o_addblock(output, arg, p - arg);
6311 debug_print_list("expand_vars_to_list[1]", output, n);
6312 arg = ++p;
6313 p = strchr(p, SPECIAL_VAR_SYMBOL);
6314
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006315 /* Fetch special var name (if it is indeed one of them)
6316 * and quote bit, force the bit on if singleword expansion -
6317 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006318 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006319
6320 /* Is this variable quoted and thus expansion can't be null?
6321 * "$@" is special. Even if quoted, it can still
6322 * expand to nothing (not even an empty string),
6323 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006324 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006325 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006326
6327 switch (first_ch & 0x7f) {
6328 /* Highest bit in first_ch indicates that var is double-quoted */
6329 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006330 case '@': {
6331 int i;
6332 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006333 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006334 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006335 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006336 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006337 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006338 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006339 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6340 if (G.global_argv[i++][0] && G.global_argv[i]) {
6341 /* this argv[] is not empty and not last:
6342 * put terminating NUL, start new word */
6343 o_addchr(output, '\0');
6344 debug_print_list("expand_vars_to_list[2]", output, n);
6345 n = o_save_ptr(output, n);
6346 debug_print_list("expand_vars_to_list[3]", output, n);
6347 }
6348 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006349 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006350 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006351 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006352 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006353 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006354 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006355 while (1) {
6356 o_addQstr(output, G.global_argv[i]);
6357 if (++i >= G.global_argc)
6358 break;
6359 o_addchr(output, '\0');
6360 debug_print_list("expand_vars_to_list[4]", output, n);
6361 n = o_save_ptr(output, n);
6362 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006363 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006364 while (1) {
6365 o_addQstr(output, G.global_argv[i]);
6366 if (!G.global_argv[++i])
6367 break;
6368 if (G.ifs[0])
6369 o_addchr(output, G.ifs[0]);
6370 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006371 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006372 }
6373 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006374 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006375 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6376 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006377 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006378 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006379 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006380 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006381 case SPECIAL_VAR_QUOTED_SVS:
6382 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6383 arg++;
6384 val = SPECIAL_VAR_SYMBOL_STR;
6385 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006386#if ENABLE_HUSH_TICK
6387 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006388 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006389 arg++;
6390 /* Can't just stuff it into output o_string,
6391 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006392 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006393 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6394 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006395 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006396 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6397 val = subst_result.data;
6398 goto store_val;
6399#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006400#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006401 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6402 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006403
6404 arg++; /* skip '+' */
6405 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6406 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006407 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006408 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6409 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006410 val = arith_buf;
6411 break;
6412 }
6413#endif
6414 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006415 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006416 IF_HUSH_TICK(store_val:)
6417 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006418 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6419 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006420 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006421 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006422 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006423 }
6424 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006425 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006426 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6427 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006428 }
6429 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006430 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6431
6432 if (val && val[0]) {
6433 o_addQstr(output, val);
6434 }
6435 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006436
6437 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6438 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006439 if (*p != SPECIAL_VAR_SYMBOL)
6440 *p = SPECIAL_VAR_SYMBOL;
6441
6442#if ENABLE_HUSH_TICK
6443 o_free(&subst_result);
6444#endif
6445 arg = ++p;
6446 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6447
6448 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006449 if (ended_in_ifs) {
6450 o_addchr(output, '\0');
6451 n = o_save_ptr(output, n);
6452 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006453 debug_print_list("expand_vars_to_list[a]", output, n);
6454 /* this part is literal, and it was already pre-quoted
6455 * if needed (much earlier), do not use o_addQstr here! */
6456 o_addstr_with_NUL(output, arg);
6457 debug_print_list("expand_vars_to_list[b]", output, n);
6458 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006459 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006460 ) {
6461 n--;
6462 /* allow to reuse list[n] later without re-growth */
6463 output->has_empty_slot = 1;
6464 } else {
6465 o_addchr(output, '\0');
6466 }
6467
6468 return n;
6469}
6470
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006471static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006472{
6473 int n;
6474 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006475 o_string output = NULL_O_STRING;
6476
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006477 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006478
6479 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006480 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006481 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006482 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006483 }
6484 debug_print_list("expand_variables", &output, n);
6485
6486 /* output.data (malloced in one block) gets returned in "list" */
6487 list = o_finalize_list(&output, n);
6488 debug_print_strings("expand_variables[1]", list);
6489 return list;
6490}
6491
6492static char **expand_strvec_to_strvec(char **argv)
6493{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006494 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006495}
6496
Denys Vlasenko11752d42018-04-03 08:20:58 +02006497#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006498static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6499{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006500 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006501}
6502#endif
6503
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006504/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006505 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006506 *
6507 * NB: should NOT do globbing!
6508 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6509 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006510static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006511{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006512#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006513 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006514 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006515#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006516 char *argv[2], **list;
6517
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006518 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006519 /* This is generally an optimization, but it also
6520 * handles "", which otherwise trips over !list[0] check below.
6521 * (is this ever happens that we actually get str="" here?)
6522 */
6523 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6524 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006525 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006526 return xstrdup(str);
6527 }
6528
6529 argv[0] = (char*)str;
6530 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006531 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006532 if (HUSH_DEBUG)
6533 if (!list[0] || list[1])
6534 bb_error_msg_and_die("BUG in varexp2");
6535 /* actually, just move string 2*sizeof(char*) bytes back */
6536 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006537 if (do_unbackslash)
6538 unbackslash((char*)list);
6539 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006540 return (char*)list;
6541}
6542
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006543#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006544static char* expand_strvec_to_string(char **argv)
6545{
6546 char **list;
6547
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006548 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006549 /* Convert all NULs to spaces */
6550 if (list[0]) {
6551 int n = 1;
6552 while (list[n]) {
6553 if (HUSH_DEBUG)
6554 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6555 bb_error_msg_and_die("BUG in varexp3");
6556 /* bash uses ' ' regardless of $IFS contents */
6557 list[n][-1] = ' ';
6558 n++;
6559 }
6560 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006561 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006562 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6563 return (char*)list;
6564}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006565#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006566
6567static char **expand_assignments(char **argv, int count)
6568{
6569 int i;
6570 char **p;
6571
6572 G.expanded_assignments = p = NULL;
6573 /* Expand assignments into one string each */
6574 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006575 p = add_string_to_strings(p,
6576 expand_string_to_string(argv[i],
6577 EXP_FLAG_ESC_GLOB_CHARS,
6578 /*unbackslash:*/ 1
6579 )
6580 );
6581 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006582 }
6583 G.expanded_assignments = NULL;
6584 return p;
6585}
6586
6587
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006588static void switch_off_special_sigs(unsigned mask)
6589{
6590 unsigned sig = 0;
6591 while ((mask >>= 1) != 0) {
6592 sig++;
6593 if (!(mask & 1))
6594 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006595#if ENABLE_HUSH_TRAP
6596 if (G_traps) {
6597 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006598 /* trap is '', has to remain SIG_IGN */
6599 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006600 free(G_traps[sig]);
6601 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006602 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006603#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006604 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006605 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006606 }
6607}
6608
Denys Vlasenkob347df92011-08-09 22:49:15 +02006609#if BB_MMU
6610/* never called */
6611void re_execute_shell(char ***to_free, const char *s,
6612 char *g_argv0, char **g_argv,
6613 char **builtin_argv) NORETURN;
6614
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006615static void reset_traps_to_defaults(void)
6616{
6617 /* This function is always called in a child shell
6618 * after fork (not vfork, NOMMU doesn't use this function).
6619 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006620 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006621 unsigned mask;
6622
6623 /* Child shells are not interactive.
6624 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6625 * Testcase: (while :; do :; done) + ^Z should background.
6626 * Same goes for SIGTERM, SIGHUP, SIGINT.
6627 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006628 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006629 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006630 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006631
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006632 /* Switch off special sigs */
6633 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006634# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006635 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006636# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006637 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006638 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6639 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006640
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006641# if ENABLE_HUSH_TRAP
6642 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006643 return;
6644
6645 /* Reset all sigs to default except ones with empty traps */
6646 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006647 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006648 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006649 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006650 continue; /* empty trap: has to remain SIG_IGN */
6651 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006652 free(G_traps[sig]);
6653 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006654 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006655 if (sig == 0)
6656 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006657 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006658 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006659# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006660}
6661
6662#else /* !BB_MMU */
6663
6664static void re_execute_shell(char ***to_free, const char *s,
6665 char *g_argv0, char **g_argv,
6666 char **builtin_argv) NORETURN;
6667static void re_execute_shell(char ***to_free, const char *s,
6668 char *g_argv0, char **g_argv,
6669 char **builtin_argv)
6670{
6671# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6672 /* delims + 2 * (number of bytes in printed hex numbers) */
6673 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6674 char *heredoc_argv[4];
6675 struct variable *cur;
6676# if ENABLE_HUSH_FUNCTIONS
6677 struct function *funcp;
6678# endif
6679 char **argv, **pp;
6680 unsigned cnt;
6681 unsigned long long empty_trap_mask;
6682
6683 if (!g_argv0) { /* heredoc */
6684 argv = heredoc_argv;
6685 argv[0] = (char *) G.argv0_for_re_execing;
6686 argv[1] = (char *) "-<";
6687 argv[2] = (char *) s;
6688 argv[3] = NULL;
6689 pp = &argv[3]; /* used as pointer to empty environment */
6690 goto do_exec;
6691 }
6692
6693 cnt = 0;
6694 pp = builtin_argv;
6695 if (pp) while (*pp++)
6696 cnt++;
6697
6698 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006699 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006700 int sig;
6701 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006702 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006703 empty_trap_mask |= 1LL << sig;
6704 }
6705 }
6706
6707 sprintf(param_buf, NOMMU_HACK_FMT
6708 , (unsigned) G.root_pid
6709 , (unsigned) G.root_ppid
6710 , (unsigned) G.last_bg_pid
6711 , (unsigned) G.last_exitcode
6712 , cnt
6713 , empty_trap_mask
6714 IF_HUSH_LOOPS(, G.depth_of_loop)
6715 );
6716# undef NOMMU_HACK_FMT
6717 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6718 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6719 */
6720 cnt += 6;
6721 for (cur = G.top_var; cur; cur = cur->next) {
6722 if (!cur->flg_export || cur->flg_read_only)
6723 cnt += 2;
6724 }
6725# if ENABLE_HUSH_FUNCTIONS
6726 for (funcp = G.top_func; funcp; funcp = funcp->next)
6727 cnt += 3;
6728# endif
6729 pp = g_argv;
6730 while (*pp++)
6731 cnt++;
6732 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6733 *pp++ = (char *) G.argv0_for_re_execing;
6734 *pp++ = param_buf;
6735 for (cur = G.top_var; cur; cur = cur->next) {
6736 if (strcmp(cur->varstr, hush_version_str) == 0)
6737 continue;
6738 if (cur->flg_read_only) {
6739 *pp++ = (char *) "-R";
6740 *pp++ = cur->varstr;
6741 } else if (!cur->flg_export) {
6742 *pp++ = (char *) "-V";
6743 *pp++ = cur->varstr;
6744 }
6745 }
6746# if ENABLE_HUSH_FUNCTIONS
6747 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6748 *pp++ = (char *) "-F";
6749 *pp++ = funcp->name;
6750 *pp++ = funcp->body_as_string;
6751 }
6752# endif
6753 /* We can pass activated traps here. Say, -Tnn:trap_string
6754 *
6755 * However, POSIX says that subshells reset signals with traps
6756 * to SIG_DFL.
6757 * I tested bash-3.2 and it not only does that with true subshells
6758 * of the form ( list ), but with any forked children shells.
6759 * I set trap "echo W" WINCH; and then tried:
6760 *
6761 * { echo 1; sleep 20; echo 2; } &
6762 * while true; do echo 1; sleep 20; echo 2; break; done &
6763 * true | { echo 1; sleep 20; echo 2; } | cat
6764 *
6765 * In all these cases sending SIGWINCH to the child shell
6766 * did not run the trap. If I add trap "echo V" WINCH;
6767 * _inside_ group (just before echo 1), it works.
6768 *
6769 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006770 */
6771 *pp++ = (char *) "-c";
6772 *pp++ = (char *) s;
6773 if (builtin_argv) {
6774 while (*++builtin_argv)
6775 *pp++ = *builtin_argv;
6776 *pp++ = (char *) "";
6777 }
6778 *pp++ = g_argv0;
6779 while (*g_argv)
6780 *pp++ = *g_argv++;
6781 /* *pp = NULL; - is already there */
6782 pp = environ;
6783
6784 do_exec:
6785 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006786 /* Don't propagate SIG_IGN to the child */
6787 if (SPECIAL_JOBSTOP_SIGS != 0)
6788 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006789 execve(bb_busybox_exec_path, argv, pp);
6790 /* Fallback. Useful for init=/bin/hush usage etc */
6791 if (argv[0][0] == '/')
6792 execve(argv[0], argv, pp);
6793 xfunc_error_retval = 127;
6794 bb_error_msg_and_die("can't re-execute the shell");
6795}
6796#endif /* !BB_MMU */
6797
6798
6799static int run_and_free_list(struct pipe *pi);
6800
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006801/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006802 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6803 * end_trigger controls how often we stop parsing
6804 * NUL: parse all, execute, return
6805 * ';': parse till ';' or newline, execute, repeat till EOF
6806 */
6807static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006808{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006809 /* Why we need empty flag?
6810 * An obscure corner case "false; ``; echo $?":
6811 * empty command in `` should still set $? to 0.
6812 * But we can't just set $? to 0 at the start,
6813 * this breaks "false; echo `echo $?`" case.
6814 */
6815 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006816 while (1) {
6817 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006818
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006819#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02006820 if (end_trigger == ';') {
6821 G.promptmode = 0; /* PS1 */
6822 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
6823 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006824#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006825 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006826 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6827 /* If we are in "big" script
6828 * (not in `cmd` or something similar)...
6829 */
6830 if (pipe_list == ERR_PTR && end_trigger == ';') {
6831 /* Discard cached input (rest of line) */
6832 int ch = inp->last_char;
6833 while (ch != EOF && ch != '\n') {
6834 //bb_error_msg("Discarded:'%c'", ch);
6835 ch = i_getch(inp);
6836 }
6837 /* Force prompt */
6838 inp->p = NULL;
6839 /* This stream isn't empty */
6840 empty = 0;
6841 continue;
6842 }
6843 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006844 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006845 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006846 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006847 debug_print_tree(pipe_list, 0);
6848 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6849 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006850 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006851 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006852 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006853 }
Eric Andersen25f27032001-04-26 23:22:31 +00006854}
6855
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006856static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006857{
6858 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006859 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6860
Eric Andersen25f27032001-04-26 23:22:31 +00006861 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006862 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006863 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006864}
6865
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006866static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006867{
Eric Andersen25f27032001-04-26 23:22:31 +00006868 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006869 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01006870
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006871 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01006872 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006873 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006874 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006875}
6876
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006877#if ENABLE_HUSH_TICK
6878static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6879{
6880 pid_t pid;
6881 int channel[2];
6882# if !BB_MMU
6883 char **to_free = NULL;
6884# endif
6885
6886 xpipe(channel);
6887 pid = BB_MMU ? xfork() : xvfork();
6888 if (pid == 0) { /* child */
6889 disable_restore_tty_pgrp_on_exit();
6890 /* Process substitution is not considered to be usual
6891 * 'command execution'.
6892 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6893 */
6894 bb_signals(0
6895 + (1 << SIGTSTP)
6896 + (1 << SIGTTIN)
6897 + (1 << SIGTTOU)
6898 , SIG_IGN);
6899 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6900 close(channel[0]); /* NB: close _first_, then move fd! */
6901 xmove_fd(channel[1], 1);
6902 /* Prevent it from trying to handle ctrl-z etc */
6903 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006904# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006905 /* Awful hack for `trap` or $(trap).
6906 *
6907 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6908 * contains an example where "trap" is executed in a subshell:
6909 *
6910 * save_traps=$(trap)
6911 * ...
6912 * eval "$save_traps"
6913 *
6914 * Standard does not say that "trap" in subshell shall print
6915 * parent shell's traps. It only says that its output
6916 * must have suitable form, but then, in the above example
6917 * (which is not supposed to be normative), it implies that.
6918 *
6919 * bash (and probably other shell) does implement it
6920 * (traps are reset to defaults, but "trap" still shows them),
6921 * but as a result, "trap" logic is hopelessly messed up:
6922 *
6923 * # trap
6924 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6925 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6926 * # true | trap <--- trap is in subshell - no output (ditto)
6927 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6928 * trap -- 'echo Ho' SIGWINCH
6929 * # echo `(trap)` <--- in subshell in subshell - output
6930 * trap -- 'echo Ho' SIGWINCH
6931 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6932 * trap -- 'echo Ho' SIGWINCH
6933 *
6934 * The rules when to forget and when to not forget traps
6935 * get really complex and nonsensical.
6936 *
6937 * Our solution: ONLY bare $(trap) or `trap` is special.
6938 */
6939 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006940 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006941 && skip_whitespace(s + 4)[0] == '\0'
6942 ) {
6943 static const char *const argv[] = { NULL, NULL };
6944 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006945 fflush_all(); /* important */
6946 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006947 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006948# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006949# if BB_MMU
6950 reset_traps_to_defaults();
6951 parse_and_run_string(s);
6952 _exit(G.last_exitcode);
6953# else
6954 /* We re-execute after vfork on NOMMU. This makes this script safe:
6955 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6956 * huge=`cat BIG` # was blocking here forever
6957 * echo OK
6958 */
6959 re_execute_shell(&to_free,
6960 s,
6961 G.global_argv[0],
6962 G.global_argv + 1,
6963 NULL);
6964# endif
6965 }
6966
6967 /* parent */
6968 *pid_p = pid;
6969# if ENABLE_HUSH_FAST
6970 G.count_SIGCHLD++;
6971//bb_error_msg("[%d] fork in generate_stream_from_string:"
6972// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6973// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6974# endif
6975 enable_restore_tty_pgrp_on_exit();
6976# if !BB_MMU
6977 free(to_free);
6978# endif
6979 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006980 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006981}
6982
6983/* Return code is exit status of the process that is run. */
6984static int process_command_subs(o_string *dest, const char *s)
6985{
6986 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006987 pid_t pid;
6988 int status, ch, eol_cnt;
6989
6990 fp = generate_stream_from_string(s, &pid);
6991
6992 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006993 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006994 while ((ch = getc(fp)) != EOF) {
6995 if (ch == '\0')
6996 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006997 if (ch == '\n') {
6998 eol_cnt++;
6999 continue;
7000 }
7001 while (eol_cnt) {
7002 o_addchr(dest, '\n');
7003 eol_cnt--;
7004 }
7005 o_addQchr(dest, ch);
7006 }
7007
7008 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007009 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007010 /* We need to extract exitcode. Test case
7011 * "true; echo `sleep 1; false` $?"
7012 * should print 1 */
7013 safe_waitpid(pid, &status, 0);
7014 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7015 return WEXITSTATUS(status);
7016}
7017#endif /* ENABLE_HUSH_TICK */
7018
7019
7020static void setup_heredoc(struct redir_struct *redir)
7021{
7022 struct fd_pair pair;
7023 pid_t pid;
7024 int len, written;
7025 /* the _body_ of heredoc (misleading field name) */
7026 const char *heredoc = redir->rd_filename;
7027 char *expanded;
7028#if !BB_MMU
7029 char **to_free;
7030#endif
7031
7032 expanded = NULL;
7033 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007034 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007035 if (expanded)
7036 heredoc = expanded;
7037 }
7038 len = strlen(heredoc);
7039
7040 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7041 xpiped_pair(pair);
7042 xmove_fd(pair.rd, redir->rd_fd);
7043
7044 /* Try writing without forking. Newer kernels have
7045 * dynamically growing pipes. Must use non-blocking write! */
7046 ndelay_on(pair.wr);
7047 while (1) {
7048 written = write(pair.wr, heredoc, len);
7049 if (written <= 0)
7050 break;
7051 len -= written;
7052 if (len == 0) {
7053 close(pair.wr);
7054 free(expanded);
7055 return;
7056 }
7057 heredoc += written;
7058 }
7059 ndelay_off(pair.wr);
7060
7061 /* Okay, pipe buffer was not big enough */
7062 /* Note: we must not create a stray child (bastard? :)
7063 * for the unsuspecting parent process. Child creates a grandchild
7064 * and exits before parent execs the process which consumes heredoc
7065 * (that exec happens after we return from this function) */
7066#if !BB_MMU
7067 to_free = NULL;
7068#endif
7069 pid = xvfork();
7070 if (pid == 0) {
7071 /* child */
7072 disable_restore_tty_pgrp_on_exit();
7073 pid = BB_MMU ? xfork() : xvfork();
7074 if (pid != 0)
7075 _exit(0);
7076 /* grandchild */
7077 close(redir->rd_fd); /* read side of the pipe */
7078#if BB_MMU
7079 full_write(pair.wr, heredoc, len); /* may loop or block */
7080 _exit(0);
7081#else
7082 /* Delegate blocking writes to another process */
7083 xmove_fd(pair.wr, STDOUT_FILENO);
7084 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7085#endif
7086 }
7087 /* parent */
7088#if ENABLE_HUSH_FAST
7089 G.count_SIGCHLD++;
7090//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7091#endif
7092 enable_restore_tty_pgrp_on_exit();
7093#if !BB_MMU
7094 free(to_free);
7095#endif
7096 close(pair.wr);
7097 free(expanded);
7098 wait(NULL); /* wait till child has died */
7099}
7100
Denys Vlasenko2db74612017-07-07 22:07:28 +02007101struct squirrel {
7102 int orig_fd;
7103 int moved_to;
7104 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7105 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7106};
7107
Denys Vlasenko621fc502017-07-24 12:42:17 +02007108static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7109{
7110 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7111 sq[i].orig_fd = orig;
7112 sq[i].moved_to = moved;
7113 sq[i+1].orig_fd = -1; /* end marker */
7114 return sq;
7115}
7116
Denys Vlasenko2db74612017-07-07 22:07:28 +02007117static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7118{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007119 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007120 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007121
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007122 i = 0;
7123 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007124 /* If we collide with an already moved fd... */
7125 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007126 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007127 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7128 if (sq[i].moved_to < 0) /* what? */
7129 xfunc_die();
7130 return sq;
7131 }
7132 if (fd == sq[i].orig_fd) {
7133 /* Example: echo Hello >/dev/null 1>&2 */
7134 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7135 return sq;
7136 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007137 }
7138
Denys Vlasenko2db74612017-07-07 22:07:28 +02007139 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007140 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007141 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7142 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007143 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007144 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007145}
7146
Denys Vlasenko657e9002017-07-30 23:34:04 +02007147static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7148{
7149 int i;
7150
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007151 i = 0;
7152 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007153 /* If we collide with an already moved fd... */
7154 if (fd == sq[i].orig_fd) {
7155 /* Examples:
7156 * "echo 3>FILE 3>&- 3>FILE"
7157 * "echo 3>&- 3>FILE"
7158 * No need for last redirect to insert
7159 * another "need to close 3" indicator.
7160 */
7161 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7162 return sq;
7163 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007164 }
7165
7166 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7167 return append_squirrel(sq, i, fd, -1);
7168}
7169
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007170/* fd: redirect wants this fd to be used (e.g. 3>file).
7171 * Move all conflicting internally used fds,
7172 * and remember them so that we can restore them later.
7173 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007174static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007175{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007176 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7177 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007178
7179#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007180 if (fd == G.interactive_fd) {
7181 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007182 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007183 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7184 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007185 }
7186#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007187 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7188 * (1) Redirect in a forked child. No need to save FILEs' fds,
7189 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007190 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7191 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007192 * "fileno(fd) = new_fd" can't be done.
7193 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007194 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007195 return 0;
7196
Denys Vlasenko2db74612017-07-07 22:07:28 +02007197 /* If this one of script's fds? */
7198 if (save_FILEs_on_redirect(fd, avoid_fd))
7199 return 1; /* yes. "we closed fd" */
7200
7201 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7202 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7203 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007204}
7205
Denys Vlasenko2db74612017-07-07 22:07:28 +02007206static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007207{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007208 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007209 int i;
7210 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007211 if (sq[i].moved_to >= 0) {
7212 /* We simply die on error */
7213 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7214 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7215 } else {
7216 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7217 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7218 close(sq[i].orig_fd);
7219 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007220 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007221 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007222 }
7223
Denys Vlasenko2db74612017-07-07 22:07:28 +02007224 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007225
7226 restore_redirected_FILEs();
7227}
7228
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007229#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007230static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007231{
7232 if (G_interactive_fd)
7233 close(G_interactive_fd);
7234 close_all_FILE_list();
7235}
7236#endif
7237
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007238static int internally_opened_fd(int fd, struct squirrel *sq)
7239{
7240 int i;
7241
7242#if ENABLE_HUSH_INTERACTIVE
7243 if (fd == G.interactive_fd)
7244 return 1;
7245#endif
7246 /* If this one of script's fds? */
7247 if (fd_in_FILEs(fd))
7248 return 1;
7249
7250 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7251 if (fd == sq[i].moved_to)
7252 return 1;
7253 }
7254 return 0;
7255}
7256
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007257/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7258 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007259static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007260{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007261 struct redir_struct *redir;
7262
7263 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007264 int newfd;
7265 int closed;
7266
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007267 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007268 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007269 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007270 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7271 * of the heredoc */
7272 debug_printf_parse("set heredoc '%s'\n",
7273 redir->rd_filename);
7274 setup_heredoc(redir);
7275 continue;
7276 }
7277
7278 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007279 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007280 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007281 int mode;
7282
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007283 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007284 /*
7285 * Examples:
7286 * "cmd >" (no filename)
7287 * "cmd > <file" (2nd redirect starts too early)
7288 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007289 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007290 continue;
7291 }
7292 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007293 p = expand_string_to_string(redir->rd_filename,
7294 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007295 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007296 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007297 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007298 /* Error message from open_or_warn can be lost
7299 * if stderr has been redirected, but bash
7300 * and ash both lose it as well
7301 * (though zsh doesn't!)
7302 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007303 return 1;
7304 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007305 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007306 /* open() gave us precisely the fd we wanted.
7307 * This means that this fd was not busy
7308 * (not opened to anywhere).
7309 * Remember to close it on restore:
7310 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007311 *sqp = add_squirrel_closed(*sqp, newfd);
7312 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007313 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007314 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007315 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7316 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007317 }
7318
Denys Vlasenko657e9002017-07-30 23:34:04 +02007319 if (newfd == redir->rd_fd)
7320 continue;
7321
7322 /* if "N>FILE": move newfd to redir->rd_fd */
7323 /* if "N>&M": dup newfd to redir->rd_fd */
7324 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7325
7326 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7327 if (newfd == REDIRFD_CLOSE) {
7328 /* "N>&-" means "close me" */
7329 if (!closed) {
7330 /* ^^^ optimization: saving may already
7331 * have closed it. If not... */
7332 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007333 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007334 /* Sometimes we do another close on restore, getting EBADF.
7335 * Consider "echo 3>FILE 3>&-"
7336 * first redirect remembers "need to close 3",
7337 * and second redirect closes 3! Restore code then closes 3 again.
7338 */
7339 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007340 /* if newfd is a script fd or saved fd, simulate EBADF */
7341 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7342 //errno = EBADF;
7343 //bb_perror_msg_and_die("can't duplicate file descriptor");
7344 newfd = -1; /* same effect as code above */
7345 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007346 xdup2(newfd, redir->rd_fd);
7347 if (redir->rd_dup == REDIRFD_TO_FILE)
7348 /* "rd_fd > FILE" */
7349 close(newfd);
7350 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007351 }
7352 }
7353 return 0;
7354}
7355
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007356static char *find_in_path(const char *arg)
7357{
7358 char *ret = NULL;
7359 const char *PATH = get_local_var_value("PATH");
7360
7361 if (!PATH)
7362 return NULL;
7363
7364 while (1) {
7365 const char *end = strchrnul(PATH, ':');
7366 int sz = end - PATH; /* must be int! */
7367
7368 free(ret);
7369 if (sz != 0) {
7370 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7371 } else {
7372 /* We have xxx::yyyy in $PATH,
7373 * it means "use current dir" */
7374 ret = xstrdup(arg);
7375 }
7376 if (access(ret, F_OK) == 0)
7377 break;
7378
7379 if (*end == '\0') {
7380 free(ret);
7381 return NULL;
7382 }
7383 PATH = end + 1;
7384 }
7385
7386 return ret;
7387}
7388
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007389static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007390 const struct built_in_command *x,
7391 const struct built_in_command *end)
7392{
7393 while (x != end) {
7394 if (strcmp(name, x->b_cmd) != 0) {
7395 x++;
7396 continue;
7397 }
7398 debug_printf_exec("found builtin '%s'\n", name);
7399 return x;
7400 }
7401 return NULL;
7402}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007403static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007404{
7405 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7406}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007407static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007408{
7409 const struct built_in_command *x = find_builtin1(name);
7410 if (x)
7411 return x;
7412 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7413}
7414
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007415static void remove_nested_vars(void)
7416{
7417 struct variable *cur;
7418 struct variable **cur_pp;
7419
7420 cur_pp = &G.top_var;
7421 while ((cur = *cur_pp) != NULL) {
7422 if (cur->var_nest_level <= G.var_nest_level) {
7423 cur_pp = &cur->next;
7424 continue;
7425 }
7426 /* Unexport */
7427 if (cur->flg_export) {
7428 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7429 bb_unsetenv(cur->varstr);
7430 }
7431 /* Remove from global list */
7432 *cur_pp = cur->next;
7433 /* Free */
7434 if (!cur->max_len) {
7435 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7436 free(cur->varstr);
7437 }
7438 free(cur);
7439 }
7440}
7441
7442static void enter_var_nest_level(void)
7443{
7444 G.var_nest_level++;
7445 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7446
7447 /* Try: f() { echo -n .; f; }; f
7448 * struct variable::var_nest_level is uint16_t,
7449 * thus limiting recursion to < 2^16.
7450 * In any case, with 8 Mbyte stack SEGV happens
7451 * not too long after 2^16 recursions anyway.
7452 */
7453 if (G.var_nest_level > 0xff00)
7454 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7455}
7456
7457static void leave_var_nest_level(void)
7458{
7459 G.var_nest_level--;
7460 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7461 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7462 bb_error_msg_and_die("BUG: nesting underflow");
7463
7464 remove_nested_vars();
7465}
7466
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007467#if ENABLE_HUSH_FUNCTIONS
7468static struct function **find_function_slot(const char *name)
7469{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007470 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007471 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007472
7473 while ((funcp = *funcpp) != NULL) {
7474 if (strcmp(name, funcp->name) == 0) {
7475 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007476 break;
7477 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007478 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007479 }
7480 return funcpp;
7481}
7482
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007483static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007484{
7485 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007486 return funcp;
7487}
7488
7489/* Note: takes ownership on name ptr */
7490static struct function *new_function(char *name)
7491{
7492 struct function **funcpp = find_function_slot(name);
7493 struct function *funcp = *funcpp;
7494
7495 if (funcp != NULL) {
7496 struct command *cmd = funcp->parent_cmd;
7497 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7498 if (!cmd) {
7499 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7500 free(funcp->name);
7501 /* Note: if !funcp->body, do not free body_as_string!
7502 * This is a special case of "-F name body" function:
7503 * body_as_string was not malloced! */
7504 if (funcp->body) {
7505 free_pipe_list(funcp->body);
7506# if !BB_MMU
7507 free(funcp->body_as_string);
7508# endif
7509 }
7510 } else {
7511 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7512 cmd->argv[0] = funcp->name;
7513 cmd->group = funcp->body;
7514# if !BB_MMU
7515 cmd->group_as_string = funcp->body_as_string;
7516# endif
7517 }
7518 } else {
7519 debug_printf_exec("remembering new function '%s'\n", name);
7520 funcp = *funcpp = xzalloc(sizeof(*funcp));
7521 /*funcp->next = NULL;*/
7522 }
7523
7524 funcp->name = name;
7525 return funcp;
7526}
7527
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007528# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007529static void unset_func(const char *name)
7530{
7531 struct function **funcpp = find_function_slot(name);
7532 struct function *funcp = *funcpp;
7533
7534 if (funcp != NULL) {
7535 debug_printf_exec("freeing function '%s'\n", funcp->name);
7536 *funcpp = funcp->next;
7537 /* funcp is unlinked now, deleting it.
7538 * Note: if !funcp->body, the function was created by
7539 * "-F name body", do not free ->body_as_string
7540 * and ->name as they were not malloced. */
7541 if (funcp->body) {
7542 free_pipe_list(funcp->body);
7543 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007544# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007545 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007546# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007547 }
7548 free(funcp);
7549 }
7550}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007551# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007552
7553# if BB_MMU
7554#define exec_function(to_free, funcp, argv) \
7555 exec_function(funcp, argv)
7556# endif
7557static void exec_function(char ***to_free,
7558 const struct function *funcp,
7559 char **argv) NORETURN;
7560static void exec_function(char ***to_free,
7561 const struct function *funcp,
7562 char **argv)
7563{
7564# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007565 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007566
7567 argv[0] = G.global_argv[0];
7568 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007569 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007570
7571// Example when we are here: "cmd | func"
7572// func will run with saved-redirect fds open.
7573// $ f() { echo /proc/self/fd/*; }
7574// $ true | f
7575// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7576// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7577// Same in script:
7578// $ . ./SCRIPT
7579// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7580// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7581// They are CLOEXEC so external programs won't see them, but
7582// for "more correctness" we might want to close those extra fds here:
7583//? close_saved_fds_and_FILE_fds();
7584
Denys Vlasenko332e4112018-04-04 22:32:59 +02007585 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007586 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007587 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007588 IF_HUSH_LOCAL(G.func_nest_level++;)
7589
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007590 /* On MMU, funcp->body is always non-NULL */
7591 n = run_list(funcp->body);
7592 fflush_all();
7593 _exit(n);
7594# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007595//? close_saved_fds_and_FILE_fds();
7596
7597//TODO: check whether "true | func_with_return" works
7598
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007599 re_execute_shell(to_free,
7600 funcp->body_as_string,
7601 G.global_argv[0],
7602 argv + 1,
7603 NULL);
7604# endif
7605}
7606
7607static int run_function(const struct function *funcp, char **argv)
7608{
7609 int rc;
7610 save_arg_t sv;
7611 smallint sv_flg;
7612
7613 save_and_replace_G_args(&sv, argv);
7614
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007615 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007616 sv_flg = G_flag_return_in_progress;
7617 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007618
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007619 /* Make "local" variables properly shadow previous ones */
7620 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007621 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007622
7623 /* On MMU, funcp->body is always non-NULL */
7624# if !BB_MMU
7625 if (!funcp->body) {
7626 /* Function defined by -F */
7627 parse_and_run_string(funcp->body_as_string);
7628 rc = G.last_exitcode;
7629 } else
7630# endif
7631 {
7632 rc = run_list(funcp->body);
7633 }
7634
Denys Vlasenko332e4112018-04-04 22:32:59 +02007635 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007636 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007637
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007638 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007639
7640 restore_G_args(&sv, argv);
7641
7642 return rc;
7643}
7644#endif /* ENABLE_HUSH_FUNCTIONS */
7645
7646
7647#if BB_MMU
7648#define exec_builtin(to_free, x, argv) \
7649 exec_builtin(x, argv)
7650#else
7651#define exec_builtin(to_free, x, argv) \
7652 exec_builtin(to_free, argv)
7653#endif
7654static void exec_builtin(char ***to_free,
7655 const struct built_in_command *x,
7656 char **argv) NORETURN;
7657static void exec_builtin(char ***to_free,
7658 const struct built_in_command *x,
7659 char **argv)
7660{
7661#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007662 int rcode;
7663 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007664//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007665 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007666 fflush_all();
7667 _exit(rcode);
7668#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007669 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007670 /* On NOMMU, we must never block!
7671 * Example: { sleep 99 | read line; } & echo Ok
7672 */
7673 re_execute_shell(to_free,
7674 argv[0],
7675 G.global_argv[0],
7676 G.global_argv + 1,
7677 argv);
7678#endif
7679}
7680
7681
7682static void execvp_or_die(char **argv) NORETURN;
7683static void execvp_or_die(char **argv)
7684{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007685 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007686 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007687 /* Don't propagate SIG_IGN to the child */
7688 if (SPECIAL_JOBSTOP_SIGS != 0)
7689 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007690 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007691 e = 2;
7692 if (errno == EACCES) e = 126;
7693 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007694 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007695 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007696}
7697
7698#if ENABLE_HUSH_MODE_X
7699static void dump_cmd_in_x_mode(char **argv)
7700{
7701 if (G_x_mode && argv) {
7702 /* We want to output the line in one write op */
7703 char *buf, *p;
7704 int len;
7705 int n;
7706
7707 len = 3;
7708 n = 0;
7709 while (argv[n])
7710 len += strlen(argv[n++]) + 1;
7711 buf = xmalloc(len);
7712 buf[0] = '+';
7713 p = buf + 1;
7714 n = 0;
7715 while (argv[n])
7716 p += sprintf(p, " %s", argv[n++]);
7717 *p++ = '\n';
7718 *p = '\0';
7719 fputs(buf, stderr);
7720 free(buf);
7721 }
7722}
7723#else
7724# define dump_cmd_in_x_mode(argv) ((void)0)
7725#endif
7726
Denys Vlasenko57000292018-01-12 14:41:45 +01007727#if ENABLE_HUSH_COMMAND
7728static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7729{
7730 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007731
Denys Vlasenko57000292018-01-12 14:41:45 +01007732 if (!opt_vV)
7733 return;
7734
7735 to_free = NULL;
7736 if (!explanation) {
7737 char *path = getenv("PATH");
7738 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007739 if (!explanation)
7740 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007741 if (opt_vV != 'V')
7742 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7743 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007744 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007745 free(to_free);
7746 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007747 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007748}
7749#else
7750# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7751#endif
7752
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007753#if BB_MMU
7754#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7755 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7756#define pseudo_exec(nommu_save, command, argv_expanded) \
7757 pseudo_exec(command, argv_expanded)
7758#endif
7759
7760/* Called after [v]fork() in run_pipe, or from builtin_exec.
7761 * Never returns.
7762 * Don't exit() here. If you don't exec, use _exit instead.
7763 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007764 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007765 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007766static void pseudo_exec_argv(nommu_save_t *nommu_save,
7767 char **argv, int assignment_cnt,
7768 char **argv_expanded) NORETURN;
7769static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7770 char **argv, int assignment_cnt,
7771 char **argv_expanded)
7772{
Denys Vlasenko57000292018-01-12 14:41:45 +01007773 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007774 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007775 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007776 IF_HUSH_COMMAND(char opt_vV = 0;)
7777 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007778
7779 new_env = expand_assignments(argv, assignment_cnt);
7780 dump_cmd_in_x_mode(new_env);
7781
7782 if (!argv[assignment_cnt]) {
7783 /* Case when we are here: ... | var=val | ...
7784 * (note that we do not exit early, i.e., do not optimize out
7785 * expand_assignments(): think about ... | var=`sleep 1` | ...
7786 */
7787 free_strings(new_env);
7788 _exit(EXIT_SUCCESS);
7789 }
7790
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007791 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007792#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007793 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007794#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007795 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007796 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007797#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007798 set_vars_and_save_old(new_env);
7799 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007800
7801 if (argv_expanded) {
7802 argv = argv_expanded;
7803 } else {
7804 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7805#if !BB_MMU
7806 nommu_save->argv = argv;
7807#endif
7808 }
7809 dump_cmd_in_x_mode(argv);
7810
7811#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7812 if (strchr(argv[0], '/') != NULL)
7813 goto skip;
7814#endif
7815
Denys Vlasenko75481d32017-07-31 05:27:09 +02007816#if ENABLE_HUSH_FUNCTIONS
7817 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007818 funcp = find_function(argv[0]);
7819 if (funcp)
7820 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02007821#endif
7822
Denys Vlasenko57000292018-01-12 14:41:45 +01007823#if ENABLE_HUSH_COMMAND
7824 /* "command BAR": run BAR without looking it up among functions
7825 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7826 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7827 */
7828 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7829 char *p;
7830
7831 argv++;
7832 p = *argv;
7833 if (p[0] != '-' || !p[1])
7834 continue; /* bash allows "command command command [-OPT] BAR" */
7835
7836 for (;;) {
7837 p++;
7838 switch (*p) {
7839 case '\0':
7840 argv++;
7841 p = *argv;
7842 if (p[0] != '-' || !p[1])
7843 goto after_opts;
7844 continue; /* next arg is also -opts, process it too */
7845 case 'v':
7846 case 'V':
7847 opt_vV = *p;
7848 continue;
7849 default:
7850 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7851 }
7852 }
7853 }
7854 after_opts:
7855# if ENABLE_HUSH_FUNCTIONS
7856 if (opt_vV && find_function(argv[0]))
7857 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7858# endif
7859#endif
7860
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007861 /* Check if the command matches any of the builtins.
7862 * Depending on context, this might be redundant. But it's
7863 * easier to waste a few CPU cycles than it is to figure out
7864 * if this is one of those cases.
7865 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007866 /* Why "BB_MMU ? :" difference in logic? -
7867 * On NOMMU, it is more expensive to re-execute shell
7868 * just in order to run echo or test builtin.
7869 * It's better to skip it here and run corresponding
7870 * non-builtin later. */
7871 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7872 if (x) {
7873 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7874 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007875 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007876
7877#if ENABLE_FEATURE_SH_STANDALONE
7878 /* Check if the command matches any busybox applets */
7879 {
7880 int a = find_applet_by_name(argv[0]);
7881 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007882 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007883# if BB_MMU /* see above why on NOMMU it is not allowed */
7884 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007885 /* Do not leak open fds from opened script files etc.
7886 * Testcase: interactive "ls -l /proc/self/fd"
7887 * should not show tty fd open.
7888 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007889 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007890//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007891//This casuses test failures in
7892//redir_children_should_not_see_saved_fd_2.tests
7893//redir_children_should_not_see_saved_fd_3.tests
7894//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007895 /* Without this, "rm -i FILE" can't be ^C'ed: */
7896 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007897 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007898 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007899 }
7900# endif
7901 /* Re-exec ourselves */
7902 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007903 /* Don't propagate SIG_IGN to the child */
7904 if (SPECIAL_JOBSTOP_SIGS != 0)
7905 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007906 execv(bb_busybox_exec_path, argv);
7907 /* If they called chroot or otherwise made the binary no longer
7908 * executable, fall through */
7909 }
7910 }
7911#endif
7912
7913#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7914 skip:
7915#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007916 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007917 execvp_or_die(argv);
7918}
7919
7920/* Called after [v]fork() in run_pipe
7921 */
7922static void pseudo_exec(nommu_save_t *nommu_save,
7923 struct command *command,
7924 char **argv_expanded) NORETURN;
7925static void pseudo_exec(nommu_save_t *nommu_save,
7926 struct command *command,
7927 char **argv_expanded)
7928{
Denys Vlasenko49015a62018-04-03 13:02:43 +02007929#if ENABLE_HUSH_FUNCTIONS
7930 if (command->cmd_type == CMD_FUNCDEF) {
7931 /* Ignore funcdefs in pipes:
7932 * true | f() { cmd }
7933 */
7934 _exit(0);
7935 }
7936#endif
7937
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007938 if (command->argv) {
7939 pseudo_exec_argv(nommu_save, command->argv,
7940 command->assignment_cnt, argv_expanded);
7941 }
7942
7943 if (command->group) {
7944 /* Cases when we are here:
7945 * ( list )
7946 * { list } &
7947 * ... | ( list ) | ...
7948 * ... | { list } | ...
7949 */
7950#if BB_MMU
7951 int rcode;
7952 debug_printf_exec("pseudo_exec: run_list\n");
7953 reset_traps_to_defaults();
7954 rcode = run_list(command->group);
7955 /* OK to leak memory by not calling free_pipe_list,
7956 * since this process is about to exit */
7957 _exit(rcode);
7958#else
7959 re_execute_shell(&nommu_save->argv_from_re_execing,
7960 command->group_as_string,
7961 G.global_argv[0],
7962 G.global_argv + 1,
7963 NULL);
7964#endif
7965 }
7966
7967 /* Case when we are here: ... | >file */
7968 debug_printf_exec("pseudo_exec'ed null command\n");
7969 _exit(EXIT_SUCCESS);
7970}
7971
7972#if ENABLE_HUSH_JOB
7973static const char *get_cmdtext(struct pipe *pi)
7974{
7975 char **argv;
7976 char *p;
7977 int len;
7978
7979 /* This is subtle. ->cmdtext is created only on first backgrounding.
7980 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7981 * On subsequent bg argv is trashed, but we won't use it */
7982 if (pi->cmdtext)
7983 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007984
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007985 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007986 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007987 pi->cmdtext = xzalloc(1);
7988 return pi->cmdtext;
7989 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007990 len = 0;
7991 do {
7992 len += strlen(*argv) + 1;
7993 } while (*++argv);
7994 p = xmalloc(len);
7995 pi->cmdtext = p;
7996 argv = pi->cmds[0].argv;
7997 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007998 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007999 *p++ = ' ';
8000 } while (*++argv);
8001 p[-1] = '\0';
8002 return pi->cmdtext;
8003}
8004
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008005static void remove_job_from_table(struct pipe *pi)
8006{
8007 struct pipe *prev_pipe;
8008
8009 if (pi == G.job_list) {
8010 G.job_list = pi->next;
8011 } else {
8012 prev_pipe = G.job_list;
8013 while (prev_pipe->next != pi)
8014 prev_pipe = prev_pipe->next;
8015 prev_pipe->next = pi->next;
8016 }
8017 G.last_jobid = 0;
8018 if (G.job_list)
8019 G.last_jobid = G.job_list->jobid;
8020}
8021
8022static void delete_finished_job(struct pipe *pi)
8023{
8024 remove_job_from_table(pi);
8025 free_pipe(pi);
8026}
8027
8028static void clean_up_last_dead_job(void)
8029{
8030 if (G.job_list && !G.job_list->alive_cmds)
8031 delete_finished_job(G.job_list);
8032}
8033
Denys Vlasenko16096292017-07-10 10:00:28 +02008034static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008035{
8036 struct pipe *job, **jobp;
8037 int i;
8038
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008039 clean_up_last_dead_job();
8040
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008041 /* Find the end of the list, and find next job ID to use */
8042 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008043 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008044 while ((job = *jobp) != NULL) {
8045 if (job->jobid > i)
8046 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008047 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008048 }
8049 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008050
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008051 /* Create a new job struct at the end */
8052 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008053 job->next = NULL;
8054 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8055 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8056 for (i = 0; i < pi->num_cmds; i++) {
8057 job->cmds[i].pid = pi->cmds[i].pid;
8058 /* all other fields are not used and stay zero */
8059 }
8060 job->cmdtext = xstrdup(get_cmdtext(pi));
8061
8062 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008063 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008064 G.last_jobid = job->jobid;
8065}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008066#endif /* JOB */
8067
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008068static int job_exited_or_stopped(struct pipe *pi)
8069{
8070 int rcode, i;
8071
8072 if (pi->alive_cmds != pi->stopped_cmds)
8073 return -1;
8074
8075 /* All processes in fg pipe have exited or stopped */
8076 rcode = 0;
8077 i = pi->num_cmds;
8078 while (--i >= 0) {
8079 rcode = pi->cmds[i].cmd_exitcode;
8080 /* usually last process gives overall exitstatus,
8081 * but with "set -o pipefail", last *failed* process does */
8082 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8083 break;
8084 }
8085 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8086 return rcode;
8087}
8088
Denys Vlasenko7e675362016-10-28 21:57:31 +02008089static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008090{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008091#if ENABLE_HUSH_JOB
8092 struct pipe *pi;
8093#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008094 int i, dead;
8095
8096 dead = WIFEXITED(status) || WIFSIGNALED(status);
8097
8098#if DEBUG_JOBS
8099 if (WIFSTOPPED(status))
8100 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8101 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8102 if (WIFSIGNALED(status))
8103 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8104 childpid, WTERMSIG(status), WEXITSTATUS(status));
8105 if (WIFEXITED(status))
8106 debug_printf_jobs("pid %d exited, exitcode %d\n",
8107 childpid, WEXITSTATUS(status));
8108#endif
8109 /* Were we asked to wait for a fg pipe? */
8110 if (fg_pipe) {
8111 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008112
Denys Vlasenko7e675362016-10-28 21:57:31 +02008113 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008114 int rcode;
8115
Denys Vlasenko7e675362016-10-28 21:57:31 +02008116 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8117 if (fg_pipe->cmds[i].pid != childpid)
8118 continue;
8119 if (dead) {
8120 int ex;
8121 fg_pipe->cmds[i].pid = 0;
8122 fg_pipe->alive_cmds--;
8123 ex = WEXITSTATUS(status);
8124 /* bash prints killer signal's name for *last*
8125 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8126 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8127 */
8128 if (WIFSIGNALED(status)) {
8129 int sig = WTERMSIG(status);
8130 if (i == fg_pipe->num_cmds-1)
8131 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8132 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8133 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8134 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8135 * Maybe we need to use sig | 128? */
8136 ex = sig + 128;
8137 }
8138 fg_pipe->cmds[i].cmd_exitcode = ex;
8139 } else {
8140 fg_pipe->stopped_cmds++;
8141 }
8142 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8143 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008144 rcode = job_exited_or_stopped(fg_pipe);
8145 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008146/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8147 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8148 * and "killall -STOP cat" */
8149 if (G_interactive_fd) {
8150#if ENABLE_HUSH_JOB
8151 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008152 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008153#endif
8154 return rcode;
8155 }
8156 if (fg_pipe->alive_cmds == 0)
8157 return rcode;
8158 }
8159 /* There are still running processes in the fg_pipe */
8160 return -1;
8161 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008162 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008163 }
8164
8165#if ENABLE_HUSH_JOB
8166 /* We were asked to wait for bg or orphaned children */
8167 /* No need to remember exitcode in this case */
8168 for (pi = G.job_list; pi; pi = pi->next) {
8169 for (i = 0; i < pi->num_cmds; i++) {
8170 if (pi->cmds[i].pid == childpid)
8171 goto found_pi_and_prognum;
8172 }
8173 }
8174 /* Happens when shell is used as init process (init=/bin/sh) */
8175 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8176 return -1; /* this wasn't a process from fg_pipe */
8177
8178 found_pi_and_prognum:
8179 if (dead) {
8180 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008181 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008182 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008183 rcode = 128 + WTERMSIG(status);
8184 pi->cmds[i].cmd_exitcode = rcode;
8185 if (G.last_bg_pid == pi->cmds[i].pid)
8186 G.last_bg_pid_exitcode = rcode;
8187 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008188 pi->alive_cmds--;
8189 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008190 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008191 printf(JOB_STATUS_FORMAT, pi->jobid,
8192 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008193 delete_finished_job(pi);
8194 } else {
8195/*
8196 * bash deletes finished jobs from job table only in interactive mode,
8197 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8198 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8199 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8200 * We only retain one "dead" job, if it's the single job on the list.
8201 * This covers most of real-world scenarios where this is useful.
8202 */
8203 if (pi != G.job_list)
8204 delete_finished_job(pi);
8205 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008206 }
8207 } else {
8208 /* child stopped */
8209 pi->stopped_cmds++;
8210 }
8211#endif
8212 return -1; /* this wasn't a process from fg_pipe */
8213}
8214
8215/* Check to see if any processes have exited -- if they have,
8216 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008217 *
8218 * If non-NULL fg_pipe: wait for its completion or stop.
8219 * Return its exitcode or zero if stopped.
8220 *
8221 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8222 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8223 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8224 * or 0 if no children changed status.
8225 *
8226 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8227 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8228 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008229 */
8230static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8231{
8232 int attributes;
8233 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008234 int rcode = 0;
8235
8236 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8237
8238 attributes = WUNTRACED;
8239 if (fg_pipe == NULL)
8240 attributes |= WNOHANG;
8241
8242 errno = 0;
8243#if ENABLE_HUSH_FAST
8244 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8245//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8246//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8247 /* There was neither fork nor SIGCHLD since last waitpid */
8248 /* Avoid doing waitpid syscall if possible */
8249 if (!G.we_have_children) {
8250 errno = ECHILD;
8251 return -1;
8252 }
8253 if (fg_pipe == NULL) { /* is WNOHANG set? */
8254 /* We have children, but they did not exit
8255 * or stop yet (we saw no SIGCHLD) */
8256 return 0;
8257 }
8258 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8259 }
8260#endif
8261
8262/* Do we do this right?
8263 * bash-3.00# sleep 20 | false
8264 * <ctrl-Z pressed>
8265 * [3]+ Stopped sleep 20 | false
8266 * bash-3.00# echo $?
8267 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8268 * [hush 1.14.0: yes we do it right]
8269 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008270 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008271 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008272#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008273 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008274 i = G.count_SIGCHLD;
8275#endif
8276 childpid = waitpid(-1, &status, attributes);
8277 if (childpid <= 0) {
8278 if (childpid && errno != ECHILD)
8279 bb_perror_msg("waitpid");
8280#if ENABLE_HUSH_FAST
8281 else { /* Until next SIGCHLD, waitpid's are useless */
8282 G.we_have_children = (childpid == 0);
8283 G.handled_SIGCHLD = i;
8284//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8285 }
8286#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008287 /* ECHILD (no children), or 0 (no change in children status) */
8288 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008289 break;
8290 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008291 rcode = process_wait_result(fg_pipe, childpid, status);
8292 if (rcode >= 0) {
8293 /* fg_pipe exited or stopped */
8294 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008295 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008296 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008297 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008298 rcode = WEXITSTATUS(status);
8299 if (WIFSIGNALED(status))
8300 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008301 if (WIFSTOPPED(status))
8302 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8303 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008304 rcode++;
8305 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008306 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008307 /* This wasn't one of our processes, or */
8308 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008309 } /* while (waitpid succeeds)... */
8310
8311 return rcode;
8312}
8313
8314#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008315static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008316{
8317 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008318 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008319 if (G_saved_tty_pgrp) {
8320 /* Job finished, move the shell to the foreground */
8321 p = getpgrp(); /* our process group id */
8322 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8323 tcsetpgrp(G_interactive_fd, p);
8324 }
8325 return rcode;
8326}
8327#endif
8328
8329/* Start all the jobs, but don't wait for anything to finish.
8330 * See checkjobs().
8331 *
8332 * Return code is normally -1, when the caller has to wait for children
8333 * to finish to determine the exit status of the pipe. If the pipe
8334 * is a simple builtin command, however, the action is done by the
8335 * time run_pipe returns, and the exit code is provided as the
8336 * return value.
8337 *
8338 * Returns -1 only if started some children. IOW: we have to
8339 * mask out retvals of builtins etc with 0xff!
8340 *
8341 * The only case when we do not need to [v]fork is when the pipe
8342 * is single, non-backgrounded, non-subshell command. Examples:
8343 * cmd ; ... { list } ; ...
8344 * cmd && ... { list } && ...
8345 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008346 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008347 * or (if SH_STANDALONE) an applet, and we can run the { list }
8348 * with run_list. If it isn't one of these, we fork and exec cmd.
8349 *
8350 * Cases when we must fork:
8351 * non-single: cmd | cmd
8352 * backgrounded: cmd & { list } &
8353 * subshell: ( list ) [&]
8354 */
8355#if !ENABLE_HUSH_MODE_X
Denys Vlasenkoc96bb2c2018-06-26 15:43:56 +02008356#define redirect_and_varexp_helper(command, squirrel, argv_expanded) \
8357 redirect_and_varexp_helper(command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008358#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008359static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008360 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008361 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008362 char **argv_expanded)
8363{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008364 /* Assignments occur before redirects. Try:
8365 * a=`sleep 1` sleep 2 3>/qwe/rty
8366 */
8367
8368 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8369 dump_cmd_in_x_mode(new_env);
8370 dump_cmd_in_x_mode(argv_expanded);
8371 /* this takes ownership of new_env[i] elements, and frees new_env: */
8372 set_vars_and_save_old(new_env);
8373
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008374 /* setup_redirects acts on file descriptors, not FILEs.
8375 * This is perfect for work that comes after exec().
8376 * Is it really safe for inline use? Experimentally,
8377 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008378 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008379}
8380static NOINLINE int run_pipe(struct pipe *pi)
8381{
8382 static const char *const null_ptr = NULL;
8383
8384 int cmd_no;
8385 int next_infd;
8386 struct command *command;
8387 char **argv_expanded;
8388 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008389 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008390 int rcode;
8391
8392 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8393 debug_enter();
8394
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008395 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8396 * Result should be 3 lines: q w e, qwe, q w e
8397 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008398 if (G.ifs_whitespace != G.ifs)
8399 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008400 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008401 if (G.ifs) {
8402 char *p;
8403 G.ifs_whitespace = (char*)G.ifs;
8404 p = skip_whitespace(G.ifs);
8405 if (*p) {
8406 /* Not all $IFS is whitespace */
8407 char *d;
8408 int len = p - G.ifs;
8409 p = skip_non_whitespace(p);
8410 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8411 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8412 while (*p) {
8413 if (isspace(*p))
8414 *d++ = *p;
8415 p++;
8416 }
8417 *d = '\0';
8418 }
8419 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008420 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008421 G.ifs_whitespace = (char*)G.ifs;
8422 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008423
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008424 IF_HUSH_JOB(pi->pgrp = -1;)
8425 pi->stopped_cmds = 0;
8426 command = &pi->cmds[0];
8427 argv_expanded = NULL;
8428
8429 if (pi->num_cmds != 1
8430 || pi->followup == PIPE_BG
8431 || command->cmd_type == CMD_SUBSHELL
8432 ) {
8433 goto must_fork;
8434 }
8435
8436 pi->alive_cmds = 1;
8437
8438 debug_printf_exec(": group:%p argv:'%s'\n",
8439 command->group, command->argv ? command->argv[0] : "NONE");
8440
8441 if (command->group) {
8442#if ENABLE_HUSH_FUNCTIONS
8443 if (command->cmd_type == CMD_FUNCDEF) {
8444 /* "executing" func () { list } */
8445 struct function *funcp;
8446
8447 funcp = new_function(command->argv[0]);
8448 /* funcp->name is already set to argv[0] */
8449 funcp->body = command->group;
8450# if !BB_MMU
8451 funcp->body_as_string = command->group_as_string;
8452 command->group_as_string = NULL;
8453# endif
8454 command->group = NULL;
8455 command->argv[0] = NULL;
8456 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8457 funcp->parent_cmd = command;
8458 command->child_func = funcp;
8459
8460 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8461 debug_leave();
8462 return EXIT_SUCCESS;
8463 }
8464#endif
8465 /* { list } */
8466 debug_printf("non-subshell group\n");
8467 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008468 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008469 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008470//FIXME: we need to pass squirrel down into run_list()
8471//for SH_STANDALONE case, or else this construct:
8472// { find /proc/self/fd; true; } >FILE; cmd2
8473//has no way of closing saved fd#1 for "find",
8474//and in SH_STANDALONE mode, "find" is not execed,
8475//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008476 rcode = run_list(command->group) & 0xff;
8477 }
8478 restore_redirects(squirrel);
8479 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8480 debug_leave();
8481 debug_printf_exec("run_pipe: return %d\n", rcode);
8482 return rcode;
8483 }
8484
8485 argv = command->argv ? command->argv : (char **) &null_ptr;
8486 {
8487 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008488 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8489 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008490 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008491 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008492
Denys Vlasenko5807e182018-02-08 19:19:04 +01008493#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008494 if (G.lineno_var)
8495 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8496#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008497
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008498 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008499 /* Assignments, but no command.
8500 * Ensure redirects take effect (that is, create files).
8501 * Try "a=t >file"
8502 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008503 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008504 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008505 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008506 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008507 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008508
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008509 /* Set shell variables */
8510 if (G_x_mode)
8511 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008512 i = 0;
8513 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008514 char *p = expand_string_to_string(argv[i],
8515 EXP_FLAG_ESC_GLOB_CHARS,
8516 /*unbackslash:*/ 1
8517 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008518 if (G_x_mode)
8519 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008520 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008521 if (set_local_var(p, /*flag:*/ 0)) {
8522 /* assignment to readonly var / putenv error? */
8523 rcode = 1;
8524 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008525 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008526 }
8527 if (G_x_mode)
8528 bb_putchar_stderr('\n');
8529 /* Redirect error sets $? to 1. Otherwise,
8530 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008531 * Else, clear $?:
8532 * false; q=`exit 2`; echo $? - should print 2
8533 * false; x=1; echo $? - should print 0
8534 * Because of the 2nd case, we can't just use G.last_exitcode.
8535 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008536 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008537 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008538 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8539 debug_leave();
8540 debug_printf_exec("run_pipe: return %d\n", rcode);
8541 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008542 }
8543
8544 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008545#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008546 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008547 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008548 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008549#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008550 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008551
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008552 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008553 if (!argv_expanded[0]) {
8554 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008555 /* `false` still has to set exitcode 1 */
8556 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008557 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008558 }
8559
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008560 old_vars = NULL;
8561 sv_shadowed = G.shadowed_vars_pp;
8562
Denys Vlasenko75481d32017-07-31 05:27:09 +02008563 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008564 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8565 IF_HUSH_FUNCTIONS(x = NULL;)
8566 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008567 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008568 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008569 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8570 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008571 /*
8572 * Variable assignments are executed, but then "forgotten":
8573 * a=`sleep 1;echo A` exec 3>&-; echo $a
8574 * sleeps, but prints nothing.
8575 */
8576 enter_var_nest_level();
8577 G.shadowed_vars_pp = &old_vars;
8578 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8579 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008580 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008581
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008582 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008583 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008584
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008585 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008586 * a=b true; env | grep ^a=
8587 */
8588 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008589 /* Collect all variables "shadowed" by helper
8590 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8591 * into old_vars list:
8592 */
8593 G.shadowed_vars_pp = &old_vars;
8594 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008595 if (rcode == 0) {
8596 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008597 /* Do not collect *to old_vars list* vars shadowed
8598 * by e.g. "local VAR" builtin (collect them
8599 * in the previously nested list instead):
8600 * don't want them to be restored immediately
8601 * after "local" completes.
8602 */
8603 G.shadowed_vars_pp = sv_shadowed;
8604
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008605 debug_printf_exec(": builtin '%s' '%s'...\n",
8606 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008607 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008608 rcode = x->b_function(argv_expanded) & 0xff;
8609 fflush_all();
8610 }
8611#if ENABLE_HUSH_FUNCTIONS
8612 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008613 debug_printf_exec(": function '%s' '%s'...\n",
8614 funcp->name, argv_expanded[1]);
8615 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008616 /*
8617 * But do collect *to old_vars list* vars shadowed
8618 * within function execution. To that end, restore
8619 * this pointer _after_ function run:
8620 */
8621 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008622 }
8623#endif
8624 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008625 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008626 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008627 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008628 if (n < 0 || !APPLET_IS_NOFORK(n))
8629 goto must_fork;
8630
8631 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008632 /* Collect all variables "shadowed" by helper into old_vars list */
8633 G.shadowed_vars_pp = &old_vars;
8634 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8635 G.shadowed_vars_pp = sv_shadowed;
8636
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008637 if (rcode == 0) {
8638 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8639 argv_expanded[0], argv_expanded[1]);
8640 /*
8641 * Note: signals (^C) can't interrupt here.
8642 * We remember them and they will be acted upon
8643 * after applet returns.
8644 * This makes applets which can run for a long time
8645 * and/or wait for user input ineligible for NOFORK:
8646 * for example, "yes" or "rm" (rm -i waits for input).
8647 */
8648 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008649 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008650 } else
8651 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008652
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008653 restore_redirects(squirrel);
8654 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008655 leave_var_nest_level();
8656 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008657
8658 /*
8659 * Try "usleep 99999999" + ^C + "echo $?"
8660 * with FEATURE_SH_NOFORK=y.
8661 */
8662 if (!funcp) {
8663 /* It was builtin or nofork.
8664 * if this would be a real fork/execed program,
8665 * it should have died if a fatal sig was received.
8666 * But OTOH, there was no separate process,
8667 * the sig was sent to _shell_, not to non-existing
8668 * child.
8669 * Let's just handle ^C only, this one is obvious:
8670 * we aren't ok with exitcode 0 when ^C was pressed
8671 * during builtin/nofork.
8672 */
8673 if (sigismember(&G.pending_set, SIGINT))
8674 rcode = 128 + SIGINT;
8675 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008676 free(argv_expanded);
8677 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8678 debug_leave();
8679 debug_printf_exec("run_pipe return %d\n", rcode);
8680 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008681 }
8682
8683 must_fork:
8684 /* NB: argv_expanded may already be created, and that
8685 * might include `cmd` runs! Do not rerun it! We *must*
8686 * use argv_expanded if it's non-NULL */
8687
8688 /* Going to fork a child per each pipe member */
8689 pi->alive_cmds = 0;
8690 next_infd = 0;
8691
8692 cmd_no = 0;
8693 while (cmd_no < pi->num_cmds) {
8694 struct fd_pair pipefds;
8695#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008696 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008697 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008698 nommu_save.old_vars = NULL;
8699 nommu_save.argv = NULL;
8700 nommu_save.argv_from_re_execing = NULL;
8701#endif
8702 command = &pi->cmds[cmd_no];
8703 cmd_no++;
8704 if (command->argv) {
8705 debug_printf_exec(": pipe member '%s' '%s'...\n",
8706 command->argv[0], command->argv[1]);
8707 } else {
8708 debug_printf_exec(": pipe member with no argv\n");
8709 }
8710
8711 /* pipes are inserted between pairs of commands */
8712 pipefds.rd = 0;
8713 pipefds.wr = 1;
8714 if (cmd_no < pi->num_cmds)
8715 xpiped_pair(pipefds);
8716
Denys Vlasenko5807e182018-02-08 19:19:04 +01008717#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008718 if (G.lineno_var)
8719 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8720#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008721
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008722 command->pid = BB_MMU ? fork() : vfork();
8723 if (!command->pid) { /* child */
8724#if ENABLE_HUSH_JOB
8725 disable_restore_tty_pgrp_on_exit();
8726 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8727
8728 /* Every child adds itself to new process group
8729 * with pgid == pid_of_first_child_in_pipe */
8730 if (G.run_list_level == 1 && G_interactive_fd) {
8731 pid_t pgrp;
8732 pgrp = pi->pgrp;
8733 if (pgrp < 0) /* true for 1st process only */
8734 pgrp = getpid();
8735 if (setpgid(0, pgrp) == 0
8736 && pi->followup != PIPE_BG
8737 && G_saved_tty_pgrp /* we have ctty */
8738 ) {
8739 /* We do it in *every* child, not just first,
8740 * to avoid races */
8741 tcsetpgrp(G_interactive_fd, pgrp);
8742 }
8743 }
8744#endif
8745 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8746 /* 1st cmd in backgrounded pipe
8747 * should have its stdin /dev/null'ed */
8748 close(0);
8749 if (open(bb_dev_null, O_RDONLY))
8750 xopen("/", O_RDONLY);
8751 } else {
8752 xmove_fd(next_infd, 0);
8753 }
8754 xmove_fd(pipefds.wr, 1);
8755 if (pipefds.rd > 1)
8756 close(pipefds.rd);
8757 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008758 * and the pipe fd (fd#1) is available for dup'ing:
8759 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8760 * of cmd1 goes into pipe.
8761 */
8762 if (setup_redirects(command, NULL)) {
8763 /* Happens when redir file can't be opened:
8764 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8765 * FOO
8766 * hush: can't open '/qwe/rty': No such file or directory
8767 * BAZ
8768 * (echo BAR is not executed, it hits _exit(1) below)
8769 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008770 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008771 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008772
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008773 /* Stores to nommu_save list of env vars putenv'ed
8774 * (NOMMU, on MMU we don't need that) */
8775 /* cast away volatility... */
8776 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8777 /* pseudo_exec() does not return */
8778 }
8779
8780 /* parent or error */
8781#if ENABLE_HUSH_FAST
8782 G.count_SIGCHLD++;
8783//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8784#endif
8785 enable_restore_tty_pgrp_on_exit();
8786#if !BB_MMU
8787 /* Clean up after vforked child */
8788 free(nommu_save.argv);
8789 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008790 G.var_nest_level = sv_var_nest_level;
8791 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008792 add_vars(nommu_save.old_vars);
8793#endif
8794 free(argv_expanded);
8795 argv_expanded = NULL;
8796 if (command->pid < 0) { /* [v]fork failed */
8797 /* Clearly indicate, was it fork or vfork */
8798 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8799 } else {
8800 pi->alive_cmds++;
8801#if ENABLE_HUSH_JOB
8802 /* Second and next children need to know pid of first one */
8803 if (pi->pgrp < 0)
8804 pi->pgrp = command->pid;
8805#endif
8806 }
8807
8808 if (cmd_no > 1)
8809 close(next_infd);
8810 if (cmd_no < pi->num_cmds)
8811 close(pipefds.wr);
8812 /* Pass read (output) pipe end to next iteration */
8813 next_infd = pipefds.rd;
8814 }
8815
8816 if (!pi->alive_cmds) {
8817 debug_leave();
8818 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8819 return 1;
8820 }
8821
8822 debug_leave();
8823 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8824 return -1;
8825}
8826
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008827/* NB: called by pseudo_exec, and therefore must not modify any
8828 * global data until exec/_exit (we can be a child after vfork!) */
8829static int run_list(struct pipe *pi)
8830{
8831#if ENABLE_HUSH_CASE
8832 char *case_word = NULL;
8833#endif
8834#if ENABLE_HUSH_LOOPS
8835 struct pipe *loop_top = NULL;
8836 char **for_lcur = NULL;
8837 char **for_list = NULL;
8838#endif
8839 smallint last_followup;
8840 smalluint rcode;
8841#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8842 smalluint cond_code = 0;
8843#else
8844 enum { cond_code = 0 };
8845#endif
8846#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008847 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008848 smallint last_rword; /* ditto */
8849#endif
8850
8851 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8852 debug_enter();
8853
8854#if ENABLE_HUSH_LOOPS
8855 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008856 {
8857 struct pipe *cpipe;
8858 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8859 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8860 continue;
8861 /* current word is FOR or IN (BOLD in comments below) */
8862 if (cpipe->next == NULL) {
8863 syntax_error("malformed for");
8864 debug_leave();
8865 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8866 return 1;
8867 }
8868 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8869 if (cpipe->next->res_word == RES_DO)
8870 continue;
8871 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8872 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8873 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8874 ) {
8875 syntax_error("malformed for");
8876 debug_leave();
8877 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8878 return 1;
8879 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008880 }
8881 }
8882#endif
8883
8884 /* Past this point, all code paths should jump to ret: label
8885 * in order to return, no direct "return" statements please.
8886 * This helps to ensure that no memory is leaked. */
8887
8888#if ENABLE_HUSH_JOB
8889 G.run_list_level++;
8890#endif
8891
8892#if HAS_KEYWORDS
8893 rword = RES_NONE;
8894 last_rword = RES_XXXX;
8895#endif
8896 last_followup = PIPE_SEQ;
8897 rcode = G.last_exitcode;
8898
8899 /* Go through list of pipes, (maybe) executing them. */
8900 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008901 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008902 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008903
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008904 if (G.flag_SIGINT)
8905 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008906 if (G_flag_return_in_progress == 1)
8907 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008908
8909 IF_HAS_KEYWORDS(rword = pi->res_word;)
8910 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8911 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008912
8913 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008914 if (
8915#if ENABLE_HUSH_IF
8916 rword == RES_IF || rword == RES_ELIF ||
8917#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008918 pi->followup != PIPE_SEQ
8919 ) {
8920 G.errexit_depth++;
8921 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008922#if ENABLE_HUSH_LOOPS
8923 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8924 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8925 ) {
8926 /* start of a loop: remember where loop starts */
8927 loop_top = pi;
8928 G.depth_of_loop++;
8929 }
8930#endif
8931 /* Still in the same "if...", "then..." or "do..." branch? */
8932 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8933 if ((rcode == 0 && last_followup == PIPE_OR)
8934 || (rcode != 0 && last_followup == PIPE_AND)
8935 ) {
8936 /* It is "<true> || CMD" or "<false> && CMD"
8937 * and we should not execute CMD */
8938 debug_printf_exec("skipped cmd because of || or &&\n");
8939 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008940 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008941 }
8942 }
8943 last_followup = pi->followup;
8944 IF_HAS_KEYWORDS(last_rword = rword;)
8945#if ENABLE_HUSH_IF
8946 if (cond_code) {
8947 if (rword == RES_THEN) {
8948 /* if false; then ... fi has exitcode 0! */
8949 G.last_exitcode = rcode = EXIT_SUCCESS;
8950 /* "if <false> THEN cmd": skip cmd */
8951 continue;
8952 }
8953 } else {
8954 if (rword == RES_ELSE || rword == RES_ELIF) {
8955 /* "if <true> then ... ELSE/ELIF cmd":
8956 * skip cmd and all following ones */
8957 break;
8958 }
8959 }
8960#endif
8961#if ENABLE_HUSH_LOOPS
8962 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8963 if (!for_lcur) {
8964 /* first loop through for */
8965
8966 static const char encoded_dollar_at[] ALIGN1 = {
8967 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8968 }; /* encoded representation of "$@" */
8969 static const char *const encoded_dollar_at_argv[] = {
8970 encoded_dollar_at, NULL
8971 }; /* argv list with one element: "$@" */
8972 char **vals;
8973
8974 vals = (char**)encoded_dollar_at_argv;
8975 if (pi->next->res_word == RES_IN) {
8976 /* if no variable values after "in" we skip "for" */
8977 if (!pi->next->cmds[0].argv) {
8978 G.last_exitcode = rcode = EXIT_SUCCESS;
8979 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8980 break;
8981 }
8982 vals = pi->next->cmds[0].argv;
8983 } /* else: "for var; do..." -> assume "$@" list */
8984 /* create list of variable values */
8985 debug_print_strings("for_list made from", vals);
8986 for_list = expand_strvec_to_strvec(vals);
8987 for_lcur = for_list;
8988 debug_print_strings("for_list", for_list);
8989 }
8990 if (!*for_lcur) {
8991 /* "for" loop is over, clean up */
8992 free(for_list);
8993 for_list = NULL;
8994 for_lcur = NULL;
8995 break;
8996 }
8997 /* Insert next value from for_lcur */
8998 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008999 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009000 continue;
9001 }
9002 if (rword == RES_IN) {
9003 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9004 }
9005 if (rword == RES_DONE) {
9006 continue; /* "done" has no cmds too */
9007 }
9008#endif
9009#if ENABLE_HUSH_CASE
9010 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009011 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009012 case_word = expand_string_to_string(pi->cmds->argv[0],
9013 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009014 debug_printf_exec("CASE word1:'%s'\n", case_word);
9015 //unbackslash(case_word);
9016 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009017 continue;
9018 }
9019 if (rword == RES_MATCH) {
9020 char **argv;
9021
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009022 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009023 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9024 break;
9025 /* all prev words didn't match, does this one match? */
9026 argv = pi->cmds->argv;
9027 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009028 char *pattern;
9029 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9030 pattern = expand_string_to_string(*argv,
9031 EXP_FLAG_ESC_GLOB_CHARS,
9032 /*unbackslash:*/ 0
9033 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009034 /* TODO: which FNM_xxx flags to use? */
9035 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009036 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9037 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009038 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009039 if (cond_code == 0) {
9040 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009041 free(case_word);
9042 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009043 break;
9044 }
9045 argv++;
9046 }
9047 continue;
9048 }
9049 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009050 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009051 if (cond_code != 0)
9052 continue; /* not matched yet, skip this pipe */
9053 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009054 if (rword == RES_ESAC) {
9055 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9056 if (case_word) {
9057 /* "case" did not match anything: still set $? (to 0) */
9058 G.last_exitcode = rcode = EXIT_SUCCESS;
9059 }
9060 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009061#endif
9062 /* Just pressing <enter> in shell should check for jobs.
9063 * OTOH, in non-interactive shell this is useless
9064 * and only leads to extra job checks */
9065 if (pi->num_cmds == 0) {
9066 if (G_interactive_fd)
9067 goto check_jobs_and_continue;
9068 continue;
9069 }
9070
9071 /* After analyzing all keywords and conditions, we decided
9072 * to execute this pipe. NB: have to do checkjobs(NULL)
9073 * after run_pipe to collect any background children,
9074 * even if list execution is to be stopped. */
9075 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009076#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009077 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009078#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009079 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9080 if (r != -1) {
9081 /* We ran a builtin, function, or group.
9082 * rcode is already known
9083 * and we don't need to wait for anything. */
9084 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9085 G.last_exitcode = rcode;
9086 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009087#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009088 /* Was it "break" or "continue"? */
9089 if (G.flag_break_continue) {
9090 smallint fbc = G.flag_break_continue;
9091 /* We might fall into outer *loop*,
9092 * don't want to break it too */
9093 if (loop_top) {
9094 G.depth_break_continue--;
9095 if (G.depth_break_continue == 0)
9096 G.flag_break_continue = 0;
9097 /* else: e.g. "continue 2" should *break* once, *then* continue */
9098 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9099 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009100 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009101 break;
9102 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009103 /* "continue": simulate end of loop */
9104 rword = RES_DONE;
9105 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009106 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009107#endif
9108 if (G_flag_return_in_progress == 1) {
9109 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9110 break;
9111 }
9112 } else if (pi->followup == PIPE_BG) {
9113 /* What does bash do with attempts to background builtins? */
9114 /* even bash 3.2 doesn't do that well with nested bg:
9115 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9116 * I'm NOT treating inner &'s as jobs */
9117#if ENABLE_HUSH_JOB
9118 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009119 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009120#endif
9121 /* Last command's pid goes to $! */
9122 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009123 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009124 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009125/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009126 rcode = EXIT_SUCCESS;
9127 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009128 } else {
9129#if ENABLE_HUSH_JOB
9130 if (G.run_list_level == 1 && G_interactive_fd) {
9131 /* Waits for completion, then fg's main shell */
9132 rcode = checkjobs_and_fg_shell(pi);
9133 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009134 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009135 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009136#endif
9137 /* This one just waits for completion */
9138 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9139 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9140 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009141 G.last_exitcode = rcode;
9142 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009143 }
9144
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009145 /* Handle "set -e" */
9146 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9147 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9148 if (G.errexit_depth == 0)
9149 hush_exit(rcode);
9150 }
9151 G.errexit_depth = sv_errexit_depth;
9152
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009153 /* Analyze how result affects subsequent commands */
9154#if ENABLE_HUSH_IF
9155 if (rword == RES_IF || rword == RES_ELIF)
9156 cond_code = rcode;
9157#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009158 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009159 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009160 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009161#if ENABLE_HUSH_LOOPS
9162 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009163 if (pi->next
9164 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009165 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009166 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009167 if (rword == RES_WHILE) {
9168 if (rcode) {
9169 /* "while false; do...done" - exitcode 0 */
9170 G.last_exitcode = rcode = EXIT_SUCCESS;
9171 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009172 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009173 }
9174 }
9175 if (rword == RES_UNTIL) {
9176 if (!rcode) {
9177 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009178 break;
9179 }
9180 }
9181 }
9182#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009183 } /* for (pi) */
9184
9185#if ENABLE_HUSH_JOB
9186 G.run_list_level--;
9187#endif
9188#if ENABLE_HUSH_LOOPS
9189 if (loop_top)
9190 G.depth_of_loop--;
9191 free(for_list);
9192#endif
9193#if ENABLE_HUSH_CASE
9194 free(case_word);
9195#endif
9196 debug_leave();
9197 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9198 return rcode;
9199}
9200
9201/* Select which version we will use */
9202static int run_and_free_list(struct pipe *pi)
9203{
9204 int rcode = 0;
9205 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009206 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009207 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9208 rcode = run_list(pi);
9209 }
9210 /* free_pipe_list has the side effect of clearing memory.
9211 * In the long run that function can be merged with run_list,
9212 * but doing that now would hobble the debugging effort. */
9213 free_pipe_list(pi);
9214 debug_printf_exec("run_and_free_list return %d\n", rcode);
9215 return rcode;
9216}
9217
9218
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009219static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009220{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009221 sighandler_t old_handler;
9222 unsigned sig = 0;
9223 while ((mask >>= 1) != 0) {
9224 sig++;
9225 if (!(mask & 1))
9226 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009227 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009228 /* POSIX allows shell to re-enable SIGCHLD
9229 * even if it was SIG_IGN on entry.
9230 * Therefore we skip IGN check for it:
9231 */
9232 if (sig == SIGCHLD)
9233 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009234 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9235 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9236 */
9237 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009238 if (old_handler == SIG_IGN) {
9239 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009240 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009241#if ENABLE_HUSH_TRAP
9242 if (!G_traps)
9243 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9244 free(G_traps[sig]);
9245 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9246#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009247 }
9248 }
9249}
9250
9251/* Called a few times only (or even once if "sh -c") */
9252static void install_special_sighandlers(void)
9253{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009254 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009255
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009256 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009257 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009258 if (G_interactive_fd) {
9259 mask |= SPECIAL_INTERACTIVE_SIGS;
9260 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009261 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009262 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009263 /* Careful, do not re-install handlers we already installed */
9264 if (G.special_sig_mask != mask) {
9265 unsigned diff = mask & ~G.special_sig_mask;
9266 G.special_sig_mask = mask;
9267 install_sighandlers(diff);
9268 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009269}
9270
9271#if ENABLE_HUSH_JOB
9272/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009273/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009274static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009275{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009276 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009277
9278 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009279 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009280 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9281 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009282 + (1 << SIGBUS ) * HUSH_DEBUG
9283 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009284 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009285 + (1 << SIGABRT)
9286 /* bash 3.2 seems to handle these just like 'fatal' ones */
9287 + (1 << SIGPIPE)
9288 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009289 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009290 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009291 * we never want to restore pgrp on exit, and this fn is not called
9292 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009293 /*+ (1 << SIGHUP )*/
9294 /*+ (1 << SIGTERM)*/
9295 /*+ (1 << SIGINT )*/
9296 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009297 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009298
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009299 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009300}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009301#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009302
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009303static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009304{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009305 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009306 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009307 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009308 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009309 break;
9310 case 'x':
9311 IF_HUSH_MODE_X(G_x_mode = state;)
9312 break;
9313 case 'o':
9314 if (!o_opt) {
9315 /* "set -+o" without parameter.
9316 * in bash, set -o produces this output:
9317 * pipefail off
9318 * and set +o:
9319 * set +o pipefail
9320 * We always use the second form.
9321 */
9322 const char *p = o_opt_strings;
9323 idx = 0;
9324 while (*p) {
9325 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9326 idx++;
9327 p += strlen(p) + 1;
9328 }
9329 break;
9330 }
9331 idx = index_in_strings(o_opt_strings, o_opt);
9332 if (idx >= 0) {
9333 G.o_opt[idx] = state;
9334 break;
9335 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009336 case 'e':
9337 G.o_opt[OPT_O_ERREXIT] = state;
9338 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009339 default:
9340 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009341 }
9342 return EXIT_SUCCESS;
9343}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009344
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009345int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009346int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009347{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009348 enum {
9349 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009350 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009351 };
9352 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009353 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009354 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009355 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009356 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009357
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009358 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009359 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009360 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009361
Denys Vlasenko10c01312011-05-11 11:49:21 +02009362#if ENABLE_HUSH_FAST
9363 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9364#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009365#if !BB_MMU
9366 G.argv0_for_re_execing = argv[0];
9367#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009368
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009369 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009370 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9371 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009372 shell_ver = xzalloc(sizeof(*shell_ver));
9373 shell_ver->flg_export = 1;
9374 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009375 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009376 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009377 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009378
Denys Vlasenko605067b2010-09-06 12:10:51 +02009379 /* Create shell local variables from the values
9380 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009381 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009382 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009383 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009384 if (e) while (*e) {
9385 char *value = strchr(*e, '=');
9386 if (value) { /* paranoia */
9387 cur_var->next = xzalloc(sizeof(*cur_var));
9388 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009389 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009390 cur_var->max_len = strlen(*e);
9391 cur_var->flg_export = 1;
9392 }
9393 e++;
9394 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009395 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009396 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9397 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009398
9399 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009400 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009401
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009402#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9403 /* Set (but not export) PS1/2 unless already set */
9404 if (!get_local_var_value("PS1"))
9405 set_local_var_from_halves("PS1", "\\w \\$ ");
9406 if (!get_local_var_value("PS2"))
9407 set_local_var_from_halves("PS2", "> ");
9408#endif
9409
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009410#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009411 /* Set (but not export) HOSTNAME unless already set */
9412 if (!get_local_var_value("HOSTNAME")) {
9413 struct utsname uts;
9414 uname(&uts);
9415 set_local_var_from_halves("HOSTNAME", uts.nodename);
9416 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009417 /* bash also exports SHLVL and _,
9418 * and sets (but doesn't export) the following variables:
9419 * BASH=/bin/bash
9420 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9421 * BASH_VERSION='3.2.0(1)-release'
9422 * HOSTTYPE=i386
9423 * MACHTYPE=i386-pc-linux-gnu
9424 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009425 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009426 * EUID=<NNNNN>
9427 * UID=<NNNNN>
9428 * GROUPS=()
9429 * LINES=<NNN>
9430 * COLUMNS=<NNN>
9431 * BASH_ARGC=()
9432 * BASH_ARGV=()
9433 * BASH_LINENO=()
9434 * BASH_SOURCE=()
9435 * DIRSTACK=()
9436 * PIPESTATUS=([0]="0")
9437 * HISTFILE=/<xxx>/.bash_history
9438 * HISTFILESIZE=500
9439 * HISTSIZE=500
9440 * MAILCHECK=60
9441 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9442 * SHELL=/bin/bash
9443 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9444 * TERM=dumb
9445 * OPTERR=1
9446 * OPTIND=1
9447 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009448 * PS4='+ '
9449 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009450#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009451
Denys Vlasenko5807e182018-02-08 19:19:04 +01009452#if ENABLE_HUSH_LINENO_VAR
9453 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009454 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9455 set_local_var(p, /*flags*/ 0);
9456 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9457 }
9458#endif
9459
Denis Vlasenko38f63192007-01-22 09:03:07 +00009460#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009461 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009462#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009463
Eric Andersen94ac2442001-05-22 19:05:18 +00009464 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009465 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009466
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009467 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009468
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009469 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009470 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009471 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009472 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009473 * in order to intercept (more) signals.
9474 */
9475
9476 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009477 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009478 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009479 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009480 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009481 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009482#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009483 "<:$:R:V:"
9484# if ENABLE_HUSH_FUNCTIONS
9485 "F:"
9486# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009487#endif
9488 );
9489 if (opt <= 0)
9490 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009491 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009492 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009493 /* Possibilities:
9494 * sh ... -c 'script'
9495 * sh ... -c 'script' ARG0 [ARG1...]
9496 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009497 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009498 * "" needs to be replaced with NULL
9499 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009500 * Note: the form without ARG0 never happens:
9501 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009502 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009503 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009504 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009505 G.root_ppid = getppid();
9506 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009507 G.global_argv = argv + optind;
9508 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009509 if (builtin_argc) {
9510 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9511 const struct built_in_command *x;
9512
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009513 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009514 x = find_builtin(optarg);
9515 if (x) { /* paranoia */
9516 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9517 G.global_argv += builtin_argc;
9518 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009519 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009520 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009521 }
9522 goto final_return;
9523 }
9524 if (!G.global_argv[0]) {
9525 /* -c 'script' (no params): prevent empty $0 */
9526 G.global_argv--; /* points to argv[i] of 'script' */
9527 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009528 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009529 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009530 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009531 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009532 goto final_return;
9533 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009534 /* Well, we cannot just declare interactiveness,
9535 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009536 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009537 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009538 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009539 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009540 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009541 case 'l':
9542 flags |= OPT_login;
9543 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009544#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009545 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009546 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009547 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009548 case '$': {
9549 unsigned long long empty_trap_mask;
9550
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009551 G.root_pid = bb_strtou(optarg, &optarg, 16);
9552 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009553 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9554 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009555 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9556 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009557 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009558 optarg++;
9559 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009560 optarg++;
9561 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9562 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009563 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009564 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009565# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009566 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009567 for (sig = 1; sig < NSIG; sig++) {
9568 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009569 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009570 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009571 }
9572 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009573# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009574 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009575# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009576 optarg++;
9577 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009578# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009579# if ENABLE_HUSH_FUNCTIONS
9580 /* nommu uses re-exec trick for "... | func | ...",
9581 * should allow "return".
9582 * This accidentally allows returns in subshells.
9583 */
9584 G_flag_return_in_progress = -1;
9585# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009586 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009587 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009588 case 'R':
9589 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009590 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009591 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009592# if ENABLE_HUSH_FUNCTIONS
9593 case 'F': {
9594 struct function *funcp = new_function(optarg);
9595 /* funcp->name is already set to optarg */
9596 /* funcp->body is set to NULL. It's a special case. */
9597 funcp->body_as_string = argv[optind];
9598 optind++;
9599 break;
9600 }
9601# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009602#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009603 case 'n':
9604 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009605 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009606 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009607 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009608 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009609#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009610 fprintf(stderr, "Usage: sh [FILE]...\n"
9611 " or: sh -c command [args]...\n\n");
9612 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009613#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009614 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009615#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009616 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009617 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009618
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009619 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9620 G.global_argc = argc - (optind - 1);
9621 G.global_argv = argv + (optind - 1);
9622 G.global_argv[0] = argv[0];
9623
Denys Vlasenkodea47882009-10-09 15:40:49 +02009624 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009625 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009626 G.root_ppid = getppid();
9627 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009628
9629 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009630 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009631 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009632 debug_printf("sourcing /etc/profile\n");
9633 input = fopen_for_read("/etc/profile");
9634 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009635 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009636 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009637 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009638 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009639 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009640 /* bash: after sourcing /etc/profile,
9641 * tries to source (in the given order):
9642 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009643 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009644 * bash also sources ~/.bash_logout on exit.
9645 * If called as sh, skips .bash_XXX files.
9646 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009647 }
9648
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009649 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9650 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009651 FILE *input;
9652 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009653 * "bash <script>" (which is never interactive (unless -i?))
9654 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009655 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009656 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009657 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009658 G.global_argc--;
9659 G.global_argv++;
9660 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009661 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009662 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009663 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009664 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009665 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009666 parse_and_run_file(input);
9667#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009668 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009669#endif
9670 goto final_return;
9671 }
9672
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009673 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009674 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009675 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009676
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009677 /* A shell is interactive if the '-i' flag was given,
9678 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009679 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009680 * no arguments remaining or the -s flag given
9681 * standard input is a terminal
9682 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009683 * Refer to Posix.2, the description of the 'sh' utility.
9684 */
9685#if ENABLE_HUSH_JOB
9686 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009687 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9688 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9689 if (G_saved_tty_pgrp < 0)
9690 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009691
9692 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009693 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009694 if (G_interactive_fd < 0) {
9695 /* try to dup to any fd */
9696 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009697 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009698 /* give up */
9699 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009700 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009701 }
9702 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009703// TODO: track & disallow any attempts of user
9704// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009705 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009706 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009707 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009708 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009709
Mike Frysinger38478a62009-05-20 04:48:06 -04009710 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009711 /* If we were run as 'hush &', sleep until we are
9712 * in the foreground (tty pgrp == our pgrp).
9713 * If we get started under a job aware app (like bash),
9714 * make sure we are now in charge so we don't fight over
9715 * who gets the foreground */
9716 while (1) {
9717 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009718 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9719 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009720 break;
9721 /* send TTIN to ourself (should stop us) */
9722 kill(- shell_pgrp, SIGTTIN);
9723 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009724 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009725
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009726 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009727 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009728
Mike Frysinger38478a62009-05-20 04:48:06 -04009729 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009730 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009731 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009732 /* Put ourselves in our own process group
9733 * (bash, too, does this only if ctty is available) */
9734 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9735 /* Grab control of the terminal */
9736 tcsetpgrp(G_interactive_fd, getpid());
9737 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009738 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009739
9740# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9741 {
9742 const char *hp = get_local_var_value("HISTFILE");
9743 if (!hp) {
9744 hp = get_local_var_value("HOME");
9745 if (hp)
9746 hp = concat_path_file(hp, ".hush_history");
9747 } else {
9748 hp = xstrdup(hp);
9749 }
9750 if (hp) {
9751 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009752 //set_local_var(xasprintf("HISTFILE=%s", ...));
9753 }
9754# if ENABLE_FEATURE_SH_HISTFILESIZE
9755 hp = get_local_var_value("HISTFILESIZE");
9756 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9757# endif
9758 }
9759# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009760 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009761 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009762 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009763#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009764 /* No job control compiled in, only prompt/line editing */
9765 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009766 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009767 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009768 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +02009769 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009770 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009771 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009772 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009773 }
9774 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009775 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009776 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009777 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009778 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009779#else
9780 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009781 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009782#endif
9783 /* bash:
9784 * if interactive but not a login shell, sources ~/.bashrc
9785 * (--norc turns this off, --rcfile <file> overrides)
9786 */
9787
9788 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009789 /* note: ash and hush share this string */
9790 printf("\n\n%s %s\n"
9791 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9792 "\n",
9793 bb_banner,
9794 "hush - the humble shell"
9795 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009796 }
9797
Denis Vlasenkof9375282009-04-05 19:13:39 +00009798 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009799
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009800 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009801 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009802}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009803
9804
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009805/*
9806 * Built-ins
9807 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009808static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009809{
9810 return 0;
9811}
9812
Denys Vlasenko265062d2017-01-10 15:13:30 +01009813#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009814static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009815{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009816 int argc = string_array_len(argv);
9817 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009818}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009819#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009820#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009821static int FAST_FUNC builtin_test(char **argv)
9822{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009823 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009824}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009825#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009826#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009827static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009828{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009829 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009830}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009831#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009832#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009833static int FAST_FUNC builtin_printf(char **argv)
9834{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009835 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009836}
9837#endif
9838
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009839#if ENABLE_HUSH_HELP
9840static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9841{
9842 const struct built_in_command *x;
9843
9844 printf(
9845 "Built-in commands:\n"
9846 "------------------\n");
9847 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9848 if (x->b_descr)
9849 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9850 }
9851 return EXIT_SUCCESS;
9852}
9853#endif
9854
9855#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9856static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9857{
9858 show_history(G.line_input_state);
9859 return EXIT_SUCCESS;
9860}
9861#endif
9862
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009863static char **skip_dash_dash(char **argv)
9864{
9865 argv++;
9866 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9867 argv++;
9868 return argv;
9869}
9870
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009871static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009872{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009873 const char *newdir;
9874
9875 argv = skip_dash_dash(argv);
9876 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009877 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009878 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009879 * bash says "bash: cd: HOME not set" and does nothing
9880 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009881 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009882 const char *home = get_local_var_value("HOME");
9883 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009884 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009885 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009886 /* Mimic bash message exactly */
9887 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009888 return EXIT_FAILURE;
9889 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009890 /* Read current dir (get_cwd(1) is inside) and set PWD.
9891 * Note: do not enforce exporting. If PWD was unset or unexported,
9892 * set it again, but do not export. bash does the same.
9893 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009894 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009895 return EXIT_SUCCESS;
9896}
9897
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009898static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9899{
9900 puts(get_cwd(0));
9901 return EXIT_SUCCESS;
9902}
9903
9904static int FAST_FUNC builtin_eval(char **argv)
9905{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009906 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009907
Denys Vlasenkob0441a72018-07-15 18:03:56 +02009908 if (!argv[0])
9909 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +01009910
Denys Vlasenkob0441a72018-07-15 18:03:56 +02009911 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009912 /* bash:
9913 * eval "echo Hi; done" ("done" is syntax error):
9914 * "echo Hi" will not execute too.
9915 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +02009916 parse_and_run_string(argv[0]);
9917 } else {
9918 /* "The eval utility shall construct a command by
9919 * concatenating arguments together, separating
9920 * each with a <space> character."
9921 */
9922 char *str, *p;
9923 unsigned len = 0;
9924 char **pp = argv;
9925 do
9926 len += strlen(*pp) + 1;
9927 while (*++pp);
9928 str = p = xmalloc(len);
9929 pp = argv;
9930 for (;;) {
9931 p = stpcpy(p, *pp);
9932 pp++;
9933 if (!*pp)
9934 break;
9935 *p++ = ' ';
9936 }
9937 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009938 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009939 }
Denys Vlasenkob0441a72018-07-15 18:03:56 +02009940 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009941}
9942
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009943static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009944{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009945 argv = skip_dash_dash(argv);
9946 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009947 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009948
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009949 /* Careful: we can end up here after [v]fork. Do not restore
9950 * tty pgrp then, only top-level shell process does that */
9951 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9952 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9953
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009954 /* Saved-redirect fds, script fds and G_interactive_fd are still
9955 * open here. However, they are all CLOEXEC, and execv below
9956 * closes them. Try interactive "exec ls -l /proc/self/fd",
9957 * it should show no extra open fds in the "ls" process.
9958 * If we'd try to run builtins/NOEXECs, this would need improving.
9959 */
9960 //close_saved_fds_and_FILE_fds();
9961
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009962 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009963 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009964 * and tcsetpgrp, and this is inherently racy.
9965 */
9966 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009967}
9968
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009969static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009970{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009971 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009972
9973 /* interactive bash:
9974 * # trap "echo EEE" EXIT
9975 * # exit
9976 * exit
9977 * There are stopped jobs.
9978 * (if there are _stopped_ jobs, running ones don't count)
9979 * # exit
9980 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009981 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009982 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009983 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009984 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009985
9986 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009987 argv = skip_dash_dash(argv);
9988 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009989 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009990 /* mimic bash: exit 123abc == exit 255 + error msg */
9991 xfunc_error_retval = 255;
9992 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009993 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009994}
9995
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009996#if ENABLE_HUSH_TYPE
9997/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9998static int FAST_FUNC builtin_type(char **argv)
9999{
10000 int ret = EXIT_SUCCESS;
10001
10002 while (*++argv) {
10003 const char *type;
10004 char *path = NULL;
10005
10006 if (0) {} /* make conditional compile easier below */
10007 /*else if (find_alias(*argv))
10008 type = "an alias";*/
10009#if ENABLE_HUSH_FUNCTIONS
10010 else if (find_function(*argv))
10011 type = "a function";
10012#endif
10013 else if (find_builtin(*argv))
10014 type = "a shell builtin";
10015 else if ((path = find_in_path(*argv)) != NULL)
10016 type = path;
10017 else {
10018 bb_error_msg("type: %s: not found", *argv);
10019 ret = EXIT_FAILURE;
10020 continue;
10021 }
10022
10023 printf("%s is %s\n", *argv, type);
10024 free(path);
10025 }
10026
10027 return ret;
10028}
10029#endif
10030
10031#if ENABLE_HUSH_READ
10032/* Interruptibility of read builtin in bash
10033 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10034 *
10035 * Empty trap makes read ignore corresponding signal, for any signal.
10036 *
10037 * SIGINT:
10038 * - terminates non-interactive shell;
10039 * - interrupts read in interactive shell;
10040 * if it has non-empty trap:
10041 * - executes trap and returns to command prompt in interactive shell;
10042 * - executes trap and returns to read in non-interactive shell;
10043 * SIGTERM:
10044 * - is ignored (does not interrupt) read in interactive shell;
10045 * - terminates non-interactive shell;
10046 * if it has non-empty trap:
10047 * - executes trap and returns to read;
10048 * SIGHUP:
10049 * - terminates shell (regardless of interactivity);
10050 * if it has non-empty trap:
10051 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010052 * SIGCHLD from children:
10053 * - does not interrupt read regardless of interactivity:
10054 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010055 */
10056static int FAST_FUNC builtin_read(char **argv)
10057{
10058 const char *r;
10059 char *opt_n = NULL;
10060 char *opt_p = NULL;
10061 char *opt_t = NULL;
10062 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010063 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010064 const char *ifs;
10065 int read_flags;
10066
10067 /* "!": do not abort on errors.
10068 * Option string must start with "sr" to match BUILTIN_READ_xxx
10069 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010070 read_flags = getopt32(argv,
10071#if BASH_READ_D
10072 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10073#else
10074 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10075#endif
10076 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010077 if (read_flags == (uint32_t)-1)
10078 return EXIT_FAILURE;
10079 argv += optind;
10080 ifs = get_local_var_value("IFS"); /* can be NULL */
10081
10082 again:
10083 r = shell_builtin_read(set_local_var_from_halves,
10084 argv,
10085 ifs,
10086 read_flags,
10087 opt_n,
10088 opt_p,
10089 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010090 opt_u,
10091 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010092 );
10093
10094 if ((uintptr_t)r == 1 && errno == EINTR) {
10095 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010096 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010097 goto again;
10098 }
10099
10100 if ((uintptr_t)r > 1) {
10101 bb_error_msg("%s", r);
10102 r = (char*)(uintptr_t)1;
10103 }
10104
10105 return (uintptr_t)r;
10106}
10107#endif
10108
10109#if ENABLE_HUSH_UMASK
10110static int FAST_FUNC builtin_umask(char **argv)
10111{
10112 int rc;
10113 mode_t mask;
10114
10115 rc = 1;
10116 mask = umask(0);
10117 argv = skip_dash_dash(argv);
10118 if (argv[0]) {
10119 mode_t old_mask = mask;
10120
10121 /* numeric umasks are taken as-is */
10122 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10123 if (!isdigit(argv[0][0]))
10124 mask ^= 0777;
10125 mask = bb_parse_mode(argv[0], mask);
10126 if (!isdigit(argv[0][0]))
10127 mask ^= 0777;
10128 if ((unsigned)mask > 0777) {
10129 mask = old_mask;
10130 /* bash messages:
10131 * bash: umask: 'q': invalid symbolic mode operator
10132 * bash: umask: 999: octal number out of range
10133 */
10134 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10135 rc = 0;
10136 }
10137 } else {
10138 /* Mimic bash */
10139 printf("%04o\n", (unsigned) mask);
10140 /* fall through and restore mask which we set to 0 */
10141 }
10142 umask(mask);
10143
10144 return !rc; /* rc != 0 - success */
10145}
10146#endif
10147
Denys Vlasenko41ade052017-01-08 18:56:24 +010010148#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010149static void print_escaped(const char *s)
10150{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010151 if (*s == '\'')
10152 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010153 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010154 const char *p = strchrnul(s, '\'');
10155 /* print 'xxxx', possibly just '' */
10156 printf("'%.*s'", (int)(p - s), s);
10157 if (*p == '\0')
10158 break;
10159 s = p;
10160 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010161 /* s points to '; print "'''...'''" */
10162 putchar('"');
10163 do putchar('\''); while (*++s == '\'');
10164 putchar('"');
10165 } while (*s);
10166}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010167#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010168
Denys Vlasenko1e660422017-07-17 21:10:50 +020010169#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010170static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010171{
10172 do {
10173 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010174 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010175
10176 /* So far we do not check that name is valid (TODO?) */
10177
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010178 if (*name_end == '\0') {
10179 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010180
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010181 vpp = get_ptr_to_local_var(name, name_end - name);
10182 var = vpp ? *vpp : NULL;
10183
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010184 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010185 /* export -n NAME (without =VALUE) */
10186 if (var) {
10187 var->flg_export = 0;
10188 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10189 unsetenv(name);
10190 } /* else: export -n NOT_EXISTING_VAR: no-op */
10191 continue;
10192 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010193 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010194 /* export NAME (without =VALUE) */
10195 if (var) {
10196 var->flg_export = 1;
10197 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10198 putenv(var->varstr);
10199 continue;
10200 }
10201 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010202 if (flags & SETFLAG_MAKE_RO) {
10203 /* readonly NAME (without =VALUE) */
10204 if (var) {
10205 var->flg_read_only = 1;
10206 continue;
10207 }
10208 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010209# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010210 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010211 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010212 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10213 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010214 /* "local x=abc; ...; local x" - ignore second local decl */
10215 continue;
10216 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010217 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010218# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010219 /* Exporting non-existing variable.
10220 * bash does not put it in environment,
10221 * but remembers that it is exported,
10222 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010223 * We just set it to "" and export.
10224 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010225 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010226 * bash sets the value to "".
10227 */
10228 /* Or, it's "readonly NAME" (without =VALUE).
10229 * bash remembers NAME and disallows its creation
10230 * in the future.
10231 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010232 name = xasprintf("%s=", name);
10233 } else {
10234 /* (Un)exporting/making local NAME=VALUE */
10235 name = xstrdup(name);
10236 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010237 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010238 if (set_local_var(name, flags))
10239 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010240 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010241 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010242}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010243#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010244
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010245#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010246static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010247{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010248 unsigned opt_unexport;
10249
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010250#if ENABLE_HUSH_EXPORT_N
10251 /* "!": do not abort on errors */
10252 opt_unexport = getopt32(argv, "!n");
10253 if (opt_unexport == (uint32_t)-1)
10254 return EXIT_FAILURE;
10255 argv += optind;
10256#else
10257 opt_unexport = 0;
10258 argv++;
10259#endif
10260
10261 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010262 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010263 if (e) {
10264 while (*e) {
10265#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010266 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010267#else
10268 /* ash emits: export VAR='VAL'
10269 * bash: declare -x VAR="VAL"
10270 * we follow ash example */
10271 const char *s = *e++;
10272 const char *p = strchr(s, '=');
10273
10274 if (!p) /* wtf? take next variable */
10275 continue;
10276 /* export var= */
10277 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010278 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010279 putchar('\n');
10280#endif
10281 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010282 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010283 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010284 return EXIT_SUCCESS;
10285 }
10286
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010287 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010288}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010289#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010290
Denys Vlasenko295fef82009-06-03 12:47:26 +020010291#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010292static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010293{
10294 if (G.func_nest_level == 0) {
10295 bb_error_msg("%s: not in a function", argv[0]);
10296 return EXIT_FAILURE; /* bash compat */
10297 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010298 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010299 /* Since all builtins run in a nested variable level,
10300 * need to use level - 1 here. Or else the variable will be removed at once
10301 * after builtin returns.
10302 */
10303 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010304}
10305#endif
10306
Denys Vlasenko1e660422017-07-17 21:10:50 +020010307#if ENABLE_HUSH_READONLY
10308static int FAST_FUNC builtin_readonly(char **argv)
10309{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010310 argv++;
10311 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010312 /* bash: readonly [-p]: list all readonly VARs
10313 * (-p has no effect in bash)
10314 */
10315 struct variable *e;
10316 for (e = G.top_var; e; e = e->next) {
10317 if (e->flg_read_only) {
10318//TODO: quote value: readonly VAR='VAL'
10319 printf("readonly %s\n", e->varstr);
10320 }
10321 }
10322 return EXIT_SUCCESS;
10323 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010324 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010325}
10326#endif
10327
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010328#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010329/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10330static int FAST_FUNC builtin_unset(char **argv)
10331{
10332 int ret;
10333 unsigned opts;
10334
10335 /* "!": do not abort on errors */
10336 /* "+": stop at 1st non-option */
10337 opts = getopt32(argv, "!+vf");
10338 if (opts == (unsigned)-1)
10339 return EXIT_FAILURE;
10340 if (opts == 3) {
10341 bb_error_msg("unset: -v and -f are exclusive");
10342 return EXIT_FAILURE;
10343 }
10344 argv += optind;
10345
10346 ret = EXIT_SUCCESS;
10347 while (*argv) {
10348 if (!(opts & 2)) { /* not -f */
10349 if (unset_local_var(*argv)) {
10350 /* unset <nonexistent_var> doesn't fail.
10351 * Error is when one tries to unset RO var.
10352 * Message was printed by unset_local_var. */
10353 ret = EXIT_FAILURE;
10354 }
10355 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010356# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010357 else {
10358 unset_func(*argv);
10359 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010360# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010361 argv++;
10362 }
10363 return ret;
10364}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010365#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010366
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010367#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010368/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10369 * built-in 'set' handler
10370 * SUSv3 says:
10371 * set [-abCefhmnuvx] [-o option] [argument...]
10372 * set [+abCefhmnuvx] [+o option] [argument...]
10373 * set -- [argument...]
10374 * set -o
10375 * set +o
10376 * Implementations shall support the options in both their hyphen and
10377 * plus-sign forms. These options can also be specified as options to sh.
10378 * Examples:
10379 * Write out all variables and their values: set
10380 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10381 * Turn on the -x and -v options: set -xv
10382 * Unset all positional parameters: set --
10383 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10384 * Set the positional parameters to the expansion of x, even if x expands
10385 * with a leading '-' or '+': set -- $x
10386 *
10387 * So far, we only support "set -- [argument...]" and some of the short names.
10388 */
10389static int FAST_FUNC builtin_set(char **argv)
10390{
10391 int n;
10392 char **pp, **g_argv;
10393 char *arg = *++argv;
10394
10395 if (arg == NULL) {
10396 struct variable *e;
10397 for (e = G.top_var; e; e = e->next)
10398 puts(e->varstr);
10399 return EXIT_SUCCESS;
10400 }
10401
10402 do {
10403 if (strcmp(arg, "--") == 0) {
10404 ++argv;
10405 goto set_argv;
10406 }
10407 if (arg[0] != '+' && arg[0] != '-')
10408 break;
10409 for (n = 1; arg[n]; ++n) {
10410 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10411 goto error;
10412 if (arg[n] == 'o' && argv[1])
10413 argv++;
10414 }
10415 } while ((arg = *++argv) != NULL);
10416 /* Now argv[0] is 1st argument */
10417
10418 if (arg == NULL)
10419 return EXIT_SUCCESS;
10420 set_argv:
10421
10422 /* NB: G.global_argv[0] ($0) is never freed/changed */
10423 g_argv = G.global_argv;
10424 if (G.global_args_malloced) {
10425 pp = g_argv;
10426 while (*++pp)
10427 free(*pp);
10428 g_argv[1] = NULL;
10429 } else {
10430 G.global_args_malloced = 1;
10431 pp = xzalloc(sizeof(pp[0]) * 2);
10432 pp[0] = g_argv[0]; /* retain $0 */
10433 g_argv = pp;
10434 }
10435 /* This realloc's G.global_argv */
10436 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10437
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010438 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010439
10440 return EXIT_SUCCESS;
10441
10442 /* Nothing known, so abort */
10443 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010444 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010445 return EXIT_FAILURE;
10446}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010447#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010448
10449static int FAST_FUNC builtin_shift(char **argv)
10450{
10451 int n = 1;
10452 argv = skip_dash_dash(argv);
10453 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010454 n = bb_strtou(argv[0], NULL, 10);
10455 if (errno || n < 0) {
10456 /* shared string with ash.c */
10457 bb_error_msg("Illegal number: %s", argv[0]);
10458 /*
10459 * ash aborts in this case.
10460 * bash prints error message and set $? to 1.
10461 * Interestingly, for "shift 99999" bash does not
10462 * print error message, but does set $? to 1
10463 * (and does no shifting at all).
10464 */
10465 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010466 }
10467 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010468 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010469 int m = 1;
10470 while (m <= n)
10471 free(G.global_argv[m++]);
10472 }
10473 G.global_argc -= n;
10474 memmove(&G.global_argv[1], &G.global_argv[n+1],
10475 G.global_argc * sizeof(G.global_argv[0]));
10476 return EXIT_SUCCESS;
10477 }
10478 return EXIT_FAILURE;
10479}
10480
Denys Vlasenko74d40582017-08-11 01:32:46 +020010481#if ENABLE_HUSH_GETOPTS
10482static int FAST_FUNC builtin_getopts(char **argv)
10483{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010484/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10485
Denys Vlasenko74d40582017-08-11 01:32:46 +020010486TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010487If a required argument is not found, and getopts is not silent,
10488a question mark (?) is placed in VAR, OPTARG is unset, and a
10489diagnostic message is printed. If getopts is silent, then a
10490colon (:) is placed in VAR and OPTARG is set to the option
10491character found.
10492
10493Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010494
10495"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010496*/
10497 char cbuf[2];
10498 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010499 int c, n, exitcode, my_opterr;
10500 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010501
10502 optstring = *++argv;
10503 if (!optstring || !(var = *++argv)) {
10504 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10505 return EXIT_FAILURE;
10506 }
10507
Denys Vlasenko238ff982017-08-29 13:38:30 +020010508 if (argv[1])
10509 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10510 else
10511 argv = G.global_argv;
10512 cbuf[1] = '\0';
10513
10514 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010515 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010516 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010517 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010518 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010519 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010520
10521 /* getopts stops on first non-option. Add "+" to force that */
10522 /*if (optstring[0] != '+')*/ {
10523 char *s = alloca(strlen(optstring) + 2);
10524 sprintf(s, "+%s", optstring);
10525 optstring = s;
10526 }
10527
Denys Vlasenko238ff982017-08-29 13:38:30 +020010528 /* Naively, now we should just
10529 * cp = get_local_var_value("OPTIND");
10530 * optind = cp ? atoi(cp) : 0;
10531 * optarg = NULL;
10532 * opterr = my_opterr;
10533 * c = getopt(string_array_len(argv), argv, optstring);
10534 * and be done? Not so fast...
10535 * Unlike normal getopt() usage in C programs, here
10536 * each successive call will (usually) have the same argv[] CONTENTS,
10537 * but not the ADDRESSES. Worse yet, it's possible that between
10538 * invocations of "getopts", there will be calls to shell builtins
10539 * which use getopt() internally. Example:
10540 * while getopts "abc" RES -a -bc -abc de; do
10541 * unset -ff func
10542 * done
10543 * This would not work correctly: getopt() call inside "unset"
10544 * modifies internal libc state which is tracking position in
10545 * multi-option strings ("-abc"). At best, it can skip options
10546 * or return the same option infinitely. With glibc implementation
10547 * of getopt(), it would use outright invalid pointers and return
10548 * garbage even _without_ "unset" mangling internal state.
10549 *
10550 * We resort to resetting getopt() state and calling it N times,
10551 * until we get Nth result (or failure).
10552 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10553 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010554 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010555 count = 0;
10556 n = string_array_len(argv);
10557 do {
10558 optarg = NULL;
10559 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10560 c = getopt(n, argv, optstring);
10561 if (c < 0)
10562 break;
10563 count++;
10564 } while (count <= G.getopt_count);
10565
10566 /* Set OPTIND. Prevent resetting of the magic counter! */
10567 set_local_var_from_halves("OPTIND", utoa(optind));
10568 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010569 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010570
10571 /* Set OPTARG */
10572 /* Always set or unset, never left as-is, even on exit/error:
10573 * "If no option was found, or if the option that was found
10574 * does not have an option-argument, OPTARG shall be unset."
10575 */
10576 cp = optarg;
10577 if (c == '?') {
10578 /* If ":optstring" and unknown option is seen,
10579 * it is stored to OPTARG.
10580 */
10581 if (optstring[1] == ':') {
10582 cbuf[0] = optopt;
10583 cp = cbuf;
10584 }
10585 }
10586 if (cp)
10587 set_local_var_from_halves("OPTARG", cp);
10588 else
10589 unset_local_var("OPTARG");
10590
10591 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010592 exitcode = EXIT_SUCCESS;
10593 if (c < 0) { /* -1: end of options */
10594 exitcode = EXIT_FAILURE;
10595 c = '?';
10596 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010597
Denys Vlasenko238ff982017-08-29 13:38:30 +020010598 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010599 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010600 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010601
Denys Vlasenko74d40582017-08-11 01:32:46 +020010602 return exitcode;
10603}
10604#endif
10605
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010606static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010607{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010608 char *arg_path, *filename;
10609 FILE *input;
10610 save_arg_t sv;
10611 char *args_need_save;
10612#if ENABLE_HUSH_FUNCTIONS
10613 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010614#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010615
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010616 argv = skip_dash_dash(argv);
10617 filename = argv[0];
10618 if (!filename) {
10619 /* bash says: "bash: .: filename argument required" */
10620 return 2; /* bash compat */
10621 }
10622 arg_path = NULL;
10623 if (!strchr(filename, '/')) {
10624 arg_path = find_in_path(filename);
10625 if (arg_path)
10626 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010627 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010628 errno = ENOENT;
10629 bb_simple_perror_msg(filename);
10630 return EXIT_FAILURE;
10631 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010632 }
10633 input = remember_FILE(fopen_or_warn(filename, "r"));
10634 free(arg_path);
10635 if (!input) {
10636 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10637 /* POSIX: non-interactive shell should abort here,
10638 * not merely fail. So far no one complained :)
10639 */
10640 return EXIT_FAILURE;
10641 }
10642
10643#if ENABLE_HUSH_FUNCTIONS
10644 sv_flg = G_flag_return_in_progress;
10645 /* "we are inside sourced file, ok to use return" */
10646 G_flag_return_in_progress = -1;
10647#endif
10648 args_need_save = argv[1]; /* used as a boolean variable */
10649 if (args_need_save)
10650 save_and_replace_G_args(&sv, argv);
10651
10652 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10653 G.last_exitcode = 0;
10654 parse_and_run_file(input);
10655 fclose_and_forget(input);
10656
10657 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10658 restore_G_args(&sv, argv);
10659#if ENABLE_HUSH_FUNCTIONS
10660 G_flag_return_in_progress = sv_flg;
10661#endif
10662
10663 return G.last_exitcode;
10664}
10665
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010666#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010667static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010668{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010669 int sig;
10670 char *new_cmd;
10671
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010672 if (!G_traps)
10673 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010674
10675 argv++;
10676 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010677 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010678 /* No args: print all trapped */
10679 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010680 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010681 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010682 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010683 /* note: bash adds "SIG", but only if invoked
10684 * as "bash". If called as "sh", or if set -o posix,
10685 * then it prints short signal names.
10686 * We are printing short names: */
10687 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010688 }
10689 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010690 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010691 return EXIT_SUCCESS;
10692 }
10693
10694 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010695 /* If first arg is a number: reset all specified signals */
10696 sig = bb_strtou(*argv, NULL, 10);
10697 if (errno == 0) {
10698 int ret;
10699 process_sig_list:
10700 ret = EXIT_SUCCESS;
10701 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010702 sighandler_t handler;
10703
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010704 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010705 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010706 ret = EXIT_FAILURE;
10707 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010708 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010709 continue;
10710 }
10711
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010712 free(G_traps[sig]);
10713 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010714
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010715 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010716 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010717
10718 /* There is no signal for 0 (EXIT) */
10719 if (sig == 0)
10720 continue;
10721
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010722 if (new_cmd)
10723 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10724 else
10725 /* We are removing trap handler */
10726 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010727 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010728 }
10729 return ret;
10730 }
10731
10732 if (!argv[1]) { /* no second arg */
10733 bb_error_msg("trap: invalid arguments");
10734 return EXIT_FAILURE;
10735 }
10736
10737 /* First arg is "-": reset all specified to default */
10738 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10739 /* Everything else: set arg as signal handler
10740 * (includes "" case, which ignores signal) */
10741 if (argv[0][0] == '-') {
10742 if (argv[0][1] == '\0') { /* "-" */
10743 /* new_cmd remains NULL: "reset these sigs" */
10744 goto reset_traps;
10745 }
10746 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10747 argv++;
10748 }
10749 /* else: "-something", no special meaning */
10750 }
10751 new_cmd = *argv;
10752 reset_traps:
10753 argv++;
10754 goto process_sig_list;
10755}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010756#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010757
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010758#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010759static struct pipe *parse_jobspec(const char *str)
10760{
10761 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010762 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010763
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010764 if (sscanf(str, "%%%u", &jobnum) != 1) {
10765 if (str[0] != '%'
10766 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10767 ) {
10768 bb_error_msg("bad argument '%s'", str);
10769 return NULL;
10770 }
10771 /* It is "%%", "%+" or "%" - current job */
10772 jobnum = G.last_jobid;
10773 if (jobnum == 0) {
10774 bb_error_msg("no current job");
10775 return NULL;
10776 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010777 }
10778 for (pi = G.job_list; pi; pi = pi->next) {
10779 if (pi->jobid == jobnum) {
10780 return pi;
10781 }
10782 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010783 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010784 return NULL;
10785}
10786
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010787static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10788{
10789 struct pipe *job;
10790 const char *status_string;
10791
10792 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10793 for (job = G.job_list; job; job = job->next) {
10794 if (job->alive_cmds == job->stopped_cmds)
10795 status_string = "Stopped";
10796 else
10797 status_string = "Running";
10798
10799 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10800 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010801
10802 clean_up_last_dead_job();
10803
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010804 return EXIT_SUCCESS;
10805}
10806
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010807/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010808static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010809{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010810 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010811 struct pipe *pi;
10812
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010813 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010814 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010815
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010816 /* If they gave us no args, assume they want the last backgrounded task */
10817 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010818 for (pi = G.job_list; pi; pi = pi->next) {
10819 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010820 goto found;
10821 }
10822 }
10823 bb_error_msg("%s: no current job", argv[0]);
10824 return EXIT_FAILURE;
10825 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010826
10827 pi = parse_jobspec(argv[1]);
10828 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010829 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010830 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010831 /* TODO: bash prints a string representation
10832 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010833 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010834 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010835 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010836 }
10837
10838 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010839 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10840 for (i = 0; i < pi->num_cmds; i++) {
10841 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010842 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010843 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010844
10845 i = kill(- pi->pgrp, SIGCONT);
10846 if (i < 0) {
10847 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010848 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010849 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010850 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010851 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010852 }
10853
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010854 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010855 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010856 return checkjobs_and_fg_shell(pi);
10857 }
10858 return EXIT_SUCCESS;
10859}
10860#endif
10861
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010862#if ENABLE_HUSH_KILL
10863static int FAST_FUNC builtin_kill(char **argv)
10864{
10865 int ret = 0;
10866
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010867# if ENABLE_HUSH_JOB
10868 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10869 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010870
10871 do {
10872 struct pipe *pi;
10873 char *dst;
10874 int j, n;
10875
10876 if (argv[i][0] != '%')
10877 continue;
10878 /*
10879 * "kill %N" - job kill
10880 * Converting to pgrp / pid kill
10881 */
10882 pi = parse_jobspec(argv[i]);
10883 if (!pi) {
10884 /* Eat bad jobspec */
10885 j = i;
10886 do {
10887 j++;
10888 argv[j - 1] = argv[j];
10889 } while (argv[j]);
10890 ret = 1;
10891 i--;
10892 continue;
10893 }
10894 /*
10895 * In jobs started under job control, we signal
10896 * entire process group by kill -PGRP_ID.
10897 * This happens, f.e., in interactive shell.
10898 *
10899 * Otherwise, we signal each child via
10900 * kill PID1 PID2 PID3.
10901 * Testcases:
10902 * sh -c 'sleep 1|sleep 1 & kill %1'
10903 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10904 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10905 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010906 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010907 dst = alloca(n * sizeof(int)*4);
10908 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010909 if (G_interactive_fd)
10910 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010911 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010912 struct command *cmd = &pi->cmds[j];
10913 /* Skip exited members of the job */
10914 if (cmd->pid == 0)
10915 continue;
10916 /*
10917 * kill_main has matching code to expect
10918 * leading space. Needed to not confuse
10919 * negative pids with "kill -SIGNAL_NO" syntax
10920 */
10921 dst += sprintf(dst, " %u", (int)cmd->pid);
10922 }
10923 *dst = '\0';
10924 } while (argv[++i]);
10925 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010926# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010927
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010928 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010929 ret = run_applet_main(argv, kill_main);
10930 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010931 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010932 return ret;
10933}
10934#endif
10935
10936#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010937/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010938#if !ENABLE_HUSH_JOB
10939# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10940#endif
10941static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010942{
10943 int ret = 0;
10944 for (;;) {
10945 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010946 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010947
Denys Vlasenko830ea352016-11-08 04:59:11 +010010948 if (!sigisemptyset(&G.pending_set))
10949 goto check_sig;
10950
Denys Vlasenko7e675362016-10-28 21:57:31 +020010951 /* waitpid is not interruptible by SA_RESTARTed
10952 * signals which we use. Thus, this ugly dance:
10953 */
10954
10955 /* Make sure possible SIGCHLD is stored in kernel's
10956 * pending signal mask before we call waitpid.
10957 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010958 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010959 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010960 sigfillset(&oldset); /* block all signals, remember old set */
10961 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010962
10963 if (!sigisemptyset(&G.pending_set)) {
10964 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010965 goto restore;
10966 }
10967
10968 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010969/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010970 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010971 debug_printf_exec("checkjobs:%d\n", ret);
10972#if ENABLE_HUSH_JOB
10973 if (waitfor_pipe) {
10974 int rcode = job_exited_or_stopped(waitfor_pipe);
10975 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10976 if (rcode >= 0) {
10977 ret = rcode;
10978 sigprocmask(SIG_SETMASK, &oldset, NULL);
10979 break;
10980 }
10981 }
10982#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010983 /* if ECHILD, there are no children (ret is -1 or 0) */
10984 /* if ret == 0, no children changed state */
10985 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010986 if (errno == ECHILD || ret) {
10987 ret--;
10988 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010989 ret = 0;
10990 sigprocmask(SIG_SETMASK, &oldset, NULL);
10991 break;
10992 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010993 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010994 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10995 /* Note: sigsuspend invokes signal handler */
10996 sigsuspend(&oldset);
10997 restore:
10998 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010999 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011000 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011001 sig = check_and_run_traps();
11002 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011003 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011004 ret = 128 + sig;
11005 break;
11006 }
11007 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11008 }
11009 return ret;
11010}
11011
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011012static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011013{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011014 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011015 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011016
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011017 argv = skip_dash_dash(argv);
11018 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011019 /* Don't care about wait results */
11020 /* Note 1: must wait until there are no more children */
11021 /* Note 2: must be interruptible */
11022 /* Examples:
11023 * $ sleep 3 & sleep 6 & wait
11024 * [1] 30934 sleep 3
11025 * [2] 30935 sleep 6
11026 * [1] Done sleep 3
11027 * [2] Done sleep 6
11028 * $ sleep 3 & sleep 6 & wait
11029 * [1] 30936 sleep 3
11030 * [2] 30937 sleep 6
11031 * [1] Done sleep 3
11032 * ^C <-- after ~4 sec from keyboard
11033 * $
11034 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011035 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011036 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011037
Denys Vlasenko7e675362016-10-28 21:57:31 +020011038 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011039 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011040 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011041#if ENABLE_HUSH_JOB
11042 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011043 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011044 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011045 wait_pipe = parse_jobspec(*argv);
11046 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011047 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011048 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011049 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011050 } else {
11051 /* waiting on "last dead job" removes it */
11052 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011053 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011054 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011055 /* else: parse_jobspec() already emitted error msg */
11056 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011057 }
11058#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011059 /* mimic bash message */
11060 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011061 ret = EXIT_FAILURE;
11062 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011063 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011064
Denys Vlasenko7e675362016-10-28 21:57:31 +020011065 /* Do we have such child? */
11066 ret = waitpid(pid, &status, WNOHANG);
11067 if (ret < 0) {
11068 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011069 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011070 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011071 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011072 /* "wait $!" but last bg task has already exited. Try:
11073 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11074 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011075 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011076 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011077 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011078 } else {
11079 /* Example: "wait 1". mimic bash message */
11080 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011081 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011082 } else {
11083 /* ??? */
11084 bb_perror_msg("wait %s", *argv);
11085 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011086 continue; /* bash checks all argv[] */
11087 }
11088 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011089 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011090 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011091 } else {
11092 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011093 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011094 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011095 if (WIFSIGNALED(status))
11096 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011097 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011098 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011099
11100 return ret;
11101}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011102#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011103
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011104#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11105static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11106{
11107 if (argv[1]) {
11108 def = bb_strtou(argv[1], NULL, 10);
11109 if (errno || def < def_min || argv[2]) {
11110 bb_error_msg("%s: bad arguments", argv[0]);
11111 def = UINT_MAX;
11112 }
11113 }
11114 return def;
11115}
11116#endif
11117
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011118#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011119static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011120{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011121 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011122 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011123 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011124 /* if we came from builtin_continue(), need to undo "= 1" */
11125 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011126 return EXIT_SUCCESS; /* bash compat */
11127 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011128 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011129
11130 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11131 if (depth == UINT_MAX)
11132 G.flag_break_continue = BC_BREAK;
11133 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011134 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011135
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011136 return EXIT_SUCCESS;
11137}
11138
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011139static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011140{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011141 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11142 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011143}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011144#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011145
11146#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011147static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011148{
11149 int rc;
11150
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011151 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011152 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11153 return EXIT_FAILURE; /* bash compat */
11154 }
11155
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011156 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011157
11158 /* bash:
11159 * out of range: wraps around at 256, does not error out
11160 * non-numeric param:
11161 * f() { false; return qwe; }; f; echo $?
11162 * bash: return: qwe: numeric argument required <== we do this
11163 * 255 <== we also do this
11164 */
11165 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11166 return rc;
11167}
11168#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011169
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011170#if ENABLE_HUSH_TIMES
11171static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11172{
11173 static const uint8_t times_tbl[] ALIGN1 = {
11174 ' ', offsetof(struct tms, tms_utime),
11175 '\n', offsetof(struct tms, tms_stime),
11176 ' ', offsetof(struct tms, tms_cutime),
11177 '\n', offsetof(struct tms, tms_cstime),
11178 0
11179 };
11180 const uint8_t *p;
11181 unsigned clk_tck;
11182 struct tms buf;
11183
11184 clk_tck = bb_clk_tck();
11185
11186 times(&buf);
11187 p = times_tbl;
11188 do {
11189 unsigned sec, frac;
11190 unsigned long t;
11191 t = *(clock_t *)(((char *) &buf) + p[1]);
11192 sec = t / clk_tck;
11193 frac = t % clk_tck;
11194 printf("%um%u.%03us%c",
11195 sec / 60, sec % 60,
11196 (frac * 1000) / clk_tck,
11197 p[0]);
11198 p += 2;
11199 } while (*p);
11200
11201 return EXIT_SUCCESS;
11202}
11203#endif
11204
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011205#if ENABLE_HUSH_MEMLEAK
11206static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11207{
11208 void *p;
11209 unsigned long l;
11210
11211# ifdef M_TRIM_THRESHOLD
11212 /* Optional. Reduces probability of false positives */
11213 malloc_trim(0);
11214# endif
11215 /* Crude attempt to find where "free memory" starts,
11216 * sans fragmentation. */
11217 p = malloc(240);
11218 l = (unsigned long)p;
11219 free(p);
11220 p = malloc(3400);
11221 if (l < (unsigned long)p) l = (unsigned long)p;
11222 free(p);
11223
11224
11225# if 0 /* debug */
11226 {
11227 struct mallinfo mi = mallinfo();
11228 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11229 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11230 }
11231# endif
11232
11233 if (!G.memleak_value)
11234 G.memleak_value = l;
11235
11236 l -= G.memleak_value;
11237 if ((long)l < 0)
11238 l = 0;
11239 l /= 1024;
11240 if (l > 127)
11241 l = 127;
11242
11243 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11244 return l;
11245}
11246#endif