blob: 3c19bceaa06b31b11ce058038461a67ecf13173c [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * TODO:
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//config: hush is a small shell. It handles the normal flow control
100//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101//config: case/esac. Redirections, here documents, $((arithmetic))
102//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//config:config HUSH_BASH_SOURCE_CURDIR
127//config: bool "'source' and '.' builtins search current directory after $PATH"
128//config: default n # do not encourage non-standard behavior
129//config: depends on HUSH_BASH_COMPAT
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//config: Enable interactive mode (prompt and command editing).
139//config: Without this, hush simply reads and executes commands
140//config: from stdin just like a shell script from a file.
141//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154//config: command (not entire shell), fg/bg builtins work. Without this option,
155//config: "cmd &" still works by simply spawning a process and immediately
156//config: prompting for next command (or executing next command in a script),
157//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200360#ifndef O_CLOEXEC
361# define O_CLOEXEC 0
362#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100363#ifndef F_DUPFD_CLOEXEC
364# define F_DUPFD_CLOEXEC F_DUPFD
365#endif
366#ifndef PIPE_BUF
367# define PIPE_BUF 4096 /* amount of buffering in a pipe */
368#endif
369
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000370
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100371/* So far, all bash compat is controlled by one config option */
372/* Separate defines document which part of code implements what */
373#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
374#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100375#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
376#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200377#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200378#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100379
380
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200381/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000382#define LEAK_HUNTING 0
383#define BUILD_AS_NOMMU 0
384/* Enable/disable sanity checks. Ok to enable in production,
385 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
386 * Keeping 1 for now even in released versions.
387 */
388#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200389/* Slightly bigger (+200 bytes), but faster hush.
390 * So far it only enables a trick with counting SIGCHLDs and forks,
391 * which allows us to do fewer waitpid's.
392 * (we can detect a case where neither forks were done nor SIGCHLDs happened
393 * and therefore waitpid will return the same result as last time)
394 */
395#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200396/* TODO: implement simplified code for users which do not need ${var%...} ops
397 * So far ${var%...} ops are always enabled:
398 */
399#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000400
401
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000402#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000403# undef BB_MMU
404# undef USE_FOR_NOMMU
405# undef USE_FOR_MMU
406# define BB_MMU 0
407# define USE_FOR_NOMMU(...) __VA_ARGS__
408# define USE_FOR_MMU(...)
409#endif
410
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200411#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100412#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000413/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000414# undef CONFIG_FEATURE_SH_STANDALONE
415# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100417# undef IF_NOT_FEATURE_SH_STANDALONE
418# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000419# define IF_FEATURE_SH_STANDALONE(...)
420# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000421#endif
422
Denis Vlasenko05743d72008-02-10 12:10:08 +0000423#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000424# undef ENABLE_FEATURE_EDITING
425# define ENABLE_FEATURE_EDITING 0
426# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
427# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200428# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
429# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000430#endif
431
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000432/* Do we support ANY keywords? */
433#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000434# define HAS_KEYWORDS 1
435# define IF_HAS_KEYWORDS(...) __VA_ARGS__
436# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000437#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000438# define HAS_KEYWORDS 0
439# define IF_HAS_KEYWORDS(...)
440# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000441#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000442
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000443/* If you comment out one of these below, it will be #defined later
444 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200445#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000446/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200447#define debug_printf_parse(...) do {} while (0)
448#define debug_printf_heredoc(...) do {} while (0)
449#define debug_print_tree(a, b) do {} while (0)
450#define debug_printf_exec(...) do {} while (0)
451#define debug_printf_env(...) do {} while (0)
452#define debug_printf_jobs(...) do {} while (0)
453#define debug_printf_expand(...) do {} while (0)
454#define debug_printf_varexp(...) do {} while (0)
455#define debug_printf_glob(...) do {} while (0)
456#define debug_printf_redir(...) do {} while (0)
457#define debug_printf_list(...) do {} while (0)
458#define debug_printf_subst(...) do {} while (0)
459#define debug_printf_prompt(...) do {} while (0)
460#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000461
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000462#define ERR_PTR ((void*)(long)1)
463
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100464#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000465
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200466#define _SPECIAL_VARS_STR "_*@$!?#"
467#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
468#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100469#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200470/* Support / and // replace ops */
471/* Note that // is stored as \ in "encoded" string representation */
472# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
473# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
474# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
475#else
476# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
477# define VAR_SUBST_OPS "%#:-=+?"
478# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
479#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200480
Denys Vlasenko932b9972018-01-11 12:39:48 +0100481#define SPECIAL_VAR_SYMBOL_STR "\3"
482#define SPECIAL_VAR_SYMBOL 3
483/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
484#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000485
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200486struct variable;
487
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000488static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
489
490/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000491 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000492 */
493#if !BB_MMU
494typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200495 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000496 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000497 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000498} nommu_save_t;
499#endif
500
Denys Vlasenko9b782552010-09-08 13:33:26 +0200501enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000502 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000503#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000504 RES_IF ,
505 RES_THEN ,
506 RES_ELIF ,
507 RES_ELSE ,
508 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000509#endif
510#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000511 RES_FOR ,
512 RES_WHILE ,
513 RES_UNTIL ,
514 RES_DO ,
515 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000516#endif
517#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000518 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000519#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000520#if ENABLE_HUSH_CASE
521 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200522 /* three pseudo-keywords support contrived "case" syntax: */
523 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
524 RES_MATCH , /* "word)" */
525 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000526 RES_ESAC ,
527#endif
528 RES_XXXX ,
529 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200530};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000531
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000532typedef struct o_string {
533 char *data;
534 int length; /* position where data is appended */
535 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200536 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000537 /* At least some part of the string was inside '' or "",
538 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200539 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000540 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200541 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000542} o_string;
543enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200544 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
545 EXP_FLAG_GLOB = 0x2,
546 /* Protect newly added chars against globbing
547 * by prepending \ to *, ?, [, \ */
548 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
549};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000550/* Used for initialization: o_string foo = NULL_O_STRING; */
551#define NULL_O_STRING { NULL }
552
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200553#ifndef debug_printf_parse
554static const char *const assignment_flag[] = {
555 "MAYBE_ASSIGNMENT",
556 "DEFINITELY_ASSIGNMENT",
557 "NOT_ASSIGNMENT",
558 "WORD_IS_KEYWORD",
559};
560#endif
561
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200562/* We almost can use standard FILE api, but we need an ability to move
563 * its fd when redirects coincide with it. No api exists for that
564 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
565 * HFILE is our internal alternative. Only supports reading.
566 * Since we now can, we incorporate linked list of all opened HFILEs
567 * into the struct (used to be a separate mini-list).
568 */
569typedef struct HFILE {
570 char *cur;
571 char *end;
572 struct HFILE *next_hfile;
573 int is_stdin;
574 int fd;
575 char buf[1024];
576} HFILE;
577
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000578typedef struct in_str {
579 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200580 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200581 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200582 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000583} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000584
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200585/* The descrip member of this structure is only used to make
586 * debugging output pretty */
587static const struct {
588 int mode;
589 signed char default_fd;
590 char descrip[3];
591} redir_table[] = {
592 { O_RDONLY, 0, "<" },
593 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
594 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
595 { O_CREAT|O_RDWR, 1, "<>" },
596 { O_RDONLY, 0, "<<" },
597/* Should not be needed. Bogus default_fd helps in debugging */
598/* { O_RDONLY, 77, "<<" }, */
599};
600
Eric Andersen25f27032001-04-26 23:22:31 +0000601struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000602 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000603 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000604 int rd_fd; /* fd to redirect */
605 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
606 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000607 smallint rd_type; /* (enum redir_type) */
608 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000609 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200610 * bit 0: do we need to trim leading tabs?
611 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000612 */
Eric Andersen25f27032001-04-26 23:22:31 +0000613};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000614typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200615 REDIRECT_INPUT = 0,
616 REDIRECT_OVERWRITE = 1,
617 REDIRECT_APPEND = 2,
618 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000619 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200620 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000621
622 REDIRFD_CLOSE = -3,
623 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000624 REDIRFD_TO_FILE = -1,
625 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000626
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000627 HEREDOC_SKIPTABS = 1,
628 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000629} redir_type;
630
Eric Andersen25f27032001-04-26 23:22:31 +0000631
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000632struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000633 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200634 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100635#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100636 unsigned lineno;
637#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200638 smallint cmd_type; /* CMD_xxx */
639#define CMD_NORMAL 0
640#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200641#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
642/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
643 * "export v=t*"
644 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200645# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000646#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200647#if ENABLE_HUSH_FUNCTIONS
648# define CMD_FUNCDEF 3
649#endif
650
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100651 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200652 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
653 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000654#if !BB_MMU
655 char *group_as_string;
656#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000657#if ENABLE_HUSH_FUNCTIONS
658 struct function *child_func;
659/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200660 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000661 * When we execute "f1() {a;}" cmd, we create new function and clear
662 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200663 * When we execute "f1() {b;}", we notice that f1 exists,
664 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000665 * we put those fields back into cmd->xxx
666 * (struct function has ->parent_cmd ptr to facilitate that).
667 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
668 * Without this trick, loop would execute a;b;b;b;...
669 * instead of correct sequence a;b;a;b;...
670 * When command is freed, it severs the link
671 * (sets ->child_func->parent_cmd to NULL).
672 */
673#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000674 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000675/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
676 * and on execution these are substituted with their values.
677 * Substitution can make _several_ words out of one argv[n]!
678 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000679 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000680 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000681 struct redir_struct *redirects; /* I/O redirections */
682};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000683/* Is there anything in this command at all? */
684#define IS_NULL_CMD(cmd) \
685 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
686
Eric Andersen25f27032001-04-26 23:22:31 +0000687struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000688 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000689 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000690 int alive_cmds; /* number of commands running (not exited) */
691 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000692#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100693 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000694 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000695 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000696#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000697 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000698 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000699 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
700 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000701};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000702typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100703 PIPE_SEQ = 0,
704 PIPE_AND = 1,
705 PIPE_OR = 2,
706 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000707} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000708/* Is there anything in this pipe at all? */
709#define IS_NULL_PIPE(pi) \
710 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000711
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000712/* This holds pointers to the various results of parsing */
713struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000714 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000715 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000716 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000717 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000718 /* last command in pipe (being constructed right now) */
719 struct command *command;
720 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000721 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200722 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000723#if !BB_MMU
724 o_string as_string;
725#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200726 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000727#if HAS_KEYWORDS
728 smallint ctx_res_w;
729 smallint ctx_inverted; /* "! cmd | cmd" */
730#if ENABLE_HUSH_CASE
731 smallint ctx_dsemicolon; /* ";;" seen */
732#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000733 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
734 int old_flag;
735 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000736 * example: "if pipe1; pipe2; then pipe3; fi"
737 * when we see "if" or "then", we malloc and copy current context,
738 * and make ->stack point to it. then we parse pipeN.
739 * when closing "then" / fi" / whatever is found,
740 * we move list_head into ->stack->command->group,
741 * copy ->stack into current context, and delete ->stack.
742 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000743 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000744 struct parse_context *stack;
745#endif
746};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200747enum {
748 MAYBE_ASSIGNMENT = 0,
749 DEFINITELY_ASSIGNMENT = 1,
750 NOT_ASSIGNMENT = 2,
751 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
752 WORD_IS_KEYWORD = 3,
753};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000754
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000755/* On program start, environ points to initial environment.
756 * putenv adds new pointers into it, unsetenv removes them.
757 * Neither of these (de)allocates the strings.
758 * setenv allocates new strings in malloc space and does putenv,
759 * and thus setenv is unusable (leaky) for shell's purposes */
760#define setenv(...) setenv_is_leaky_dont_use()
761struct variable {
762 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000763 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000764 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200765 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000766 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000767 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000768};
769
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000770enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000771 BC_BREAK = 1,
772 BC_CONTINUE = 2,
773};
774
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000775#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000776struct function {
777 struct function *next;
778 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000779 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000780 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200781# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000782 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200783# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000784};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000785#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000786
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000787
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100788/* set -/+o OPT support. (TODO: make it optional)
789 * bash supports the following opts:
790 * allexport off
791 * braceexpand on
792 * emacs on
793 * errexit off
794 * errtrace off
795 * functrace off
796 * hashall on
797 * histexpand off
798 * history on
799 * ignoreeof off
800 * interactive-comments on
801 * keyword off
802 * monitor on
803 * noclobber off
804 * noexec off
805 * noglob off
806 * nolog off
807 * notify off
808 * nounset off
809 * onecmd off
810 * physical off
811 * pipefail off
812 * posix off
813 * privileged off
814 * verbose off
815 * vi off
816 * xtrace off
817 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800818static const char o_opt_strings[] ALIGN1 =
819 "pipefail\0"
820 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200821 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800822#if ENABLE_HUSH_MODE_X
823 "xtrace\0"
824#endif
825 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100826enum {
827 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800828 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200829 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800830#if ENABLE_HUSH_MODE_X
831 OPT_O_XTRACE,
832#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100833 NUM_OPT_O
834};
835
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000836/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000837/* Sorted roughly by size (smaller offsets == smaller code) */
838struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000839 /* interactive_fd != 0 means we are an interactive shell.
840 * If we are, then saved_tty_pgrp can also be != 0, meaning
841 * that controlling tty is available. With saved_tty_pgrp == 0,
842 * job control still works, but terminal signals
843 * (^C, ^Z, ^Y, ^\) won't work at all, and background
844 * process groups can only be created with "cmd &".
845 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
846 * to give tty to the foreground process group,
847 * and will take it back when the group is stopped (^Z)
848 * or killed (^C).
849 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850#if ENABLE_HUSH_INTERACTIVE
851 /* 'interactive_fd' is a fd# open to ctty, if we have one
852 * _AND_ if we decided to act interactively */
853 int interactive_fd;
854 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200855 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000856# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000857#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000858# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000859#endif
860#if ENABLE_FEATURE_EDITING
861 line_input_t *line_input_state;
862#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000863 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200864 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000865 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200866#if ENABLE_HUSH_RANDOM_SUPPORT
867 random_t random_gen;
868#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000869#if ENABLE_HUSH_JOB
870 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100871 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000872 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000873 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400874# define G_saved_tty_pgrp (G.saved_tty_pgrp)
875#else
876# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000877#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200878 /* How deeply are we in context where "set -e" is ignored */
879 int errexit_depth;
880 /* "set -e" rules (do we follow them correctly?):
881 * Exit if pipe, list, or compound command exits with a non-zero status.
882 * Shell does not exit if failed command is part of condition in
883 * if/while, part of && or || list except the last command, any command
884 * in a pipe but the last, or if the command's return value is being
885 * inverted with !. If a compound command other than a subshell returns a
886 * non-zero status because a command failed while -e was being ignored, the
887 * shell does not exit. A trap on ERR, if set, is executed before the shell
888 * exits [ERR is a bashism].
889 *
890 * If a compound command or function executes in a context where -e is
891 * ignored, none of the commands executed within are affected by the -e
892 * setting. If a compound command or function sets -e while executing in a
893 * context where -e is ignored, that setting does not have any effect until
894 * the compound command or the command containing the function call completes.
895 */
896
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100897 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100898#if ENABLE_HUSH_MODE_X
899# define G_x_mode (G.o_opt[OPT_O_XTRACE])
900#else
901# define G_x_mode 0
902#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200903#if ENABLE_HUSH_INTERACTIVE
904 smallint promptmode; /* 0: PS1, 1: PS2 */
905#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000906 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000907#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000908 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000909#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000910#if ENABLE_HUSH_FUNCTIONS
911 /* 0: outside of a function (or sourced file)
912 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000913 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000914 */
915 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200916# define G_flag_return_in_progress (G.flag_return_in_progress)
917#else
918# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000919#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000920 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200921 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000922 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200923 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200924 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100925#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000926 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000927 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100928# define G_global_args_malloced (G.global_args_malloced)
929#else
930# define G_global_args_malloced 0
931#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000932 /* how many non-NULL argv's we have. NB: $# + 1 */
933 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000934 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000935#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000936 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000937#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000938#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000939 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000940 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000941#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200942#if ENABLE_HUSH_GETOPTS
943 unsigned getopt_count;
944#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000945 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200946 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000947 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200948 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200949 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200950 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200951 unsigned var_nest_level;
952#if ENABLE_HUSH_FUNCTIONS
953# if ENABLE_HUSH_LOCAL
954 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200955# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200956 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000957#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000958 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200959#if ENABLE_HUSH_FAST
960 unsigned count_SIGCHLD;
961 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200962 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200963#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100964#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100965 unsigned lineno;
966 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100967#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200968 HFILE *HFILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200969 /* Which signals have non-DFL handler (even with no traps set)?
970 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200971 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200972 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200973 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200974 * Other than these two times, never modified.
975 */
976 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200977#if ENABLE_HUSH_JOB
978 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100979# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200980#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200981# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200982#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100983#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000984 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100985# define G_traps G.traps
986#else
987# define G_traps ((char**)NULL)
988#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200989 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100990#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000991 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100992#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +0200993#if ENABLE_HUSH_MODE_X
994 unsigned x_mode_depth;
995 /* "set -x" output should not be redirectable with subsequent 2>FILE.
996 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
997 * for all subsequent output.
998 */
999 int x_mode_fd;
1000 o_string x_mode_buf;
1001#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001002#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001003 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001004#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001005 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +02001006#if ENABLE_FEATURE_EDITING
1007 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1008#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001009};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001010#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001011/* Not #defining name to G.name - this quickly gets unwieldy
1012 * (too many defines). Also, I actually prefer to see when a variable
1013 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001014#define INIT_G() do { \
1015 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001016 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1017 sigfillset(&G.sa.sa_mask); \
1018 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001019} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001020
1021
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001022/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001023static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001024#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001025static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001026#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001027static int builtin_eval(char **argv) FAST_FUNC;
1028static int builtin_exec(char **argv) FAST_FUNC;
1029static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001030#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001031static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001032#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001033#if ENABLE_HUSH_READONLY
1034static int builtin_readonly(char **argv) FAST_FUNC;
1035#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001036#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_fg_bg(char **argv) FAST_FUNC;
1038static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001039#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001040#if ENABLE_HUSH_GETOPTS
1041static int builtin_getopts(char **argv) FAST_FUNC;
1042#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001043#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001044static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001045#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001046#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001047static int builtin_history(char **argv) FAST_FUNC;
1048#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001049#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001050static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001051#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001052#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001053static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001054#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001055#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001056static int builtin_printf(char **argv) FAST_FUNC;
1057#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001058static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001059#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001060static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001061#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001062#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001063static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001064#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001065static int builtin_shift(char **argv) FAST_FUNC;
1066static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001067#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001068static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001069#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001070#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001071static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001072#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001073#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001074static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001075#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001076#if ENABLE_HUSH_TIMES
1077static int builtin_times(char **argv) FAST_FUNC;
1078#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001079static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001080#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001081static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001082#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001083#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001084static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001085#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001086#if ENABLE_HUSH_KILL
1087static int builtin_kill(char **argv) FAST_FUNC;
1088#endif
1089#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001090static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001091#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001092#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001093static int builtin_break(char **argv) FAST_FUNC;
1094static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001095#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001096#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001097static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001098#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001099
1100/* Table of built-in functions. They can be forked or not, depending on
1101 * context: within pipes, they fork. As simple commands, they do not.
1102 * When used in non-forking context, they can change global variables
1103 * in the parent shell process. If forked, of course they cannot.
1104 * For example, 'unset foo | whatever' will parse and run, but foo will
1105 * still be set at the end. */
1106struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001107 const char *b_cmd;
1108 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001109#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001110 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001111# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001112#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001113# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001114#endif
1115};
1116
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001117static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001118 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001119 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001120#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001121 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001122#endif
1123#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001124 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001125#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001126 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001127#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001128 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001129#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001130 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1131 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001132 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001133#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001134 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001135#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001136#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001137 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001138#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001139#if ENABLE_HUSH_GETOPTS
1140 BLTIN("getopts" , builtin_getopts , NULL),
1141#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001142#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001143 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001144#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001145#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001146 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001147#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001148#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001149 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001150#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001151#if ENABLE_HUSH_KILL
1152 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1153#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001154#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001156#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001157#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001158 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001159#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001160#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001161 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001162#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001163#if ENABLE_HUSH_READONLY
1164 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1165#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001166#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001167 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001168#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001169#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001170 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001171#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001172 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001173#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001174 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001175#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001176#if ENABLE_HUSH_TIMES
1177 BLTIN("times" , builtin_times , NULL),
1178#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001179#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001180 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001181#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001182 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001183#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001184 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001185#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001186#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001187 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001188#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001189#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001190 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001191#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001192#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001193 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001194#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001195#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001196 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001197#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001198};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001199/* These builtins won't be used if we are on NOMMU and need to re-exec
1200 * (it's cheaper to run an external program in this case):
1201 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001202static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001203#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001204 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001205#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001206#if BASH_TEST2
1207 BLTIN("[[" , builtin_test , NULL),
1208#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001209#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001210 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001211#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001212#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001213 BLTIN("printf" , builtin_printf , NULL),
1214#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001215 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001216#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001217 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001218#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001219};
1220
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001221
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001222/* Debug printouts.
1223 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001224#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001225/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001226# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001227# define debug_enter() (G.debug_indent++)
1228# define debug_leave() (G.debug_indent--)
1229#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001230# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001231# define debug_enter() ((void)0)
1232# define debug_leave() ((void)0)
1233#endif
1234
1235#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001236# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001237#endif
1238
1239#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001240# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001241#endif
1242
Denys Vlasenko3675c372018-07-23 16:31:21 +02001243#ifndef debug_printf_heredoc
1244# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1245#endif
1246
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001247#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001248#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001249#endif
1250
1251#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001252# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001253#endif
1254
1255#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001256# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001257# define DEBUG_JOBS 1
1258#else
1259# define DEBUG_JOBS 0
1260#endif
1261
1262#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001263# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001264# define DEBUG_EXPAND 1
1265#else
1266# define DEBUG_EXPAND 0
1267#endif
1268
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001269#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001270# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001271#endif
1272
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001273#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001274# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001275# define DEBUG_GLOB 1
1276#else
1277# define DEBUG_GLOB 0
1278#endif
1279
Denys Vlasenko2db74612017-07-07 22:07:28 +02001280#ifndef debug_printf_redir
1281# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1282#endif
1283
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001284#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001285# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001286#endif
1287
1288#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001289# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001290#endif
1291
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001292#ifndef debug_printf_prompt
1293# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1294#endif
1295
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001296#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001297# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001298# define DEBUG_CLEAN 1
1299#else
1300# define DEBUG_CLEAN 0
1301#endif
1302
1303#if DEBUG_EXPAND
1304static void debug_print_strings(const char *prefix, char **vv)
1305{
1306 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001307 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001308 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001309 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001310}
1311#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001312# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001313#endif
1314
1315
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001316/* Leak hunting. Use hush_leaktool.sh for post-processing.
1317 */
1318#if LEAK_HUNTING
1319static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001320{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001321 void *ptr = xmalloc((size + 0xff) & ~0xff);
1322 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1323 return ptr;
1324}
1325static void *xxrealloc(int lineno, void *ptr, size_t size)
1326{
1327 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1328 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1329 return ptr;
1330}
1331static char *xxstrdup(int lineno, const char *str)
1332{
1333 char *ptr = xstrdup(str);
1334 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1335 return ptr;
1336}
1337static void xxfree(void *ptr)
1338{
1339 fdprintf(2, "free %p\n", ptr);
1340 free(ptr);
1341}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001342# define xmalloc(s) xxmalloc(__LINE__, s)
1343# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1344# define xstrdup(s) xxstrdup(__LINE__, s)
1345# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001346#endif
1347
1348
1349/* Syntax and runtime errors. They always abort scripts.
1350 * In interactive use they usually discard unparsed and/or unexecuted commands
1351 * and return to the prompt.
1352 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1353 */
1354#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001355# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001356# define syntax_error(lineno, msg) syntax_error(msg)
1357# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1358# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1359# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1360# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001361#endif
1362
Denys Vlasenko39701202017-08-02 19:44:05 +02001363static void die_if_script(void)
1364{
1365 if (!G_interactive_fd) {
1366 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1367 xfunc_error_retval = G.last_exitcode;
1368 xfunc_die();
1369 }
1370}
1371
1372static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001373{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001374 va_list p;
1375
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001376#if HUSH_DEBUG >= 2
1377 bb_error_msg("hush.c:%u", lineno);
1378#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001379 va_start(p, fmt);
1380 bb_verror_msg(fmt, p, NULL);
1381 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001382 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001383}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001384
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001385static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001386{
1387 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001388 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001389 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001390 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001391 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001392}
1393
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001394static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001395{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001396 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001397 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001398}
1399
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001400static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001401{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001402 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001403//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1404// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001405}
1406
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001407static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001408{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001409 char msg[2] = { ch, '\0' };
1410 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001411}
1412
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001413static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001414{
1415 char msg[2];
1416 msg[0] = ch;
1417 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001418#if HUSH_DEBUG >= 2
1419 bb_error_msg("hush.c:%u", lineno);
1420#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001421 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001422 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001423}
1424
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001425#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001426# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001427# undef syntax_error
1428# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001429# undef syntax_error_unterm_ch
1430# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001431# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001432#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001433# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001434# define syntax_error(msg) syntax_error(__LINE__, msg)
1435# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1436# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1437# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1438# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001439#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001440
Denis Vlasenko552433b2009-04-04 19:29:21 +00001441
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001442#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001443static void cmdedit_update_prompt(void);
1444#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001445# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001446#endif
1447
1448
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001449/* Utility functions
1450 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001451/* Replace each \x with x in place, return ptr past NUL. */
1452static char *unbackslash(char *src)
1453{
Denys Vlasenko71885402009-09-24 01:44:13 +02001454 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001455 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001456 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001457 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001458 if (*src != '\0') {
1459 /* \x -> x */
1460 *dst++ = *src++;
1461 continue;
1462 }
1463 /* else: "\<nul>". Do not delete this backslash.
1464 * Testcase: eval 'echo ok\'
1465 */
1466 *dst++ = '\\';
1467 /* fallthrough */
1468 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001469 if ((*dst++ = *src++) == '\0')
1470 break;
1471 }
1472 return dst;
1473}
1474
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001475static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001476{
1477 int i;
1478 unsigned count1;
1479 unsigned count2;
1480 char **v;
1481
1482 v = strings;
1483 count1 = 0;
1484 if (v) {
1485 while (*v) {
1486 count1++;
1487 v++;
1488 }
1489 }
1490 count2 = 0;
1491 v = add;
1492 while (*v) {
1493 count2++;
1494 v++;
1495 }
1496 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1497 v[count1 + count2] = NULL;
1498 i = count2;
1499 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001500 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001501 return v;
1502}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001503#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001504static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1505{
1506 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1507 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1508 return ptr;
1509}
1510#define add_strings_to_strings(strings, add, need_to_dup) \
1511 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1512#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001513
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001514/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001515static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001516{
1517 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001518 v[0] = add;
1519 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001520 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001521}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001522#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001523static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1524{
1525 char **ptr = add_string_to_strings(strings, add);
1526 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1527 return ptr;
1528}
1529#define add_string_to_strings(strings, add) \
1530 xx_add_string_to_strings(__LINE__, strings, add)
1531#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001532
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001533static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001534{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001535 char **v;
1536
1537 if (!strings)
1538 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001539 v = strings;
1540 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001541 free(*v);
1542 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001543 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001544 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001545}
1546
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001547static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001548{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001549 int newfd;
1550 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001551 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1552 if (newfd >= 0) {
1553 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1554 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1555 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001556 if (errno == EBUSY)
1557 goto repeat;
1558 if (errno == EINTR)
1559 goto repeat;
1560 }
1561 return newfd;
1562}
1563
Denys Vlasenko657e9002017-07-30 23:34:04 +02001564static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001565{
1566 int newfd;
1567 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001568 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001569 if (newfd < 0) {
1570 if (errno == EBUSY)
1571 goto repeat;
1572 if (errno == EINTR)
1573 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001574 /* fd was not open? */
1575 if (errno == EBADF)
1576 return fd;
1577 xfunc_die();
1578 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001579 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1580 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001581 close(fd);
1582 return newfd;
1583}
1584
1585
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001586/* Manipulating HFILEs */
1587static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001588{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001589 HFILE *fp;
1590 int fd;
1591
1592 fd = STDIN_FILENO;
1593 if (name) {
1594 fd = open(name, O_RDONLY | O_CLOEXEC);
1595 if (fd < 0)
1596 return NULL;
1597 if (O_CLOEXEC == 0) /* ancient libc */
1598 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001599 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001600
1601 fp = xmalloc(sizeof(*fp));
1602 fp->is_stdin = (name == NULL);
1603 fp->fd = fd;
1604 fp->cur = fp->end = fp->buf;
1605 fp->next_hfile = G.HFILE_list;
1606 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001607 return fp;
1608}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001609static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001610{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001611 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001612 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001613 HFILE *cur = *pp;
1614 if (cur == fp) {
1615 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001616 break;
1617 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001618 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001619 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001620 if (fp->fd >= 0)
1621 close(fp->fd);
1622 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001623}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001624static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001625{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001626 int n;
1627
1628 if (fp->fd < 0) {
1629 /* Already saw EOF */
1630 return EOF;
1631 }
1632 /* Try to buffer more input */
1633 fp->cur = fp->buf;
1634 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1635 if (n < 0) {
1636 bb_perror_msg("read error");
1637 n = 0;
1638 }
1639 fp->end = fp->buf + n;
1640 if (n == 0) {
1641 /* EOF/error */
1642 close(fp->fd);
1643 fp->fd = -1;
1644 return EOF;
1645 }
1646 return (unsigned char)(*fp->cur++);
1647}
1648/* Inlined for common case of non-empty buffer.
1649 */
1650static ALWAYS_INLINE int hfgetc(HFILE *fp)
1651{
1652 if (fp->cur < fp->end)
1653 return (unsigned char)(*fp->cur++);
1654 /* Buffer empty */
1655 return refill_HFILE_and_getc(fp);
1656}
1657static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1658{
1659 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001660 while (fl) {
1661 if (fd == fl->fd) {
1662 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001663 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001664 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001665 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001666 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001667 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001668 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001669#if ENABLE_HUSH_MODE_X
1670 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1671 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1672 return 1; /* "found and moved" */
1673 }
1674#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001675 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001676}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001677#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001678static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001679{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001680 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001681 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001682 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001683 * It is disastrous if we share memory with a vforked parent.
1684 * I'm not sure we never come here after vfork.
1685 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001686 *
1687 * ">" instead of ">=": we don't close fd#0,
1688 * interactive shell uses hfopen(NULL) as stdin input
1689 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1690 * If we'd close it here, then e.g. interactive "set | sort"
1691 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001692 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001693 if (fl->fd > 0)
1694 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001695 close(fl->fd);
1696 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001697 }
1698}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001699#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001700static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001701{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001702 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001703 while (fl) {
1704 if (fl->fd == fd)
1705 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001706 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001707 }
1708 return 0;
1709}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001710
1711
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001712/* Helpers for setting new $n and restoring them back
1713 */
1714typedef struct save_arg_t {
1715 char *sv_argv0;
1716 char **sv_g_argv;
1717 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001718 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001719} save_arg_t;
1720
1721static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1722{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001723 sv->sv_argv0 = argv[0];
1724 sv->sv_g_argv = G.global_argv;
1725 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001726 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001727
1728 argv[0] = G.global_argv[0]; /* retain $0 */
1729 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001730 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001731
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001732 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001733}
1734
1735static void restore_G_args(save_arg_t *sv, char **argv)
1736{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001737#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001738 if (G.global_args_malloced) {
1739 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001740 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001741 while (*++pp) /* note: does not free $0 */
1742 free(*pp);
1743 free(G.global_argv);
1744 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001745#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001746 argv[0] = sv->sv_argv0;
1747 G.global_argv = sv->sv_g_argv;
1748 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001749 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001750}
1751
1752
Denis Vlasenkod5762932009-03-31 11:22:57 +00001753/* Basic theory of signal handling in shell
1754 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001755 * This does not describe what hush does, rather, it is current understanding
1756 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001757 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1758 *
1759 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1760 * is finished or backgrounded. It is the same in interactive and
1761 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001762 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001763 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001764 * backgrounds (i.e. stops) or kills all members of currently running
1765 * pipe.
1766 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001767 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001768 * or by SIGINT in interactive shell.
1769 *
1770 * Trap handlers will execute even within trap handlers. (right?)
1771 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001772 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1773 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001774 *
1775 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001776 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001777 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001778 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001779 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001780 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001781 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001782 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001783 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001784 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001785 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001786 *
1787 * SIGQUIT: ignore
1788 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001789 * SIGHUP (interactive):
1790 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001791 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001792 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1793 * that all pipe members are stopped. Try this in bash:
1794 * while :; do :; done - ^Z does not background it
1795 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001796 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001797 * of the command line, show prompt. NB: ^C does not send SIGINT
1798 * to interactive shell while shell is waiting for a pipe,
1799 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001800 * Example 1: this waits 5 sec, but does not execute ls:
1801 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1802 * Example 2: this does not wait and does not execute ls:
1803 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1804 * Example 3: this does not wait 5 sec, but executes ls:
1805 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001806 * Example 4: this does not wait and does not execute ls:
1807 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001808 *
1809 * (What happens to signals which are IGN on shell start?)
1810 * (What happens with signal mask on shell start?)
1811 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001812 * Old implementation
1813 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001814 * We use in-kernel pending signal mask to determine which signals were sent.
1815 * We block all signals which we don't want to take action immediately,
1816 * i.e. we block all signals which need to have special handling as described
1817 * above, and all signals which have traps set.
1818 * After each pipe execution, we extract any pending signals via sigtimedwait()
1819 * and act on them.
1820 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001821 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001822 * sigset_t blocked_set: current blocked signal set
1823 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001824 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001825 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001826 * "trap 'cmd' SIGxxx":
1827 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001828 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001829 * unblock signals with special interactive handling
1830 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001831 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001832 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001833 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001834 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001835 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001836 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001837 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001838 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001839 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001840 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001841 * Standard says "When a subshell is entered, traps that are not being ignored
1842 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001843 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001844 *
1845 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001846 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001847 * masked signals are not visible!
1848 *
1849 * New implementation
1850 * ==================
1851 * We record each signal we are interested in by installing signal handler
1852 * for them - a bit like emulating kernel pending signal mask in userspace.
1853 * We are interested in: signals which need to have special handling
1854 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001855 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001856 * After each pipe execution, we extract any pending signals
1857 * and act on them.
1858 *
1859 * unsigned special_sig_mask: a mask of shell-special signals.
1860 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1861 * char *traps[sig] if trap for sig is set (even if it's '').
1862 * sigset_t pending_set: set of sigs we received.
1863 *
1864 * "trap - SIGxxx":
1865 * if sig is in special_sig_mask, set handler back to:
1866 * record_pending_signo, or to IGN if it's a tty stop signal
1867 * if sig is in fatal_sig_mask, set handler back to sigexit.
1868 * else: set handler back to SIG_DFL
1869 * "trap 'cmd' SIGxxx":
1870 * set handler to record_pending_signo.
1871 * "trap '' SIGxxx":
1872 * set handler to SIG_IGN.
1873 * after [v]fork, if we plan to be a shell:
1874 * set signals with special interactive handling to SIG_DFL
1875 * (because child shell is not interactive),
1876 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1877 * after [v]fork, if we plan to exec:
1878 * POSIX says fork clears pending signal mask in child - no need to clear it.
1879 *
1880 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1881 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1882 *
1883 * Note (compat):
1884 * Standard says "When a subshell is entered, traps that are not being ignored
1885 * are set to the default actions". bash interprets it so that traps which
1886 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001887 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001888enum {
1889 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001890 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001891 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001892 | (1 << SIGHUP)
1893 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001894 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001895#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001896 | (1 << SIGTTIN)
1897 | (1 << SIGTTOU)
1898 | (1 << SIGTSTP)
1899#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001900 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001901};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001902
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001903static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001904{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001905 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001906#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001907 if (sig == SIGCHLD) {
1908 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001909//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 +02001910 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001911#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001912}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001913
Denys Vlasenko0806e402011-05-12 23:06:20 +02001914static sighandler_t install_sighandler(int sig, sighandler_t handler)
1915{
1916 struct sigaction old_sa;
1917
1918 /* We could use signal() to install handlers... almost:
1919 * except that we need to mask ALL signals while handlers run.
1920 * I saw signal nesting in strace, race window isn't small.
1921 * SA_RESTART is also needed, but in Linux, signal()
1922 * sets SA_RESTART too.
1923 */
1924 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1925 /* sigfillset(&G.sa.sa_mask); - already done */
1926 /* G.sa.sa_flags = SA_RESTART; - already done */
1927 G.sa.sa_handler = handler;
1928 sigaction(sig, &G.sa, &old_sa);
1929 return old_sa.sa_handler;
1930}
1931
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001932static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001933
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001934static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001935static void restore_ttypgrp_and__exit(void)
1936{
1937 /* xfunc has failed! die die die */
1938 /* no EXIT traps, this is an escape hatch! */
1939 G.exiting = 1;
1940 hush_exit(xfunc_error_retval);
1941}
1942
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001943#if ENABLE_HUSH_JOB
1944
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001945/* Needed only on some libc:
1946 * It was observed that on exit(), fgetc'ed buffered data
1947 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1948 * With the net effect that even after fork(), not vfork(),
1949 * exit() in NOEXECed applet in "sh SCRIPT":
1950 * noexec_applet_here
1951 * echo END_OF_SCRIPT
1952 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1953 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001954 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001955 * and in `cmd` handling.
1956 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1957 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001958static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001959static void fflush_and__exit(void)
1960{
1961 fflush_all();
1962 _exit(xfunc_error_retval);
1963}
1964
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001965/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001966# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001967/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001968# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001969
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001970/* Restores tty foreground process group, and exits.
1971 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001972 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001973 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001974 * We also call it if xfunc is exiting.
1975 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001976static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001977static void sigexit(int sig)
1978{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001979 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001980 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001981 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1982 /* Disable all signals: job control, SIGPIPE, etc.
1983 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1984 */
1985 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001986 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001987 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001988
1989 /* Not a signal, just exit */
1990 if (sig <= 0)
1991 _exit(- sig);
1992
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001993 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001994}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001995#else
1996
Denys Vlasenko8391c482010-05-22 17:50:43 +02001997# define disable_restore_tty_pgrp_on_exit() ((void)0)
1998# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001999
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002000#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002001
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002002static sighandler_t pick_sighandler(unsigned sig)
2003{
2004 sighandler_t handler = SIG_DFL;
2005 if (sig < sizeof(unsigned)*8) {
2006 unsigned sigmask = (1 << sig);
2007
2008#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002009 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002010 if (G_fatal_sig_mask & sigmask)
2011 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002012 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002013#endif
2014 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002015 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002016 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002017 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002018 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002019 * in an endless loop when we try to do some
2020 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002021 */
2022 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2023 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002024 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002025 }
2026 return handler;
2027}
2028
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002029/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002030static void hush_exit(int exitcode)
2031{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002032#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
2033 save_history(G.line_input_state);
2034#endif
2035
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002036 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002037 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002038 char *argv[3];
2039 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002040 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002041 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002042 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002043 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002044 * "trap" will still show it, if executed
2045 * in the handler */
2046 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002047 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002048
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002049#if ENABLE_FEATURE_CLEAN_UP
2050 {
2051 struct variable *cur_var;
2052 if (G.cwd != bb_msg_unknown)
2053 free((char*)G.cwd);
2054 cur_var = G.top_var;
2055 while (cur_var) {
2056 struct variable *tmp = cur_var;
2057 if (!cur_var->max_len)
2058 free(cur_var->varstr);
2059 cur_var = cur_var->next;
2060 free(tmp);
2061 }
2062 }
2063#endif
2064
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002065 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002066#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002067 sigexit(- (exitcode & 0xff));
2068#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002069 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002070#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002071}
2072
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002073
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002074//TODO: return a mask of ALL handled sigs?
2075static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002076{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002077 int last_sig = 0;
2078
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002079 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002080 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002081
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002082 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002083 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002084 sig = 0;
2085 do {
2086 sig++;
2087 if (sigismember(&G.pending_set, sig)) {
2088 sigdelset(&G.pending_set, sig);
2089 goto got_sig;
2090 }
2091 } while (sig < NSIG);
2092 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002093 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002094 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002095 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002096 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002097 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002098 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002099 char *argv[3];
2100 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002101 argv[1] = xstrdup(G_traps[sig]);
2102 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002103 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002104 save_rcode = G.last_exitcode;
2105 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002106 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002107//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002108 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002109 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002110 } /* else: "" trap, ignoring signal */
2111 continue;
2112 }
2113 /* not a trap: special action */
2114 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002115 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002116 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002117 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002118 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002119 break;
2120#if ENABLE_HUSH_JOB
2121 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002122//TODO: why are we doing this? ash and dash don't do this,
2123//they have no handler for SIGHUP at all,
2124//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002125 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002126 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002127 /* bash is observed to signal whole process groups,
2128 * not individual processes */
2129 for (job = G.job_list; job; job = job->next) {
2130 if (job->pgrp <= 0)
2131 continue;
2132 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2133 if (kill(- job->pgrp, SIGHUP) == 0)
2134 kill(- job->pgrp, SIGCONT);
2135 }
2136 sigexit(SIGHUP);
2137 }
2138#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002139#if ENABLE_HUSH_FAST
2140 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002141 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002142 G.count_SIGCHLD++;
2143//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2144 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002145 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002146 * This simplifies wait builtin a bit.
2147 */
2148 break;
2149#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002150 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002151 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002152 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002153 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002154 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002155 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002156 * in interactive shell, because TERM is ignored.
2157 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002158 break;
2159 }
2160 }
2161 return last_sig;
2162}
2163
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002164
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002165static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002166{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002167 if (force || G.cwd == NULL) {
2168 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2169 * we must not try to free(bb_msg_unknown) */
2170 if (G.cwd == bb_msg_unknown)
2171 G.cwd = NULL;
2172 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2173 if (!G.cwd)
2174 G.cwd = bb_msg_unknown;
2175 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002176 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002177}
2178
Denis Vlasenko83506862007-11-23 13:11:42 +00002179
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002180/*
2181 * Shell and environment variable support
2182 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002183static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002184{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002185 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002186 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002187
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002188 pp = &G.top_var;
2189 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002190 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002191 return pp;
2192 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002193 }
2194 return NULL;
2195}
2196
Denys Vlasenko03dad222010-01-12 23:29:57 +01002197static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002198{
Denys Vlasenko29082232010-07-16 13:52:32 +02002199 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002200 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002201
2202 if (G.expanded_assignments) {
2203 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002204 while (*cpp) {
2205 char *cp = *cpp;
2206 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2207 return cp + len + 1;
2208 cpp++;
2209 }
2210 }
2211
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002212 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002213 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002214 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002215
Denys Vlasenkodea47882009-10-09 15:40:49 +02002216 if (strcmp(name, "PPID") == 0)
2217 return utoa(G.root_ppid);
2218 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002219#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002220 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002221 return utoa(next_random(&G.random_gen));
2222#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002223 return NULL;
2224}
2225
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002226static void handle_changed_special_names(const char *name, unsigned name_len)
2227{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002228 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2229 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2230 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002231 cmdedit_update_prompt();
2232 return;
2233 }
2234
2235 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2236 && name_len == 6
2237 ) {
2238#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002239 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002240 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002241 return;
2242 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002243#endif
2244#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002245 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002246 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002247 return;
2248 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002249#endif
2250 }
2251}
2252
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002253/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002254 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002255 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002256#define SETFLAG_EXPORT (1 << 0)
2257#define SETFLAG_UNEXPORT (1 << 1)
2258#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002259#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002260static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002261{
Denys Vlasenko61407802018-04-04 21:14:28 +02002262 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002263 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002264 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002265 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002267 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002268
Denis Vlasenko950bd722009-04-21 11:23:56 +00002269 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002270 if (HUSH_DEBUG && !eq_sign)
2271 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002272
Denis Vlasenko950bd722009-04-21 11:23:56 +00002273 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002274 cur_pp = &G.top_var;
2275 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002276 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002277 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002278 continue;
2279 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002280
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002281 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002282 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002283 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002284 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002285//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2286//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002287 return -1;
2288 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002289 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002290 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2291 *eq_sign = '\0';
2292 unsetenv(str);
2293 *eq_sign = '=';
2294 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002295 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002296 /* bash 3.2.33(1) and exported vars:
2297 * # export z=z
2298 * # f() { local z=a; env | grep ^z; }
2299 * # f
2300 * z=a
2301 * # env | grep ^z
2302 * z=z
2303 */
2304 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002305 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002306 /* New variable is local ("local VAR=VAL" or
2307 * "VAR=VAL cmd")
2308 * and existing one is global, or local
2309 * on a lower level that new one.
2310 * Remove it from global variable list:
2311 */
2312 *cur_pp = cur->next;
2313 if (G.shadowed_vars_pp) {
2314 /* Save in "shadowed" list */
2315 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2316 cur->flg_export ? "exported " : "",
2317 cur->varstr, cur->var_nest_level, str, local_lvl
2318 );
2319 cur->next = *G.shadowed_vars_pp;
2320 *G.shadowed_vars_pp = cur;
2321 } else {
2322 /* Came from pseudo_exec_argv(), no need to save: delete it */
2323 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2324 cur->flg_export ? "exported " : "",
2325 cur->varstr, cur->var_nest_level, str, local_lvl
2326 );
2327 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2328 free_me = cur->varstr; /* then free it later */
2329 free(cur);
2330 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002331 break;
2332 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002333
Denis Vlasenko950bd722009-04-21 11:23:56 +00002334 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002335 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002336 free_and_exp:
2337 free(str);
2338 goto exp;
2339 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002340
2341 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002342 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002343 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002344 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002345 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002346 strcpy(cur->varstr, str);
2347 goto free_and_exp;
2348 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002349 /* Can't reuse */
2350 cur->max_len = 0;
2351 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002352 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002353 /* max_len == 0 signifies "malloced" var, which we can
2354 * (and have to) free. But we can't free(cur->varstr) here:
2355 * if cur->flg_export is 1, it is in the environment.
2356 * We should either unsetenv+free, or wait until putenv,
2357 * then putenv(new)+free(old).
2358 */
2359 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002360 goto set_str_and_exp;
2361 }
2362
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002363 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002364 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002365 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002366 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002367 cur->next = *cur_pp;
2368 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002369
2370 set_str_and_exp:
2371 cur->varstr = str;
2372 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002373#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002374 if (flags & SETFLAG_MAKE_RO) {
2375 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002376 }
2377#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002378 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002379 cur->flg_export = 1;
2380 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002381 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002382 cur->flg_export = 0;
2383 /* unsetenv was already done */
2384 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002385 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002386 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002387 i = putenv(cur->varstr);
2388 /* only now we can free old exported malloced string */
2389 free(free_me);
2390 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002391 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002392 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002393 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002394
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002395 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002396
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002397 return 0;
2398}
2399
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002400static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2401{
2402 char *var = xasprintf("%s=%s", name, val);
2403 set_local_var(var, /*flag:*/ 0);
2404}
2405
Denys Vlasenko6db47842009-09-05 20:15:17 +02002406/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002407static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002408{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002409 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002410}
2411
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002412#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002413static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002414{
2415 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002416 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002417
Denys Vlasenko61407802018-04-04 21:14:28 +02002418 cur_pp = &G.top_var;
2419 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002420 if (strncmp(cur->varstr, name, name_len) == 0
2421 && cur->varstr[name_len] == '='
2422 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002423 if (cur->flg_read_only) {
2424 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002425 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002426 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002427
Denys Vlasenko61407802018-04-04 21:14:28 +02002428 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002429 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2430 bb_unsetenv(cur->varstr);
2431 if (!cur->max_len)
2432 free(cur->varstr);
2433 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002434
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002435 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002436 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002437 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002438 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002439
2440 /* Handle "unset PS1" et al even if did not find the variable to unset */
2441 handle_changed_special_names(name, name_len);
2442
Mike Frysingerd690f682009-03-30 06:50:54 +00002443 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002444}
2445
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002446static int unset_local_var(const char *name)
2447{
2448 return unset_local_var_len(name, strlen(name));
2449}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002450#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002451
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002452
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002453/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002454 * Helpers for "var1=val1 var2=val2 cmd" feature
2455 */
2456static void add_vars(struct variable *var)
2457{
2458 struct variable *next;
2459
2460 while (var) {
2461 next = var->next;
2462 var->next = G.top_var;
2463 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002464 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002465 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002466 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002467 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002468 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002469 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002470 var = next;
2471 }
2472}
2473
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002474/* We put strings[i] into variable table and possibly putenv them.
2475 * If variable is read only, we can free the strings[i]
2476 * which attempts to overwrite it.
2477 * The strings[] vector itself is freed.
2478 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002479static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002480{
2481 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002482
2483 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002484 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002485
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002486 s = strings;
2487 while (*s) {
2488 struct variable *var_p;
2489 struct variable **var_pp;
2490 char *eq;
2491
2492 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002493 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002494 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002495 var_pp = get_ptr_to_local_var(*s, eq - *s);
2496 if (var_pp) {
2497 var_p = *var_pp;
2498 if (var_p->flg_read_only) {
2499 char **p;
2500 bb_error_msg("%s: readonly variable", *s);
2501 /*
2502 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2503 * If VAR is readonly, leaving it in the list
2504 * after asssignment error (msg above)
2505 * causes doubled error message later, on unset.
2506 */
2507 debug_printf_env("removing/freeing '%s' element\n", *s);
2508 free(*s);
2509 p = s;
2510 do { *p = p[1]; p++; } while (*p);
2511 goto next;
2512 }
2513 /* below, set_local_var() with nest level will
2514 * "shadow" (remove) this variable from
2515 * global linked list.
2516 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002517 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002518 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2519 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002520 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002521 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002522 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002523 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002524}
2525
2526
2527/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002528 * Unicode helper
2529 */
2530static void reinit_unicode_for_hush(void)
2531{
2532 /* Unicode support should be activated even if LANG is set
2533 * _during_ shell execution, not only if it was set when
2534 * shell was started. Therefore, re-check LANG every time:
2535 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002536 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2537 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002538 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002539 const char *s = get_local_var_value("LC_ALL");
2540 if (!s) s = get_local_var_value("LC_CTYPE");
2541 if (!s) s = get_local_var_value("LANG");
2542 reinit_unicode(s);
2543 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002544}
2545
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002546/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002547 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002548 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002549
2550#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002551/* To test correct lineedit/interactive behavior, type from command line:
2552 * echo $P\
2553 * \
2554 * AT\
2555 * H\
2556 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002557 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002558 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002559# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002560static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002561{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002562 G.PS1 = get_local_var_value("PS1");
2563 if (G.PS1 == NULL)
2564 G.PS1 = "";
2565 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002566 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002567 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002568}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002569# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002570static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002571{
2572 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002573
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002574 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002575
2576 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2577 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002578 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002579 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2580 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002581 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002582 /* bash uses $PWD value, even if it is set by user.
2583 * It uses current dir only if PWD is unset.
2584 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002585 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002586 }
2587 prompt_str = G.PS1;
2588 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002589 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002590 return prompt_str;
2591}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002592static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002593{
2594 int r;
2595 const char *prompt_str;
2596
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002597 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002598# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002599 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002600 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002601 if (G.flag_SIGINT) {
2602 /* There was ^C'ed, make it look prettier: */
2603 bb_putchar('\n');
2604 G.flag_SIGINT = 0;
2605 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002606 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002607 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002608 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002609 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002610 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002611 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002612 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002613 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002614 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002615 if (r != 0 && !G.flag_SIGINT)
2616 break;
2617 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002618 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2619 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002620 G.last_exitcode = 128 + SIGINT;
2621 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002622 if (r < 0) {
2623 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002624 i->p = NULL;
2625 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002626 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002627 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002628 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002629 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002630# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002631 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002632 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002633 if (i->last_char == '\0' || i->last_char == '\n') {
2634 /* Why check_and_run_traps here? Try this interactively:
2635 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2636 * $ <[enter], repeatedly...>
2637 * Without check_and_run_traps, handler never runs.
2638 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002639 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002640 fputs(prompt_str, stdout);
2641 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002642 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002643//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002644 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002645 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2646 * no ^C masking happens during fgetc, no special code for ^C:
2647 * it generates SIGINT as usual.
2648 */
2649 check_and_run_traps();
2650 if (G.flag_SIGINT)
2651 G.last_exitcode = 128 + SIGINT;
2652 if (r != '\0')
2653 break;
2654 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002655 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002656# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002657}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002658/* This is the magic location that prints prompts
2659 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002660static int fgetc_interactive(struct in_str *i)
2661{
2662 int ch;
2663 /* If it's interactive stdin, get new line. */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002664 if (G_interactive_fd && i->file->is_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002665 /* Returns first char (or EOF), the rest is in i->p[] */
2666 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002667 G.promptmode = 1; /* PS2 */
2668 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002669 } else {
2670 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002671 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002672 }
2673 return ch;
2674}
2675#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002676static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002677{
2678 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002679 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002680 return ch;
2681}
2682#endif /* INTERACTIVE */
2683
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002684static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002685{
2686 int ch;
2687
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002688 if (!i->file) {
2689 /* string-based in_str */
2690 ch = (unsigned char)*i->p;
2691 if (ch != '\0') {
2692 i->p++;
2693 i->last_char = ch;
2694 return ch;
2695 }
2696 return EOF;
2697 }
2698
2699 /* FILE-based in_str */
2700
Denys Vlasenko4074d492016-09-30 01:49:53 +02002701#if ENABLE_FEATURE_EDITING
2702 /* This can be stdin, check line editing char[] buffer */
2703 if (i->p && *i->p != '\0') {
2704 ch = (unsigned char)*i->p++;
2705 goto out;
2706 }
2707#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002708 /* peek_buf[] is an int array, not char. Can contain EOF. */
2709 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002710 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002711 int ch2 = i->peek_buf[1];
2712 i->peek_buf[0] = ch2;
2713 if (ch2 == 0) /* very likely, avoid redundant write */
2714 goto out;
2715 i->peek_buf[1] = 0;
2716 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002717 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002718
Denys Vlasenko4074d492016-09-30 01:49:53 +02002719 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002720 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002721 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002722 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002723#if ENABLE_HUSH_LINENO_VAR
2724 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002725 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002726 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2727 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002728#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002729 return ch;
2730}
2731
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002732static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002733{
2734 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002735
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002736 if (!i->file) {
2737 /* string-based in_str */
2738 /* Doesn't report EOF on NUL. None of the callers care. */
2739 return (unsigned char)*i->p;
2740 }
2741
2742 /* FILE-based in_str */
2743
Denys Vlasenko4074d492016-09-30 01:49:53 +02002744#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002745 /* This can be stdin, check line editing char[] buffer */
2746 if (i->p && *i->p != '\0')
2747 return (unsigned char)*i->p;
2748#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002749 /* peek_buf[] is an int array, not char. Can contain EOF. */
2750 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002751 if (ch != 0)
2752 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002753
Denys Vlasenko4074d492016-09-30 01:49:53 +02002754 /* Need to get a new char */
2755 ch = fgetc_interactive(i);
2756 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2757
2758 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2759#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2760 if (i->p) {
2761 i->p -= 1;
2762 return ch;
2763 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002764#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002765 i->peek_buf[0] = ch;
2766 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002767 return ch;
2768}
2769
Denys Vlasenko4074d492016-09-30 01:49:53 +02002770/* Only ever called if i_peek() was called, and did not return EOF.
2771 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2772 * not end-of-line. Therefore we never need to read a new editing line here.
2773 */
2774static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002775{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002776 int ch;
2777
2778 /* There are two cases when i->p[] buffer exists.
2779 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002780 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002781 * In both cases, we know that i->p[0] exists and not NUL, and
2782 * the peek2 result is in i->p[1].
2783 */
2784 if (i->p)
2785 return (unsigned char)i->p[1];
2786
2787 /* Now we know it is a file-based in_str. */
2788
2789 /* peek_buf[] is an int array, not char. Can contain EOF. */
2790 /* Is there 2nd char? */
2791 ch = i->peek_buf[1];
2792 if (ch == 0) {
2793 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002794 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002795 i->peek_buf[1] = ch;
2796 }
2797
2798 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2799 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002800}
2801
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002802static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2803{
2804 for (;;) {
2805 int ch, ch2;
2806
2807 ch = i_getch(input);
2808 if (ch != '\\')
2809 return ch;
2810 ch2 = i_peek(input);
2811 if (ch2 != '\n')
2812 return ch;
2813 /* backslash+newline, skip it */
2814 i_getch(input);
2815 }
2816}
2817
2818/* Note: this function _eats_ \<newline> pairs, safe to use plain
2819 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2820 */
2821static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2822{
2823 for (;;) {
2824 int ch, ch2;
2825
2826 ch = i_peek(input);
2827 if (ch != '\\')
2828 return ch;
2829 ch2 = i_peek2(input);
2830 if (ch2 != '\n')
2831 return ch;
2832 /* backslash+newline, skip it */
2833 i_getch(input);
2834 i_getch(input);
2835 }
2836}
2837
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002838static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002839{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002840 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002841 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002842 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002843}
2844
2845static void setup_string_in_str(struct in_str *i, const char *s)
2846{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002847 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002848 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002849 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002850}
2851
2852
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002853/*
2854 * o_string support
2855 */
2856#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002857
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002858static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002859{
2860 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002861 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002862 if (o->data)
2863 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002864}
2865
Denys Vlasenko18567402018-07-20 17:51:31 +02002866static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002867{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002868 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002869 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002870}
2871
Denys Vlasenko18567402018-07-20 17:51:31 +02002872static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002873{
2874 free(o->data);
2875}
2876
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002877static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002878{
2879 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002880 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002881 o->data = xrealloc(o->data, 1 + o->maxlen);
2882 }
2883}
2884
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002885static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002886{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002887 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002888 if (o->length < o->maxlen) {
2889 /* likely. avoid o_grow_by() call */
2890 add:
2891 o->data[o->length] = ch;
2892 o->length++;
2893 o->data[o->length] = '\0';
2894 return;
2895 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002896 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002897 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002898}
2899
Denys Vlasenko657086a2016-09-29 18:07:42 +02002900#if 0
2901/* Valid only if we know o_string is not empty */
2902static void o_delchr(o_string *o)
2903{
2904 o->length--;
2905 o->data[o->length] = '\0';
2906}
2907#endif
2908
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002909static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002910{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002911 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002912 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002913 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002914}
2915
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002916static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002917{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002918 o_addblock(o, str, strlen(str));
2919}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002920
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002921static void o_addstr_with_NUL(o_string *o, const char *str)
2922{
2923 o_addblock(o, str, strlen(str) + 1);
2924}
2925
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002926#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002927static void nommu_addchr(o_string *o, int ch)
2928{
2929 if (o)
2930 o_addchr(o, ch);
2931}
2932#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002933# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002934#endif
2935
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002936#if ENABLE_HUSH_MODE_X
2937static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002938{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002939 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00002940}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002941static void x_mode_addstr(const char *str)
2942{
2943 o_addstr(&G.x_mode_buf, str);
2944}
2945static void x_mode_addblock(const char *str, int len)
2946{
2947 o_addblock(&G.x_mode_buf, str, len);
2948}
2949static void x_mode_prefix(void)
2950{
2951 int n = G.x_mode_depth;
2952 do x_mode_addchr('+'); while (--n >= 0);
2953}
2954static void x_mode_flush(void)
2955{
2956 int len = G.x_mode_buf.length;
2957 if (len <= 0)
2958 return;
2959 if (G.x_mode_fd > 0) {
2960 G.x_mode_buf.data[len] = '\n';
2961 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
2962 }
2963 G.x_mode_buf.length = 0;
2964}
2965#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002966
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002967/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002968 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002969 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2970 * Apparently, on unquoted $v bash still does globbing
2971 * ("v='*.txt'; echo $v" prints all .txt files),
2972 * but NOT brace expansion! Thus, there should be TWO independent
2973 * quoting mechanisms on $v expansion side: one protects
2974 * $v from brace expansion, and other additionally protects "$v" against globbing.
2975 * We have only second one.
2976 */
2977
Denys Vlasenko9e800222010-10-03 14:28:04 +02002978#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002979# define MAYBE_BRACES "{}"
2980#else
2981# define MAYBE_BRACES ""
2982#endif
2983
Eric Andersen25f27032001-04-26 23:22:31 +00002984/* My analysis of quoting semantics tells me that state information
2985 * is associated with a destination, not a source.
2986 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002987static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002988{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002989 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002990 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002991 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002992 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002993 o_grow_by(o, sz);
2994 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002995 o->data[o->length] = '\\';
2996 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002997 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002998 o->data[o->length] = ch;
2999 o->length++;
3000 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003001}
3002
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003003static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003004{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003005 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003006 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
3007 && strchr("*?[\\" MAYBE_BRACES, ch)
3008 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003009 sz++;
3010 o->data[o->length] = '\\';
3011 o->length++;
3012 }
3013 o_grow_by(o, sz);
3014 o->data[o->length] = ch;
3015 o->length++;
3016 o->data[o->length] = '\0';
3017}
3018
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003019static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003020{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003021 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003022 char ch;
3023 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003024 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003025 if (ordinary_cnt > len) /* paranoia */
3026 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003027 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003028 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003029 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003030 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003031 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003032
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003033 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003034 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003035 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003036 sz++;
3037 o->data[o->length] = '\\';
3038 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003039 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003040 o_grow_by(o, sz);
3041 o->data[o->length] = ch;
3042 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003043 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003044 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003045}
3046
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003047static void o_addQblock(o_string *o, const char *str, int len)
3048{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003049 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003050 o_addblock(o, str, len);
3051 return;
3052 }
3053 o_addqblock(o, str, len);
3054}
3055
Denys Vlasenko38292b62010-09-05 14:49:40 +02003056static void o_addQstr(o_string *o, const char *str)
3057{
3058 o_addQblock(o, str, strlen(str));
3059}
3060
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003061/* A special kind of o_string for $VAR and `cmd` expansion.
3062 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003063 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003064 * list[i] contains an INDEX (int!) into this string data.
3065 * It means that if list[] needs to grow, data needs to be moved higher up
3066 * but list[i]'s need not be modified.
3067 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003068 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003069 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3070 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003071#if DEBUG_EXPAND || DEBUG_GLOB
3072static void debug_print_list(const char *prefix, o_string *o, int n)
3073{
3074 char **list = (char**)o->data;
3075 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3076 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003077
3078 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003079 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 +02003080 prefix, list, n, string_start, o->length, o->maxlen,
3081 !!(o->o_expflags & EXP_FLAG_GLOB),
3082 o->has_quoted_part,
3083 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003084 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003085 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003086 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3087 o->data + (int)(uintptr_t)list[i] + string_start,
3088 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003089 i++;
3090 }
3091 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003092 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003093 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003094 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003095 }
3096}
3097#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003098# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003099#endif
3100
3101/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3102 * in list[n] so that it points past last stored byte so far.
3103 * It returns n+1. */
3104static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003105{
3106 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003107 int string_start;
3108 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003109
3110 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003111 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3112 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003113 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003114 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003115 /* list[n] points to string_start, make space for 16 more pointers */
3116 o->maxlen += 0x10 * sizeof(list[0]);
3117 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003118 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003119 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003120 /*
3121 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3122 * check. (grep for -prev-ifs-check-).
3123 * Ensure that argv[-1][last] is not garbage
3124 * but zero bytes, to save index check there.
3125 */
3126 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003127 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003128 } else {
3129 debug_printf_list("list[%d]=%d string_start=%d\n",
3130 n, string_len, string_start);
3131 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003132 } else {
3133 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003134 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3135 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003136 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3137 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003138 o->has_empty_slot = 0;
3139 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003140 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003141 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003142 return n + 1;
3143}
3144
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003145/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003146static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003147{
3148 char **list = (char**)o->data;
3149 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3150
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003151 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003152}
3153
Denys Vlasenko9e800222010-10-03 14:28:04 +02003154#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003155/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3156 * first, it processes even {a} (no commas), second,
3157 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003158 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003159 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003160
3161/* Helper */
3162static int glob_needed(const char *s)
3163{
3164 while (*s) {
3165 if (*s == '\\') {
3166 if (!s[1])
3167 return 0;
3168 s += 2;
3169 continue;
3170 }
3171 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3172 return 1;
3173 s++;
3174 }
3175 return 0;
3176}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003177/* Return pointer to next closing brace or to comma */
3178static const char *next_brace_sub(const char *cp)
3179{
3180 unsigned depth = 0;
3181 cp++;
3182 while (*cp != '\0') {
3183 if (*cp == '\\') {
3184 if (*++cp == '\0')
3185 break;
3186 cp++;
3187 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003188 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003189 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003190 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003191 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003192 depth++;
3193 }
3194
3195 return *cp != '\0' ? cp : NULL;
3196}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003197/* Recursive brace globber. Note: may garble pattern[]. */
3198static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003199{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003200 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003201 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003202 const char *next;
3203 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003204 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003205 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003206
3207 debug_printf_glob("glob_brace('%s')\n", pattern);
3208
3209 begin = pattern;
3210 while (1) {
3211 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003212 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003213 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003214 /* Find the first sub-pattern and at the same time
3215 * find the rest after the closing brace */
3216 next = next_brace_sub(begin);
3217 if (next == NULL) {
3218 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003219 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003220 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003221 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003222 /* "{abc}" with no commas - illegal
3223 * brace expr, disregard and skip it */
3224 begin = next + 1;
3225 continue;
3226 }
3227 break;
3228 }
3229 if (*begin == '\\' && begin[1] != '\0')
3230 begin++;
3231 begin++;
3232 }
3233 debug_printf_glob("begin:%s\n", begin);
3234 debug_printf_glob("next:%s\n", next);
3235
3236 /* Now find the end of the whole brace expression */
3237 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003238 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003239 rest = next_brace_sub(rest);
3240 if (rest == NULL) {
3241 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003242 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003243 }
3244 debug_printf_glob("rest:%s\n", rest);
3245 }
3246 rest_len = strlen(++rest) + 1;
3247
3248 /* We are sure the brace expression is well-formed */
3249
3250 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003251 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003252
3253 /* We have a brace expression. BEGIN points to the opening {,
3254 * NEXT points past the terminator of the first element, and REST
3255 * points past the final }. We will accumulate result names from
3256 * recursive runs for each brace alternative in the buffer using
3257 * GLOB_APPEND. */
3258
3259 p = begin + 1;
3260 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003261 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003262 memcpy(
3263 mempcpy(
3264 mempcpy(new_pattern_buf,
3265 /* We know the prefix for all sub-patterns */
3266 pattern, begin - pattern),
3267 p, next - p),
3268 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003269
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003270 /* Note: glob_brace() may garble new_pattern_buf[].
3271 * That's why we re-copy prefix every time (1st memcpy above).
3272 */
3273 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003274 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003275 /* We saw the last entry */
3276 break;
3277 }
3278 p = next + 1;
3279 next = next_brace_sub(next);
3280 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003281 free(new_pattern_buf);
3282 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003283
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003284 simple_glob:
3285 {
3286 int gr;
3287 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003288
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003289 memset(&globdata, 0, sizeof(globdata));
3290 gr = glob(pattern, 0, NULL, &globdata);
3291 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3292 if (gr != 0) {
3293 if (gr == GLOB_NOMATCH) {
3294 globfree(&globdata);
3295 /* NB: garbles parameter */
3296 unbackslash(pattern);
3297 o_addstr_with_NUL(o, pattern);
3298 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3299 return o_save_ptr_helper(o, n);
3300 }
3301 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003302 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003303 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3304 * but we didn't specify it. Paranoia again. */
3305 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3306 }
3307 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3308 char **argv = globdata.gl_pathv;
3309 while (1) {
3310 o_addstr_with_NUL(o, *argv);
3311 n = o_save_ptr_helper(o, n);
3312 argv++;
3313 if (!*argv)
3314 break;
3315 }
3316 }
3317 globfree(&globdata);
3318 }
3319 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003320}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003321/* Performs globbing on last list[],
3322 * saving each result as a new list[].
3323 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003324static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003325{
3326 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003327
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003328 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003329 if (!o->data)
3330 return o_save_ptr_helper(o, n);
3331 pattern = o->data + o_get_last_ptr(o, n);
3332 debug_printf_glob("glob pattern '%s'\n", pattern);
3333 if (!glob_needed(pattern)) {
3334 /* unbackslash last string in o in place, fix length */
3335 o->length = unbackslash(pattern) - o->data;
3336 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3337 return o_save_ptr_helper(o, n);
3338 }
3339
3340 copy = xstrdup(pattern);
3341 /* "forget" pattern in o */
3342 o->length = pattern - o->data;
3343 n = glob_brace(copy, o, n);
3344 free(copy);
3345 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003346 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003347 return n;
3348}
3349
Denys Vlasenko238081f2010-10-03 14:26:26 +02003350#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003351
3352/* Helper */
3353static int glob_needed(const char *s)
3354{
3355 while (*s) {
3356 if (*s == '\\') {
3357 if (!s[1])
3358 return 0;
3359 s += 2;
3360 continue;
3361 }
3362 if (*s == '*' || *s == '[' || *s == '?')
3363 return 1;
3364 s++;
3365 }
3366 return 0;
3367}
3368/* Performs globbing on last list[],
3369 * saving each result as a new list[].
3370 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003371static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003372{
3373 glob_t globdata;
3374 int gr;
3375 char *pattern;
3376
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003377 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003378 if (!o->data)
3379 return o_save_ptr_helper(o, n);
3380 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003381 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003382 if (!glob_needed(pattern)) {
3383 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003384 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003385 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003386 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003387 return o_save_ptr_helper(o, n);
3388 }
3389
3390 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003391 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3392 * If we glob "*.\*" and don't find anything, we need
3393 * to fall back to using literal "*.*", but GLOB_NOCHECK
3394 * will return "*.\*"!
3395 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003396 gr = glob(pattern, 0, NULL, &globdata);
3397 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003398 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003399 if (gr == GLOB_NOMATCH) {
3400 globfree(&globdata);
3401 goto literal;
3402 }
3403 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003404 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003405 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3406 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003407 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003408 }
3409 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3410 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003411 /* "forget" pattern in o */
3412 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003413 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003414 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003415 n = o_save_ptr_helper(o, n);
3416 argv++;
3417 if (!*argv)
3418 break;
3419 }
3420 }
3421 globfree(&globdata);
3422 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003423 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003424 return n;
3425}
3426
Denys Vlasenko238081f2010-10-03 14:26:26 +02003427#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003428
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003429/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003430 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003431static int o_save_ptr(o_string *o, int n)
3432{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003433 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003434 /* If o->has_empty_slot, list[n] was already globbed
3435 * (if it was requested back then when it was filled)
3436 * so don't do that again! */
3437 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003438 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003439 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003440 return o_save_ptr_helper(o, n);
3441}
3442
3443/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003444static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003445{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003446 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003447 int string_start;
3448
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003449 if (DEBUG_EXPAND)
3450 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003451 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003452 list = (char**)o->data;
3453 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3454 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003455 while (n) {
3456 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003457 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003458 }
3459 return list;
3460}
3461
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003462static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003463
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003464/* Returns pi->next - next pipe in the list */
3465static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003466{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003467 struct pipe *next;
3468 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003469
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003470 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003471 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003472 struct command *command;
3473 struct redir_struct *r, *rnext;
3474
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003475 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003476 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003477 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003478 if (DEBUG_CLEAN) {
3479 int a;
3480 char **p;
3481 for (a = 0, p = command->argv; *p; a++, p++) {
3482 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3483 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003484 }
3485 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003486 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003487 }
3488 /* not "else if": on syntax error, we may have both! */
3489 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003490 debug_printf_clean(" begin group (cmd_type:%d)\n",
3491 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003492 free_pipe_list(command->group);
3493 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003494 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003495 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003496 /* else is crucial here.
3497 * If group != NULL, child_func is meaningless */
3498#if ENABLE_HUSH_FUNCTIONS
3499 else if (command->child_func) {
3500 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3501 command->child_func->parent_cmd = NULL;
3502 }
3503#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003504#if !BB_MMU
3505 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003506 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003507#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003508 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003509 debug_printf_clean(" redirect %d%s",
3510 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003511 /* guard against the case >$FOO, where foo is unset or blank */
3512 if (r->rd_filename) {
3513 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3514 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003515 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003516 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003517 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003518 rnext = r->next;
3519 free(r);
3520 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003521 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003522 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003523 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003524 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003525#if ENABLE_HUSH_JOB
3526 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003527 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003528#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003529
3530 next = pi->next;
3531 free(pi);
3532 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003533}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003534
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003535static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003536{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003537 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003538#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003539 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003540#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003541 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003542 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003543 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003544}
3545
3546
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003547/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003548
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003549#ifndef debug_print_tree
3550static void debug_print_tree(struct pipe *pi, int lvl)
3551{
3552 static const char *const PIPE[] = {
3553 [PIPE_SEQ] = "SEQ",
3554 [PIPE_AND] = "AND",
3555 [PIPE_OR ] = "OR" ,
3556 [PIPE_BG ] = "BG" ,
3557 };
3558 static const char *RES[] = {
3559 [RES_NONE ] = "NONE" ,
3560# if ENABLE_HUSH_IF
3561 [RES_IF ] = "IF" ,
3562 [RES_THEN ] = "THEN" ,
3563 [RES_ELIF ] = "ELIF" ,
3564 [RES_ELSE ] = "ELSE" ,
3565 [RES_FI ] = "FI" ,
3566# endif
3567# if ENABLE_HUSH_LOOPS
3568 [RES_FOR ] = "FOR" ,
3569 [RES_WHILE] = "WHILE",
3570 [RES_UNTIL] = "UNTIL",
3571 [RES_DO ] = "DO" ,
3572 [RES_DONE ] = "DONE" ,
3573# endif
3574# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3575 [RES_IN ] = "IN" ,
3576# endif
3577# if ENABLE_HUSH_CASE
3578 [RES_CASE ] = "CASE" ,
3579 [RES_CASE_IN ] = "CASE_IN" ,
3580 [RES_MATCH] = "MATCH",
3581 [RES_CASE_BODY] = "CASE_BODY",
3582 [RES_ESAC ] = "ESAC" ,
3583# endif
3584 [RES_XXXX ] = "XXXX" ,
3585 [RES_SNTX ] = "SNTX" ,
3586 };
3587 static const char *const CMDTYPE[] = {
3588 "{}",
3589 "()",
3590 "[noglob]",
3591# if ENABLE_HUSH_FUNCTIONS
3592 "func()",
3593# endif
3594 };
3595
3596 int pin, prn;
3597
3598 pin = 0;
3599 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003600 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3601 lvl*2, "",
3602 pin,
3603 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3604 RES[pi->res_word],
3605 pi->followup, PIPE[pi->followup]
3606 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003607 prn = 0;
3608 while (prn < pi->num_cmds) {
3609 struct command *command = &pi->cmds[prn];
3610 char **argv = command->argv;
3611
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003612 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003613 lvl*2, "", prn,
3614 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003615#if ENABLE_HUSH_LINENO_VAR
3616 fdprintf(2, " LINENO:%u", command->lineno);
3617#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003618 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003619 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003620 CMDTYPE[command->cmd_type],
3621 argv
3622# if !BB_MMU
3623 , " group_as_string:", command->group_as_string
3624# else
3625 , "", ""
3626# endif
3627 );
3628 debug_print_tree(command->group, lvl+1);
3629 prn++;
3630 continue;
3631 }
3632 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003633 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003634 argv++;
3635 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003636 if (command->redirects)
3637 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003638 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003639 prn++;
3640 }
3641 pi = pi->next;
3642 pin++;
3643 }
3644}
3645#endif /* debug_print_tree */
3646
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003647static struct pipe *new_pipe(void)
3648{
Eric Andersen25f27032001-04-26 23:22:31 +00003649 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003650 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003651 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003652 return pi;
3653}
3654
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003655/* Command (member of a pipe) is complete, or we start a new pipe
3656 * if ctx->command is NULL.
3657 * No errors possible here.
3658 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003659static int done_command(struct parse_context *ctx)
3660{
3661 /* The command is really already in the pipe structure, so
3662 * advance the pipe counter and make a new, null command. */
3663 struct pipe *pi = ctx->pipe;
3664 struct command *command = ctx->command;
3665
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003666#if 0 /* Instead we emit error message at run time */
3667 if (ctx->pending_redirect) {
3668 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003669 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003670 ctx->pending_redirect = NULL;
3671 }
3672#endif
3673
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003674 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003675 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003676 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003677 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003678 }
3679 pi->num_cmds++;
3680 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003681 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003682 } else {
3683 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3684 }
3685
3686 /* Only real trickiness here is that the uncommitted
3687 * command structure is not counted in pi->num_cmds. */
3688 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003689 ctx->command = command = &pi->cmds[pi->num_cmds];
3690 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003691 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003692#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003693 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003694 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003695#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003696 return pi->num_cmds; /* used only for 0/nonzero check */
3697}
3698
3699static void done_pipe(struct parse_context *ctx, pipe_style type)
3700{
3701 int not_null;
3702
3703 debug_printf_parse("done_pipe entered, followup %d\n", type);
3704 /* Close previous command */
3705 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003706#if HAS_KEYWORDS
3707 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3708 ctx->ctx_inverted = 0;
3709 ctx->pipe->res_word = ctx->ctx_res_w;
3710#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003711 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3712 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003713 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3714 * in a backgrounded subshell.
3715 */
3716 struct pipe *pi;
3717 struct command *command;
3718
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003719 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003720 pi = ctx->list_head;
3721 while (pi != ctx->pipe) {
3722 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3723 goto no_conv;
3724 pi = pi->next;
3725 }
3726
3727 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3728 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3729 pi = xzalloc(sizeof(*pi));
3730 pi->followup = PIPE_BG;
3731 pi->num_cmds = 1;
3732 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3733 command = &pi->cmds[0];
3734 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3735 command->cmd_type = CMD_NORMAL;
3736 command->group = ctx->list_head;
3737#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003738 command->group_as_string = xstrndup(
3739 ctx->as_string.data,
3740 ctx->as_string.length - 1 /* do not copy last char, "&" */
3741 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003742#endif
3743 /* Replace all pipes in ctx with one newly created */
3744 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003745 } else {
3746 no_conv:
3747 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003748 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003749
3750 /* Without this check, even just <enter> on command line generates
3751 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003752 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003753 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003754#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003755 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003756#endif
3757#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003758 || ctx->ctx_res_w == RES_DONE
3759 || ctx->ctx_res_w == RES_FOR
3760 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003761#endif
3762#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003763 || ctx->ctx_res_w == RES_ESAC
3764#endif
3765 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003766 struct pipe *new_p;
3767 debug_printf_parse("done_pipe: adding new pipe: "
3768 "not_null:%d ctx->ctx_res_w:%d\n",
3769 not_null, ctx->ctx_res_w);
3770 new_p = new_pipe();
3771 ctx->pipe->next = new_p;
3772 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003773 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003774 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003775 * This is used to control execution.
3776 * RES_FOR and RES_IN are NOT sticky (needed to support
3777 * cases where variable or value happens to match a keyword):
3778 */
3779#if ENABLE_HUSH_LOOPS
3780 if (ctx->ctx_res_w == RES_FOR
3781 || ctx->ctx_res_w == RES_IN)
3782 ctx->ctx_res_w = RES_NONE;
3783#endif
3784#if ENABLE_HUSH_CASE
3785 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003786 ctx->ctx_res_w = RES_CASE_BODY;
3787 if (ctx->ctx_res_w == RES_CASE)
3788 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003789#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003790 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003791 /* Create the memory for command, roughly:
3792 * ctx->pipe->cmds = new struct command;
3793 * ctx->command = &ctx->pipe->cmds[0];
3794 */
3795 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003796 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003797 }
3798 debug_printf_parse("done_pipe return\n");
3799}
3800
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003801static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003802{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003803 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003804 if (MAYBE_ASSIGNMENT != 0)
3805 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003806 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003807 /* Create the memory for command, roughly:
3808 * ctx->pipe->cmds = new struct command;
3809 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003810 */
3811 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003812}
3813
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003814/* If a reserved word is found and processed, parse context is modified
3815 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003816 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003817#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003818struct reserved_combo {
3819 char literal[6];
3820 unsigned char res;
3821 unsigned char assignment_flag;
3822 int flag;
3823};
3824enum {
3825 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003826# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003827 FLAG_IF = (1 << RES_IF ),
3828 FLAG_THEN = (1 << RES_THEN ),
3829 FLAG_ELIF = (1 << RES_ELIF ),
3830 FLAG_ELSE = (1 << RES_ELSE ),
3831 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003832# endif
3833# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003834 FLAG_FOR = (1 << RES_FOR ),
3835 FLAG_WHILE = (1 << RES_WHILE),
3836 FLAG_UNTIL = (1 << RES_UNTIL),
3837 FLAG_DO = (1 << RES_DO ),
3838 FLAG_DONE = (1 << RES_DONE ),
3839 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003840# endif
3841# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003842 FLAG_MATCH = (1 << RES_MATCH),
3843 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003844# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003845 FLAG_START = (1 << RES_XXXX ),
3846};
3847
3848static const struct reserved_combo* match_reserved_word(o_string *word)
3849{
Eric Andersen25f27032001-04-26 23:22:31 +00003850 /* Mostly a list of accepted follow-up reserved words.
3851 * FLAG_END means we are done with the sequence, and are ready
3852 * to turn the compound list into a command.
3853 * FLAG_START means the word must start a new compound list.
3854 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003855 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003856# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003857 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3858 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3859 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3860 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3861 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3862 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003863# endif
3864# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003865 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3866 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3867 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3868 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3869 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3870 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003871# endif
3872# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003873 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3874 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003875# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003876 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003877 const struct reserved_combo *r;
3878
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003879 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003880 if (strcmp(word->data, r->literal) == 0)
3881 return r;
3882 }
3883 return NULL;
3884}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003885/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003886 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003887static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003888{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003889# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003890 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003891 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003892 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003893# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003894 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003895
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003896 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003897 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003898 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003899 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003900 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003901
3902 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003903# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003904 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3905 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003906 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003907 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003908# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003909 if (r->flag == 0) { /* '!' */
3910 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003911 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003912 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003913 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003914 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003915 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003916 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003917 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003918 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003919
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003920 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003921 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003922 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003923 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003924 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003925 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003926 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003927 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003928 } else {
3929 /* "{...} fi" is ok. "{...} if" is not
3930 * Example:
3931 * if { echo foo; } then { echo bar; } fi */
3932 if (ctx->command->group)
3933 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003934 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003935
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003936 ctx->ctx_res_w = r->res;
3937 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003938 ctx->is_assignment = r->assignment_flag;
3939 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003940
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003941 if (ctx->old_flag & FLAG_END) {
3942 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003943
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003944 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003945 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003946 old = ctx->stack;
3947 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003948 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003949# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003950 /* At this point, the compound command's string is in
3951 * ctx->as_string... except for the leading keyword!
3952 * Consider this example: "echo a | if true; then echo a; fi"
3953 * ctx->as_string will contain "true; then echo a; fi",
3954 * with "if " remaining in old->as_string!
3955 */
3956 {
3957 char *str;
3958 int len = old->as_string.length;
3959 /* Concatenate halves */
3960 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02003961 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003962 /* Find where leading keyword starts in first half */
3963 str = old->as_string.data + len;
3964 if (str > old->as_string.data)
3965 str--; /* skip whitespace after keyword */
3966 while (str > old->as_string.data && isalpha(str[-1]))
3967 str--;
3968 /* Ugh, we're done with this horrid hack */
3969 old->command->group_as_string = xstrdup(str);
3970 debug_printf_parse("pop, remembering as:'%s'\n",
3971 old->command->group_as_string);
3972 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003973# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003974 *ctx = *old; /* physical copy */
3975 free(old);
3976 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003977 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003978}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003979#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003980
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003981/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003982 * Normal return is 0. Syntax errors return 1.
3983 * Note: on return, word is reset, but not o_free'd!
3984 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003985static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003986{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003987 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003988
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003989 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3990 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003991 debug_printf_parse("done_word return 0: true null, ignored\n");
3992 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003993 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003994
Eric Andersen25f27032001-04-26 23:22:31 +00003995 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003996 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3997 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003998 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003999 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004000 * If the redirection operator is "<<" or "<<-", the word
4001 * that follows the redirection operator shall be
4002 * subjected to quote removal; it is unspecified whether
4003 * any of the other expansions occur. For the other
4004 * redirection operators, the word that follows the
4005 * redirection operator shall be subjected to tilde
4006 * expansion, parameter expansion, command substitution,
4007 * arithmetic expansion, and quote removal.
4008 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004009 * on the word by a non-interactive shell; an interactive
4010 * shell may perform it, but shall do so only when
4011 * the expansion would result in one word."
4012 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004013//bash does not do parameter/command substitution or arithmetic expansion
4014//for _heredoc_ redirection word: these constructs look for exact eof marker
4015// as written:
4016// <<EOF$t
4017// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004018// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4019
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004020 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004021 /* Cater for >\file case:
4022 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4023 * Same with heredocs:
4024 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4025 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004026 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4027 unbackslash(ctx->pending_redirect->rd_filename);
4028 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004029 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004030 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4031 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004032 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004033 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004034 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004035 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004036#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004037# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004038 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004039 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004040 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004041 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004042 /* ctx->ctx_res_w = RES_MATCH; */
4043 ctx->ctx_dsemicolon = 0;
4044 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004045# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004046 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004047# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004048 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4049 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004050# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004051# if ENABLE_HUSH_CASE
4052 && ctx->ctx_res_w != RES_CASE
4053# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004054 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004055 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004056 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004057 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004058 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004059# if ENABLE_HUSH_LINENO_VAR
4060/* Case:
4061 * "while ...; do
4062 * cmd ..."
4063 * If we don't close the pipe _now_, immediately after "do", lineno logic
4064 * sees "cmd" as starting at "do" - i.e., at the previous line.
4065 */
4066 if (0
4067 IF_HUSH_IF(|| reserved->res == RES_THEN)
4068 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4069 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4070 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4071 ) {
4072 done_pipe(ctx, PIPE_SEQ);
4073 }
4074# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004075 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004076 debug_printf_parse("done_word return %d\n",
4077 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004078 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004079 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004080# if defined(CMD_SINGLEWORD_NOGLOB)
4081 if (0
4082# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004083 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004084# endif
4085 /* In bash, local/export/readonly are special, args
4086 * are assignments and therefore expansion of them
4087 * should be "one-word" expansion:
4088 * $ export i=`echo 'a b'` # one arg: "i=a b"
4089 * compare with:
4090 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4091 * ls: cannot access i=a: No such file or directory
4092 * ls: cannot access b: No such file or directory
4093 * Note: bash 3.2.33(1) does this only if export word
4094 * itself is not quoted:
4095 * $ export i=`echo 'aaa bbb'`; echo "$i"
4096 * aaa bbb
4097 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4098 * aaa
4099 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004100 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4101 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4102 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004103 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004104 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4105 }
4106 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004107# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004108 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004109#endif /* HAS_KEYWORDS */
4110
Denis Vlasenkobb929512009-04-16 10:59:40 +00004111 if (command->group) {
4112 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004113 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004114 debug_printf_parse("done_word return 1: syntax error, "
4115 "groups and arglists don't mix\n");
4116 return 1;
4117 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004118
4119 /* If this word wasn't an assignment, next ones definitely
4120 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004121 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4122 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004123 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004124 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004125 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004126 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004127 command->assignment_cnt++;
4128 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4129 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004130 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4131 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004132 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004133 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4134 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004135 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004136 }
Eric Andersen25f27032001-04-26 23:22:31 +00004137
Denis Vlasenko06810332007-05-21 23:30:54 +00004138#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004139 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004140 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004141 || !is_well_formed_var_name(command->argv[0], '\0')
4142 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004143 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004144 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004145 return 1;
4146 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004147 /* Force FOR to have just one word (variable name) */
4148 /* NB: basically, this makes hush see "for v in ..."
4149 * syntax as if it is "for v; in ...". FOR and IN become
4150 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004151 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004152 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004153#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004154#if ENABLE_HUSH_CASE
4155 /* Force CASE to have just one word */
4156 if (ctx->ctx_res_w == RES_CASE) {
4157 done_pipe(ctx, PIPE_SEQ);
4158 }
4159#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004160
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004161 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004162
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004163 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004164 return 0;
4165}
4166
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004167
4168/* Peek ahead in the input to find out if we have a "&n" construct,
4169 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004170 * Return:
4171 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4172 * REDIRFD_SYNTAX_ERR if syntax error,
4173 * REDIRFD_TO_FILE if no & was seen,
4174 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 */
4176#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004177#define parse_redir_right_fd(as_string, input) \
4178 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004179#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004180static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004181{
4182 int ch, d, ok;
4183
4184 ch = i_peek(input);
4185 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004186 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004187
4188 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004189 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004190 ch = i_peek(input);
4191 if (ch == '-') {
4192 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004193 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004194 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004195 }
4196 d = 0;
4197 ok = 0;
4198 while (ch != EOF && isdigit(ch)) {
4199 d = d*10 + (ch-'0');
4200 ok = 1;
4201 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004202 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004203 ch = i_peek(input);
4204 }
4205 if (ok) return d;
4206
4207//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4208
4209 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004210 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004211}
4212
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004213/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004214 */
4215static int parse_redirect(struct parse_context *ctx,
4216 int fd,
4217 redir_type style,
4218 struct in_str *input)
4219{
4220 struct command *command = ctx->command;
4221 struct redir_struct *redir;
4222 struct redir_struct **redirp;
4223 int dup_num;
4224
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004225 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004226 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004227 /* Check for a '>&1' type redirect */
4228 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4229 if (dup_num == REDIRFD_SYNTAX_ERR)
4230 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004231 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004232 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004233 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004234 if (dup_num) { /* <<-... */
4235 ch = i_getch(input);
4236 nommu_addchr(&ctx->as_string, ch);
4237 ch = i_peek(input);
4238 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004239 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004240
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004241 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004242 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004243 if (ch == '|') {
4244 /* >|FILE redirect ("clobbering" >).
4245 * Since we do not support "set -o noclobber" yet,
4246 * >| and > are the same for now. Just eat |.
4247 */
4248 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004249 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004250 }
4251 }
4252
4253 /* Create a new redir_struct and append it to the linked list */
4254 redirp = &command->redirects;
4255 while ((redir = *redirp) != NULL) {
4256 redirp = &(redir->next);
4257 }
4258 *redirp = redir = xzalloc(sizeof(*redir));
4259 /* redir->next = NULL; */
4260 /* redir->rd_filename = NULL; */
4261 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004262 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004263
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004264 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4265 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004266
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004267 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004268 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004269 /* Erik had a check here that the file descriptor in question
4270 * is legit; I postpone that to "run time"
4271 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004272 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4273 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004274 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004275#if 0 /* Instead we emit error message at run time */
4276 if (ctx->pending_redirect) {
4277 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004278 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004279 }
4280#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004281 /* Set ctx->pending_redirect, so we know what to do at the
4282 * end of the next parsed word. */
4283 ctx->pending_redirect = redir;
4284 }
4285 return 0;
4286}
4287
Eric Andersen25f27032001-04-26 23:22:31 +00004288/* If a redirect is immediately preceded by a number, that number is
4289 * supposed to tell which file descriptor to redirect. This routine
4290 * looks for such preceding numbers. In an ideal world this routine
4291 * needs to handle all the following classes of redirects...
4292 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4293 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4294 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4295 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004296 *
4297 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4298 * "2.7 Redirection
4299 * ... If n is quoted, the number shall not be recognized as part of
4300 * the redirection expression. For example:
4301 * echo \2>a
4302 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004303 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004304 *
4305 * A -1 return means no valid number was found,
4306 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004307 */
4308static int redirect_opt_num(o_string *o)
4309{
4310 int num;
4311
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004312 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004313 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004314 num = bb_strtou(o->data, NULL, 10);
4315 if (errno || num < 0)
4316 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004317 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004318 return num;
4319}
4320
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004321#if BB_MMU
4322#define fetch_till_str(as_string, input, word, skip_tabs) \
4323 fetch_till_str(input, word, skip_tabs)
4324#endif
4325static char *fetch_till_str(o_string *as_string,
4326 struct in_str *input,
4327 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004328 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004329{
4330 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004331 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004332 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004333 int ch;
4334
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004335 /* Starting with "" is necessary for this case:
4336 * cat <<EOF
4337 *
4338 * xxx
4339 * EOF
4340 */
4341 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4342
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004343 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004344
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004345 while (1) {
4346 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004347 if (ch != EOF)
4348 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004349 if (ch == '\n' || ch == EOF) {
4350 check_heredoc_end:
4351 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004352 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004353 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4354 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004355 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004356 return heredoc.data;
4357 }
4358 if (ch == '\n') {
4359 /* This is a new line.
4360 * Remember position and backslash-escaping status.
4361 */
4362 o_addchr(&heredoc, ch);
4363 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004364 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004365 past_EOL = heredoc.length;
4366 /* Get 1st char of next line, possibly skipping leading tabs */
4367 do {
4368 ch = i_getch(input);
4369 if (ch != EOF)
4370 nommu_addchr(as_string, ch);
4371 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4372 /* If this immediately ended the line,
4373 * go back to end-of-line checks.
4374 */
4375 if (ch == '\n')
4376 goto check_heredoc_end;
4377 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004378 } else {
4379 /* Backslash-line continuation in an unquoted
4380 * heredoc. This does not need special handling
4381 * for heredoc body (unquoted heredocs are
4382 * expanded on "execution" and that would take
4383 * care of this case too), but not the case
4384 * of line continuation *in terminator*:
4385 * cat <<EOF
4386 * Ok1
4387 * EO\
4388 * F
4389 */
4390 heredoc.data[--heredoc.length] = '\0';
4391 prev = 0; /* not '\' */
4392 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004393 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004394 }
4395 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004396 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004397 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004398 }
4399 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004400 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004401 if (prev == '\\' && ch == '\\')
4402 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004403 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004404 else
4405 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004406 }
4407}
4408
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004409/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4410 * and load them all. There should be exactly heredoc_cnt of them.
4411 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004412#if BB_MMU
4413#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4414 fetch_heredocs(pi, heredoc_cnt, input)
4415#endif
4416static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004417{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004418 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004419 int i;
4420 struct command *cmd = pi->cmds;
4421
Denys Vlasenko3675c372018-07-23 16:31:21 +02004422 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004423 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004424 cmd->argv ? cmd->argv[0] : "NONE"
4425 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004426 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004427 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004428
Denys Vlasenko3675c372018-07-23 16:31:21 +02004429 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004430 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004431 while (redir) {
4432 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004433 char *p;
4434
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004435 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004436 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004437 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004438 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004439 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004440 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004441 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004442 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004443 free(redir->rd_filename);
4444 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004445 heredoc_cnt--;
4446 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004447 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004448 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004449 if (cmd->group) {
4450 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4451 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4452 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4453 if (heredoc_cnt < 0)
4454 return heredoc_cnt; /* error */
4455 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004456 cmd++;
4457 }
4458 pi = pi->next;
4459 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004460 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004461}
4462
4463
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004464static int run_list(struct pipe *pi);
4465#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004466#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4467 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004468#endif
4469static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004470 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004471 struct in_str *input,
4472 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004473
Denys Vlasenko474cb202018-07-24 13:03:03 +02004474/* Returns number of heredocs not yet consumed,
4475 * or -1 on error.
4476 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004477static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004478 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004479{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004480 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004481 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004482 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004483#if BB_MMU
4484# define as_string NULL
4485#else
4486 char *as_string = NULL;
4487#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004488 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004489 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004490 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004491 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004492
4493 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004494#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004495 if (ch == '(' && !ctx->word.has_quoted_part) {
4496 if (ctx->word.length)
4497 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004498 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004499 if (!command->argv)
4500 goto skip; /* (... */
4501 if (command->argv[1]) { /* word word ... (... */
4502 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004503 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004504 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004505 /* it is "word(..." or "word (..." */
4506 do
4507 ch = i_getch(input);
4508 while (ch == ' ' || ch == '\t');
4509 if (ch != ')') {
4510 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004511 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004512 }
4513 nommu_addchr(&ctx->as_string, ch);
4514 do
4515 ch = i_getch(input);
4516 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004517 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004518 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004519 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004520 }
4521 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004522 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004523 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004524 }
4525#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004526
4527#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004528 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004529 || ctx->word.length /* word{... */
4530 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004531 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004532 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004533 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004534 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004535 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004536 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004537#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004538
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004539 IF_HUSH_FUNCTIONS(skip:)
4540
Denis Vlasenko240c2552009-04-03 03:45:05 +00004541 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004542 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004543 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004544 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4545 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004546 } else {
4547 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004548 ch = i_peek(input);
4549 if (ch != ' ' && ch != '\t' && ch != '\n'
4550 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4551 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004552 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004553 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004554 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004555 if (ch != '(') {
4556 ch = i_getch(input);
4557 nommu_addchr(&ctx->as_string, ch);
4558 }
Eric Andersen25f27032001-04-26 23:22:31 +00004559 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004560
Denys Vlasenko474cb202018-07-24 13:03:03 +02004561 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4562 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4563 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004564#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004565 if (as_string)
4566 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004567#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004568
4569 /* empty ()/{} or parse error? */
4570 if (!pipe_list || pipe_list == ERR_PTR) {
4571 /* parse_stream already emitted error msg */
4572 if (!BB_MMU)
4573 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004574 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004575 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004576 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004577 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004578#if !BB_MMU
4579 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4580 command->group_as_string = as_string;
4581 debug_printf_parse("end of group, remembering as:'%s'\n",
4582 command->group_as_string);
4583#endif
4584
4585#if ENABLE_HUSH_FUNCTIONS
4586 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4587 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4588 struct command *cmd2;
4589
4590 cmd2 = xzalloc(sizeof(*cmd2));
4591 cmd2->cmd_type = CMD_SUBSHELL;
4592 cmd2->group = pipe_list;
4593# if !BB_MMU
4594//UNTESTED!
4595 cmd2->group_as_string = command->group_as_string;
4596 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4597# endif
4598
4599 pipe_list = new_pipe();
4600 pipe_list->cmds = cmd2;
4601 pipe_list->num_cmds = 1;
4602 }
4603#endif
4604
4605 command->group = pipe_list;
4606
Denys Vlasenko474cb202018-07-24 13:03:03 +02004607 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4608 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004609 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004610#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004611}
4612
Denys Vlasenko0b883582016-12-23 16:49:07 +01004613#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004614/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004615/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004616static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004617{
4618 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004619 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004620 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004621 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004622 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004623 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004624 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004625 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004626 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004627 }
4628}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004629static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4630{
4631 while (1) {
4632 int ch = i_getch(input);
4633 if (ch == EOF) {
4634 syntax_error_unterm_ch('\'');
4635 return 0;
4636 }
4637 if (ch == '\'')
4638 return 1;
4639 o_addqchr(dest, ch);
4640 }
4641}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004642/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004643static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004644static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004645{
4646 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004647 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004648 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004649 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004650 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004651 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004652 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004653 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004654 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004655 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004656 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004657 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004658 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004659 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004660 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4661 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004662 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004663 continue;
4664 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004665 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004666 }
4667}
4668/* Process `cmd` - copy contents until "`" is seen. Complicated by
4669 * \` quoting.
4670 * "Within the backquoted style of command substitution, backslash
4671 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4672 * The search for the matching backquote shall be satisfied by the first
4673 * backquote found without a preceding backslash; during this search,
4674 * if a non-escaped backquote is encountered within a shell comment,
4675 * a here-document, an embedded command substitution of the $(command)
4676 * form, or a quoted string, undefined results occur. A single-quoted
4677 * or double-quoted string that begins, but does not end, within the
4678 * "`...`" sequence produces undefined results."
4679 * Example Output
4680 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4681 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004682static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004683{
4684 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004685 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004686 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004687 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004688 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004689 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4690 ch = i_getch(input);
4691 if (ch != '`'
4692 && ch != '$'
4693 && ch != '\\'
4694 && (!in_dquote || ch != '"')
4695 ) {
4696 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004697 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004698 }
4699 if (ch == EOF) {
4700 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004701 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004702 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004703 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004704 }
4705}
4706/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4707 * quoting and nested ()s.
4708 * "With the $(command) style of command substitution, all characters
4709 * following the open parenthesis to the matching closing parenthesis
4710 * constitute the command. Any valid shell script can be used for command,
4711 * except a script consisting solely of redirections which produces
4712 * unspecified results."
4713 * Example Output
4714 * echo $(echo '(TEST)' BEST) (TEST) BEST
4715 * echo $(echo 'TEST)' BEST) TEST) BEST
4716 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004717 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004718 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004719 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004720 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4721 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004722 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004723#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004724static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004725{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004726 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004727 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004728# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004729 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004730# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004731 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4732
Denys Vlasenko817a2022018-06-26 15:35:17 +02004733#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004734 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004735#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004736 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4737
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004738 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004739 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004740 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004741 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004742 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004743 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004744 if (ch == end_ch
4745# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004746 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004747# endif
4748 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004749 if (!dbl)
4750 break;
4751 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004752 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004753 i_getch(input); /* eat second ')' */
4754 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004755 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004756 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004757 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004758 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004759 if (ch == '(' || ch == '{') {
4760 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004761 if (!add_till_closing_bracket(dest, input, ch))
4762 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004763 o_addchr(dest, ch);
4764 continue;
4765 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004766 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004767 if (!add_till_single_quote(dest, input))
4768 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004769 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004770 continue;
4771 }
4772 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004773 if (!add_till_double_quote(dest, input))
4774 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004775 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004776 continue;
4777 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004778 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004779 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4780 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004781 o_addchr(dest, ch);
4782 continue;
4783 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004784 if (ch == '\\') {
4785 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004786 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004787 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004788 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004789 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004790 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004791#if 0
4792 if (ch == '\n') {
4793 /* "backslash+newline", ignore both */
4794 o_delchr(dest); /* undo insertion of '\' */
4795 continue;
4796 }
4797#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004798 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004799 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004800 continue;
4801 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004802 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004803 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004804 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004805}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004806#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004807
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004808/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004809#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004810#define parse_dollar(as_string, dest, input, quote_mask) \
4811 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004812#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004813#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004814static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004815 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004816 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004817{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004818 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004819
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004820 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004821 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004822 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004823 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004824 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004825 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004826 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004827 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004828 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004829 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004830 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004831 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004832 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004833 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004834 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004835 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004836 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004837 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004838 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004839 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004840 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004841 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004842 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004843 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004844 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004845 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004846 o_addchr(dest, ch | quote_mask);
4847 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004848 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004849 case '$': /* pid */
4850 case '!': /* last bg pid */
4851 case '?': /* last exit code */
4852 case '#': /* number of args */
4853 case '*': /* args */
4854 case '@': /* args */
4855 goto make_one_char_var;
4856 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004857 char len_single_ch;
4858
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004859 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4860
Denys Vlasenko74369502010-05-21 19:52:01 +02004861 ch = i_getch(input); /* eat '{' */
4862 nommu_addchr(as_string, ch);
4863
Denys Vlasenko46e64982016-09-29 19:50:55 +02004864 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004865 /* It should be ${?}, or ${#var},
4866 * or even ${?+subst} - operator acting on a special variable,
4867 * or the beginning of variable name.
4868 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004869 if (ch == EOF
4870 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4871 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004872 bad_dollar_syntax:
4873 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004874 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4875 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004876 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004877 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004878 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004879 ch |= quote_mask;
4880
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004881 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004882 * However, this regresses some of our testsuite cases
4883 * which check invalid constructs like ${%}.
4884 * Oh well... let's check that the var name part is fine... */
4885
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004886 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004887 unsigned pos;
4888
Denys Vlasenko74369502010-05-21 19:52:01 +02004889 o_addchr(dest, ch);
4890 debug_printf_parse(": '%c'\n", ch);
4891
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004892 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004893 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004894 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004895 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004896
Denys Vlasenko74369502010-05-21 19:52:01 +02004897 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004898 unsigned end_ch;
4899 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004900 /* handle parameter expansions
4901 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4902 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004903 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4904 if (len_single_ch != '#'
4905 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4906 || i_peek(input) != '}'
4907 ) {
4908 goto bad_dollar_syntax;
4909 }
4910 /* else: it's "length of C" ${#C} op,
4911 * where C is a single char
4912 * special var name, e.g. ${#!}.
4913 */
4914 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004915 /* Eat everything until closing '}' (or ':') */
4916 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004917 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004918 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004919 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004920 ) {
4921 /* It's ${var:N[:M]} thing */
4922 end_ch = '}' * 0x100 + ':';
4923 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004924 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004925 && ch == '/'
4926 ) {
4927 /* It's ${var/[/]pattern[/repl]} thing */
4928 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4929 i_getch(input);
4930 nommu_addchr(as_string, '/');
4931 ch = '\\';
4932 }
4933 end_ch = '}' * 0x100 + '/';
4934 }
4935 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02004936 /* The pattern can't be empty.
4937 * IOW: if the first char after "${v//" is a slash,
4938 * it does not terminate the pattern - it's the first char of the pattern:
4939 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
4940 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
4941 */
4942 if (i_peek(input) == '/') {
4943 o_addchr(dest, i_getch(input));
4944 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004945 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004946 if (!BB_MMU)
4947 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004948#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004949 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004950 if (last_ch == 0) /* error? */
4951 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004952#else
4953#error Simple code to only allow ${var} is not implemented
4954#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004955 if (as_string) {
4956 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004957 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004958 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004959
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004960 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4961 && (end_ch & 0xff00)
4962 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004963 /* close the first block: */
4964 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004965 /* while parsing N from ${var:N[:M]}
4966 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004967 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004968 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004969 end_ch = '}';
4970 goto again;
4971 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004972 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004973 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004974 /* it's ${var:N} - emulate :999999999 */
4975 o_addstr(dest, "999999999");
4976 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004977 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004978 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004979 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004980 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004981 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004982 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4983 break;
4984 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004985#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004986 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004987 unsigned pos;
4988
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004989 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004990 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004991# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004992 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004993 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004994 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004995 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4996 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004997 if (!BB_MMU)
4998 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004999 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5000 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005001 if (as_string) {
5002 o_addstr(as_string, dest->data + pos);
5003 o_addchr(as_string, ')');
5004 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005005 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005006 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005007 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005008 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005009# endif
5010# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005011 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5012 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005013 if (!BB_MMU)
5014 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005015 if (!add_till_closing_bracket(dest, input, ')'))
5016 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005017 if (as_string) {
5018 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005019 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005020 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005021 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005022# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005023 break;
5024 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005025#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005026 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005027 goto make_var;
5028#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005029 /* TODO: $_ and $-: */
5030 /* $_ Shell or shell script name; or last argument of last command
5031 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5032 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005033 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005034 ch = i_getch(input);
5035 nommu_addchr(as_string, ch);
5036 ch = i_peek_and_eat_bkslash_nl(input);
5037 if (isalnum(ch)) { /* it's $_name or $_123 */
5038 ch = '_';
5039 goto make_var1;
5040 }
5041 /* else: it's $_ */
5042#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005043 default:
5044 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005045 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005046 debug_printf_parse("parse_dollar return 1 (ok)\n");
5047 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005048#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005049}
5050
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005051#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005052#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005053 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005054#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005055#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005056static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005057 o_string *dest,
5058 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005059 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005060{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005061 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005062 int next;
5063
5064 again:
5065 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005066 if (ch != EOF)
5067 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005068 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005069 debug_printf_parse("encode_string return 1 (ok)\n");
5070 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005071 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005072 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005073 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005074 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005075 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005076 }
5077 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005078 if (ch != '\n') {
5079 next = i_peek(input);
5080 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005081 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005082 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005083 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005084 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005085 /* Testcase: in interactive shell a file with
5086 * echo "unterminated string\<eof>
5087 * is sourced.
5088 */
5089 syntax_error_unterm_ch('"');
5090 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005091 }
5092 /* bash:
5093 * "The backslash retains its special meaning [in "..."]
5094 * only when followed by one of the following characters:
5095 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005096 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005097 * NB: in (unquoted) heredoc, above does not apply to ",
5098 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005099 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005100 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005101 ch = i_getch(input); /* eat next */
5102 if (ch == '\n')
5103 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005104 } /* else: ch remains == '\\', and we double it below: */
5105 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005106 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005107 goto again;
5108 }
5109 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005110 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5111 debug_printf_parse("encode_string return 0: "
5112 "parse_dollar returned 0 (error)\n");
5113 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005114 }
5115 goto again;
5116 }
5117#if ENABLE_HUSH_TICK
5118 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005119 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005120 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5121 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005122 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5123 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005124 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5125 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005126 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005127 }
5128#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005129 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005130 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005131#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005132}
5133
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005134/*
5135 * Scan input until EOF or end_trigger char.
5136 * Return a list of pipes to execute, or NULL on EOF
5137 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005138 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005139 * reset parsing machinery and start parsing anew,
5140 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005141 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005142static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005143 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005144 struct in_str *input,
5145 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005146{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005147 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005148 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005149
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005150 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005151 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005152 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005153 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005154 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005155 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005156
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005157 initialize_context(&ctx);
5158
5159 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5160 * Preventing this:
5161 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005162 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005163
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005164 /* We used to separate words on $IFS here. This was wrong.
5165 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005166 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005167 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005168
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005169 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005170 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005171 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005172 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005173 int ch;
5174 int next;
5175 int redir_fd;
5176 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005177
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005178 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005179 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005180 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005181 if (ch == EOF) {
5182 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005183
5184 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005185 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005186 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005187 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005188 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005189 syntax_error_unterm_ch('(');
5190 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005191 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005192 if (end_trigger == '}') {
5193 syntax_error_unterm_ch('{');
5194 goto parse_error;
5195 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005196
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005197 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005198 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005199 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005200 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005201 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005202 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005203 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005204 /* (this makes bare "&" cmd a no-op.
5205 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005206 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005207 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005208 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005209 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005210 pi = NULL;
5211 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005212#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005213 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005214 if (pstring)
5215 *pstring = ctx.as_string.data;
5216 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005217 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005218#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005219 // heredoc_cnt must be 0 here anyway
5220 //if (heredoc_cnt_ptr)
5221 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005222 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005223 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005224 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005225 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005226 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005227
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005228 /* Handle "'" and "\" first, as they won't play nice with
5229 * i_peek_and_eat_bkslash_nl() anyway:
5230 * echo z\\
5231 * and
5232 * echo '\
5233 * '
5234 * would break.
5235 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005236 if (ch == '\\') {
5237 ch = i_getch(input);
5238 if (ch == '\n')
5239 continue; /* drop \<newline>, get next char */
5240 nommu_addchr(&ctx.as_string, '\\');
5241 o_addchr(&ctx.word, '\\');
5242 if (ch == EOF) {
5243 /* Testcase: eval 'echo Ok\' */
5244 /* bash-4.3.43 was removing backslash,
5245 * but 4.4.19 retains it, most other shells too
5246 */
5247 continue; /* get next char */
5248 }
5249 /* Example: echo Hello \2>file
5250 * we need to know that word 2 is quoted
5251 */
5252 ctx.word.has_quoted_part = 1;
5253 nommu_addchr(&ctx.as_string, ch);
5254 o_addchr(&ctx.word, ch);
5255 continue; /* get next char */
5256 }
5257 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005258 if (ch == '\'') {
5259 ctx.word.has_quoted_part = 1;
5260 next = i_getch(input);
5261 if (next == '\'' && !ctx.pending_redirect)
5262 goto insert_empty_quoted_str_marker;
5263
5264 ch = next;
5265 while (1) {
5266 if (ch == EOF) {
5267 syntax_error_unterm_ch('\'');
5268 goto parse_error;
5269 }
5270 nommu_addchr(&ctx.as_string, ch);
5271 if (ch == '\'')
5272 break;
5273 if (ch == SPECIAL_VAR_SYMBOL) {
5274 /* Convert raw ^C to corresponding special variable reference */
5275 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5276 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5277 }
5278 o_addqchr(&ctx.word, ch);
5279 ch = i_getch(input);
5280 }
5281 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005282 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005283
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005284 next = '\0';
5285 if (ch != '\n')
5286 next = i_peek_and_eat_bkslash_nl(input);
5287
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005288 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005289 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005290 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005291 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005292 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005293 || ctx.word.length /* word{... - non-special */
5294 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005295 || (next != ';' /* }; - special */
5296 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005297 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005298 && next != '&' /* }& and }&& ... - special */
5299 && next != '|' /* }|| ... - special */
5300 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005301 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005302 ) {
5303 /* They are not special, skip "{}" */
5304 is_special += 2;
5305 }
5306 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005307 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005308
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005309 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005310 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005311 o_addQchr(&ctx.word, ch);
5312 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5313 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005314 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005315 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005316 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005317 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5318 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005319 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005320 continue;
5321 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005322
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005323 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005324#if ENABLE_HUSH_LINENO_VAR
5325/* Case:
5326 * "while ...; do<whitespace><newline>
5327 * cmd ..."
5328 * would think that "cmd" starts in <whitespace> -
5329 * i.e., at the previous line.
5330 * We need to skip all whitespace before newlines.
5331 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005332 while (ch != '\n') {
5333 next = i_peek(input);
5334 if (next != ' ' && next != '\t' && next != '\n')
5335 break; /* next char is not ws */
5336 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005337 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005338 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005339#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005340 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005341 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005342 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005343 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005344 /* Is this a case when newline is simply ignored?
5345 * Some examples:
5346 * "cmd | <newline> cmd ..."
5347 * "case ... in <newline> word) ..."
5348 */
5349 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005350 && ctx.word.length == 0
5351 && !ctx.word.has_quoted_part
5352 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005353 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005354 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005355 * Without check #1, interactive shell
5356 * ignores even bare <newline>,
5357 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005358 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005359 * ps2> _ <=== wrong, should be ps1
5360 * Without check #2, "cmd & <newline>"
5361 * is similarly mistreated.
5362 * (BTW, this makes "cmd & cmd"
5363 * and "cmd && cmd" non-orthogonal.
5364 * Really, ask yourself, why
5365 * "cmd && <newline>" doesn't start
5366 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005367 * The only reason is that it might be
5368 * a "cmd1 && <nl> cmd2 &" construct,
5369 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005370 */
5371 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005372 if (pi->num_cmds != 0 /* check #1 */
5373 && pi->followup != PIPE_BG /* check #2 */
5374 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005375 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005376 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005377 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005378 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005379 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005380 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005381 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005382 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5383 if (heredoc_cnt != 0)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005384 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005385 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005386 ctx.is_assignment = MAYBE_ASSIGNMENT;
5387 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005388 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005389 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005390 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005391 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005392 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005393
5394 /* "cmd}" or "cmd }..." without semicolon or &:
5395 * } is an ordinary char in this case, even inside { cmd; }
5396 * Pathological example: { ""}; } should exec "}" cmd
5397 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005398 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005399 if (ctx.word.length != 0 /* word} */
5400 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005401 ) {
5402 goto ordinary_char;
5403 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005404 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5405 /* Generally, there should be semicolon: "cmd; }"
5406 * However, bash allows to omit it if "cmd" is
5407 * a group. Examples:
5408 * { { echo 1; } }
5409 * {(echo 1)}
5410 * { echo 0 >&2 | { echo 1; } }
5411 * { while false; do :; done }
5412 * { case a in b) ;; esac }
5413 */
5414 if (ctx.command->group)
5415 goto term_group;
5416 goto ordinary_char;
5417 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005418 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005419 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005420 goto skip_end_trigger;
5421 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005422 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005423 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005424 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005425 && (ch != ';' || heredoc_cnt == 0)
5426#if ENABLE_HUSH_CASE
5427 && (ch != ')'
5428 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005429 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005430 )
5431#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005432 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005433 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005434 goto parse_error;
5435 }
5436 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005437 ctx.is_assignment = MAYBE_ASSIGNMENT;
5438 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005439 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005440 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005441 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005442 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005443 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005444#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005445 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005446 if (pstring)
5447 *pstring = ctx.as_string.data;
5448 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005449 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005450#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005451 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5452 /* Example: bare "{ }", "()" */
5453 G.last_exitcode = 2; /* bash compat */
5454 syntax_error_unexpected_ch(ch);
5455 goto parse_error2;
5456 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005457 if (heredoc_cnt_ptr)
5458 *heredoc_cnt_ptr = heredoc_cnt;
5459 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005460 debug_printf_parse("parse_stream return %p: "
5461 "end_trigger char found\n",
5462 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005463 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005464 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005465 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005466 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005467
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005468 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005469 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005470
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005471 /* Catch <, > before deciding whether this word is
5472 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5473 switch (ch) {
5474 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005475 redir_fd = redirect_opt_num(&ctx.word);
5476 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005477 goto parse_error;
5478 }
5479 redir_style = REDIRECT_OVERWRITE;
5480 if (next == '>') {
5481 redir_style = REDIRECT_APPEND;
5482 ch = i_getch(input);
5483 nommu_addchr(&ctx.as_string, ch);
5484 }
5485#if 0
5486 else if (next == '(') {
5487 syntax_error(">(process) not supported");
5488 goto parse_error;
5489 }
5490#endif
5491 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5492 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005493 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005494 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005495 redir_fd = redirect_opt_num(&ctx.word);
5496 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005497 goto parse_error;
5498 }
5499 redir_style = REDIRECT_INPUT;
5500 if (next == '<') {
5501 redir_style = REDIRECT_HEREDOC;
5502 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005503 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005504 ch = i_getch(input);
5505 nommu_addchr(&ctx.as_string, ch);
5506 } else if (next == '>') {
5507 redir_style = REDIRECT_IO;
5508 ch = i_getch(input);
5509 nommu_addchr(&ctx.as_string, ch);
5510 }
5511#if 0
5512 else if (next == '(') {
5513 syntax_error("<(process) not supported");
5514 goto parse_error;
5515 }
5516#endif
5517 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5518 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005519 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005520 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005521 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005522 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005523 /* note: we do not add it to &ctx.as_string */
5524/* TODO: in bash:
5525 * comment inside $() goes to the next \n, even inside quoted string (!):
5526 * cmd "$(cmd2 #comment)" - syntax error
5527 * cmd "`cmd2 #comment`" - ok
5528 * We accept both (comment ends where command subst ends, in both cases).
5529 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005530 while (1) {
5531 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005532 if (ch == '\n') {
5533 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005534 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005535 }
5536 ch = i_getch(input);
5537 if (ch == EOF)
5538 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005539 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005540 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005541 }
5542 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005543 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005544 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005545
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005546 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005547 /* check that we are not in word in "a=1 2>word b=1": */
5548 && !ctx.pending_redirect
5549 ) {
5550 /* ch is a special char and thus this word
5551 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005552 ctx.is_assignment = NOT_ASSIGNMENT;
5553 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005554 }
5555
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005556 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5557
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005558 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005559 case SPECIAL_VAR_SYMBOL:
5560 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005561 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5562 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005563 /* fall through */
5564 case '#':
5565 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005566 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005567 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005568 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005569 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005570 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005571 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005572 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005573 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005574 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005575 case '"':
5576 ctx.word.has_quoted_part = 1;
5577 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005578 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005579 insert_empty_quoted_str_marker:
5580 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005581 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5582 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005583 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005584 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005585 if (ctx.is_assignment == NOT_ASSIGNMENT)
5586 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005587 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005588 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005589 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005590 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005591#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005592 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005593 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005594
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005595 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5596 o_addchr(&ctx.word, '`');
5597 USE_FOR_NOMMU(pos = ctx.word.length;)
5598 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005599 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005600# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005601 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005602 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005603# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005604 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5605 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005606 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005607 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005608#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005609 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005610#if ENABLE_HUSH_CASE
5611 case_semi:
5612#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005613 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005614 goto parse_error;
5615 }
5616 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005617#if ENABLE_HUSH_CASE
5618 /* Eat multiple semicolons, detect
5619 * whether it means something special */
5620 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005621 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005622 if (ch != ';')
5623 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005624 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005625 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005626 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005627 ctx.ctx_dsemicolon = 1;
5628 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005629 break;
5630 }
5631 }
5632#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005633 new_cmd:
5634 /* We just finished a cmd. New one may start
5635 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005636 ctx.is_assignment = MAYBE_ASSIGNMENT;
5637 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005638 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005639 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005640 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005641 goto parse_error;
5642 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005643 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005644 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005645 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005646 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005647 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005648 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005649 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005650 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005651 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005652 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005653 goto parse_error;
5654 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005655#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005656 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005657 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005658#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005659 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005660 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005661 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005662 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005663 } else {
5664 /* we could pick up a file descriptor choice here
5665 * with redirect_opt_num(), but bash doesn't do it.
5666 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005667 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005668 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005669 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005670 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005671#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005672 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005673 if (ctx.ctx_res_w == RES_MATCH
5674 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005675 && ctx.word.length == 0 /* not word(... */
5676 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005677 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005678 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005679 }
5680#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005681 /* fall through */
5682 case '{': {
5683 int n = parse_group(&ctx, input, ch);
5684 if (n < 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005685 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005686 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005687 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5688 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005689 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005690 }
Eric Andersen25f27032001-04-26 23:22:31 +00005691 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005692#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005693 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005694 goto case_semi;
5695#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005696
Eric Andersen25f27032001-04-26 23:22:31 +00005697 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005698 /* proper use of this character is caught by end_trigger:
5699 * if we see {, we call parse_group(..., end_trigger='}')
5700 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005701 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005702 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005703 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005704 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005705 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005706 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005707 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005708 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005709
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005710 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005711 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005712 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005713 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005714 struct parse_context *pctx;
5715 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005716
5717 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005718 * Sample for finding leaks on syntax error recovery path.
5719 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005720 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005721 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005722 * while if (true | { true;}); then echo ok; fi; do break; done
5723 * 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 +00005724 */
5725 pctx = &ctx;
5726 do {
5727 /* Update pipe/command counts,
5728 * otherwise freeing may miss some */
5729 done_pipe(pctx, PIPE_SEQ);
5730 debug_printf_clean("freeing list %p from ctx %p\n",
5731 pctx->list_head, pctx);
5732 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005733 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005734 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005735#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005736 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005737#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005738 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005739 if (pctx != &ctx) {
5740 free(pctx);
5741 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005742 IF_HAS_KEYWORDS(pctx = p2;)
5743 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005744
Denys Vlasenko474cb202018-07-24 13:03:03 +02005745 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005746#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005747 if (pstring)
5748 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005749#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005750 debug_leave();
5751 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005752 }
Eric Andersen25f27032001-04-26 23:22:31 +00005753}
5754
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005755
5756/*** Execution routines ***/
5757
5758/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005759#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005760#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005761 expand_string_to_string(str)
5762#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005763static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005764#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005765static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005766#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005767static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005768
5769/* expand_strvec_to_strvec() takes a list of strings, expands
5770 * all variable references within and returns a pointer to
5771 * a list of expanded strings, possibly with larger number
5772 * of strings. (Think VAR="a b"; echo $VAR).
5773 * This new list is allocated as a single malloc block.
5774 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005775 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005776 * Caller can deallocate entire list by single free(list). */
5777
Denys Vlasenko238081f2010-10-03 14:26:26 +02005778/* A horde of its helpers come first: */
5779
5780static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5781{
5782 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005783 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005784
Denys Vlasenko9e800222010-10-03 14:28:04 +02005785#if ENABLE_HUSH_BRACE_EXPANSION
5786 if (c == '{' || c == '}') {
5787 /* { -> \{, } -> \} */
5788 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005789 /* And now we want to add { or } and continue:
5790 * o_addchr(o, c);
5791 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005792 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005793 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005794 }
5795#endif
5796 o_addchr(o, c);
5797 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005798 /* \z -> \\\z; \<eol> -> \\<eol> */
5799 o_addchr(o, '\\');
5800 if (len) {
5801 len--;
5802 o_addchr(o, '\\');
5803 o_addchr(o, *str++);
5804 }
5805 }
5806 }
5807}
5808
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005809/* Store given string, finalizing the word and starting new one whenever
5810 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005811 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005812 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005813 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5814 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005815static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005816{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005817 int last_is_ifs = 0;
5818
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005819 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005820 int word_len;
5821
5822 if (!*str) /* EOL - do not finalize word */
5823 break;
5824 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005825 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005826 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005827 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005828 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005829 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005830 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005831 * Example: "v='\*'; echo b$v" prints "b\*"
5832 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005833 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005834 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005835 /*/ Why can't we do it easier? */
5836 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5837 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5838 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005839 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005840 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005841 if (!*str) /* EOL - do not finalize word */
5842 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005843 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005844
5845 /* We know str here points to at least one IFS char */
5846 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005847 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005848 if (!*str) /* EOL - do not finalize word */
5849 break;
5850
Denys Vlasenko96786362018-04-11 16:02:58 +02005851 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5852 && strchr(G.ifs, *str) /* the second check would fail */
5853 ) {
5854 /* This is a non-whitespace $IFS char */
5855 /* Skip it and IFS whitespace chars, start new word */
5856 str++;
5857 str += strspn(str, G.ifs_whitespace);
5858 goto new_word;
5859 }
5860
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005861 /* Start new word... but not always! */
5862 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005863 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005864 /*
5865 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005866 * here nothing precedes the space in $v expansion,
5867 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005868 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005869 * It's okay if this accesses the byte before first argv[]:
5870 * past call to o_save_ptr() cleared it to zero byte
5871 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005872 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005873 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005874 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005875 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005876 o_addchr(output, '\0');
5877 debug_print_list("expand_on_ifs", output, n);
5878 n = o_save_ptr(output, n);
5879 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005880 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005881
Denys Vlasenko168579a2018-07-19 13:45:54 +02005882 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005883 debug_print_list("expand_on_ifs[1]", output, n);
5884 return n;
5885}
5886
5887/* Helper to expand $((...)) and heredoc body. These act as if
5888 * they are in double quotes, with the exception that they are not :).
5889 * Just the rules are similar: "expand only $var and `cmd`"
5890 *
5891 * Returns malloced string.
5892 * As an optimization, we return NULL if expansion is not needed.
5893 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005894static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005895{
5896 char *exp_str;
5897 struct in_str input;
5898 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005899 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005900
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005901 cp = str;
5902 for (;;) {
5903 if (!*cp) return NULL; /* string has no special chars */
5904 if (*cp == '$') break;
5905 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005906#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005907 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005908#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005909 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005910 }
5911
5912 /* We need to expand. Example:
5913 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5914 */
5915 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005916 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005917//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005918 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005919 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005920 EXP_FLAG_ESC_GLOB_CHARS,
5921 /*unbackslash:*/ 1
5922 );
5923 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02005924 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005925 return exp_str;
5926}
5927
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02005928static const char *first_special_char_in_vararg(const char *cp)
5929{
5930 for (;;) {
5931 if (!*cp) return NULL; /* string has no special chars */
5932 if (*cp == '$') return cp;
5933 if (*cp == '\\') return cp;
5934 if (*cp == '\'') return cp;
5935 if (*cp == '"') return cp;
5936#if ENABLE_HUSH_TICK
5937 if (*cp == '`') return cp;
5938#endif
5939 /* dquoted "${x:+ARG}" should not glob, therefore
5940 * '*' et al require some non-literal processing: */
5941 if (*cp == '*') return cp;
5942 if (*cp == '?') return cp;
5943 if (*cp == '[') return cp;
5944 cp++;
5945 }
5946}
5947
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005948/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5949 * These can contain single- and double-quoted strings,
5950 * and treated as if the ARG string is initially unquoted. IOW:
5951 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5952 * a dquoted string: "${var#"zz"}"), the difference only comes later
5953 * (word splitting and globbing of the ${var...} result).
5954 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005955#if !BASH_PATTERN_SUBST
5956#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5957 encode_then_expand_vararg(str, handle_squotes)
5958#endif
5959static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5960{
5961#if !BASH_PATTERN_SUBST
5962 const int do_unbackslash = 0;
5963#endif
5964 char *exp_str;
5965 struct in_str input;
5966 o_string dest = NULL_O_STRING;
5967
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02005968 if (!first_special_char_in_vararg(str)) {
5969 /* string has no special chars */
5970 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005971 }
5972
Denys Vlasenkob762c782018-07-17 14:21:38 +02005973 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005974 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005975 exp_str = NULL;
5976
5977 for (;;) {
5978 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005979
5980 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005981 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5982 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005983
5984 if (!dest.o_expflags) {
5985 if (ch == EOF)
5986 break;
5987 if (handle_squotes && ch == '\'') {
5988 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02005989 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005990 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005991 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005992 }
5993 if (ch == EOF) {
5994 syntax_error_unterm_ch('"');
5995 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005996 }
5997 if (ch == '"') {
5998 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5999 continue;
6000 }
6001 if (ch == '\\') {
6002 ch = i_getch(&input);
6003 if (ch == EOF) {
6004//example? error message? syntax_error_unterm_ch('"');
6005 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6006 goto ret;
6007 }
6008 o_addqchr(&dest, ch);
6009 continue;
6010 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006011 if (ch == '$') {
6012 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6013 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6014 goto ret;
6015 }
6016 continue;
6017 }
6018#if ENABLE_HUSH_TICK
6019 if (ch == '`') {
6020 //unsigned pos = dest->length;
6021 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6022 o_addchr(&dest, 0x80 | '`');
6023 if (!add_till_backquote(&dest, &input,
6024 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6025 )
6026 ) {
6027 goto ret; /* error */
6028 }
6029 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6030 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6031 continue;
6032 }
6033#endif
6034 o_addQchr(&dest, ch);
6035 } /* for (;;) */
6036
6037 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6038 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006039 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6040 do_unbackslash
6041 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006042 ret:
6043 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006044 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006045 return exp_str;
6046}
6047
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006048/* Expanding ARG in ${var+ARG}, ${var-ARG}
6049 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006050static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006051 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006052{
6053 struct in_str input;
6054 o_string dest = NULL_O_STRING;
6055
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006056 if (!first_special_char_in_vararg(str)
6057 && '\0' == str[strcspn(str, G.ifs)]
6058 ) {
6059 /* string has no special chars
6060 * && string has no $IFS chars
6061 */
6062 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006063 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006064
Denys Vlasenko294eb462018-07-20 16:18:59 +02006065 setup_string_in_str(&input, str);
6066
6067 for (;;) {
6068 int ch;
6069
6070 ch = i_getch(&input);
6071 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6072 __func__, ch, ch, dest.o_expflags);
6073
6074 if (!dest.o_expflags) {
6075 if (ch == EOF)
6076 break;
6077 if (!dquoted && strchr(G.ifs, ch)) {
6078 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6079 * do not assume we are at the start of the word (PREFIX above).
6080 */
6081 if (dest.data) {
6082 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006083 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006084 o_addchr(output, '\0');
6085 n = o_save_ptr(output, n); /* create next word */
6086 } else
6087 if (output->length != o_get_last_ptr(output, n)
6088 || output->has_quoted_part
6089 ) {
6090 /* For these cases:
6091 * f() { for i; do echo "|$i|"; done; }; x=x
6092 * f a${x:+ }b # 1st condition
6093 * |a|
6094 * |b|
6095 * f ""${x:+ }b # 2nd condition
6096 * ||
6097 * |b|
6098 */
6099 o_addchr(output, '\0');
6100 n = o_save_ptr(output, n); /* create next word */
6101 }
6102 continue;
6103 }
6104 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006105 if (!add_till_single_quote_dquoted(&dest, &input))
6106 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006107 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6108 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006109 continue;
6110 }
6111 }
6112 if (ch == EOF) {
6113 syntax_error_unterm_ch('"');
6114 goto ret; /* error */
6115 }
6116 if (ch == '"') {
6117 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006118 if (dest.o_expflags) {
6119 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6120 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6121 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006122 continue;
6123 }
6124 if (ch == '\\') {
6125 ch = i_getch(&input);
6126 if (ch == EOF) {
6127//example? error message? syntax_error_unterm_ch('"');
6128 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6129 goto ret;
6130 }
6131 o_addqchr(&dest, ch);
6132 continue;
6133 }
6134 if (ch == '$') {
6135 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6136 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6137 goto ret;
6138 }
6139 continue;
6140 }
6141#if ENABLE_HUSH_TICK
6142 if (ch == '`') {
6143 //unsigned pos = dest->length;
6144 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6145 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6146 if (!add_till_backquote(&dest, &input,
6147 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6148 )
6149 ) {
6150 goto ret; /* error */
6151 }
6152 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6153 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6154 continue;
6155 }
6156#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006157 if (dquoted) {
6158 /* Always glob-protect if in dquotes:
6159 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6160 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6161 */
6162 o_addqchr(&dest, ch);
6163 } else {
6164 /* Glob-protect only if char is quoted:
6165 * x=x; echo ${x:+/bin/c*} - prints many filenames
6166 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6167 */
6168 o_addQchr(&dest, ch);
6169 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006170 } /* for (;;) */
6171
6172 if (dest.data) {
6173 n = expand_vars_to_list(output, n, dest.data);
6174 }
6175 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006176 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006177 return n;
6178}
6179
Denys Vlasenko0b883582016-12-23 16:49:07 +01006180#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006181static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006182{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006183 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006184 arith_t res;
6185 char *exp_str;
6186
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006187 math_state.lookupvar = get_local_var_value;
6188 math_state.setvar = set_local_var_from_halves;
6189 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006190 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006191 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006192 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006193 if (errmsg_p)
6194 *errmsg_p = math_state.errmsg;
6195 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006196 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006197 return res;
6198}
6199#endif
6200
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006201#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006202/* ${var/[/]pattern[/repl]} helpers */
6203static char *strstr_pattern(char *val, const char *pattern, int *size)
6204{
6205 while (1) {
6206 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6207 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6208 if (end) {
6209 *size = end - val;
6210 return val;
6211 }
6212 if (*val == '\0')
6213 return NULL;
6214 /* Optimization: if "*pat" did not match the start of "string",
6215 * we know that "tring", "ring" etc will not match too:
6216 */
6217 if (pattern[0] == '*')
6218 return NULL;
6219 val++;
6220 }
6221}
6222static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6223{
6224 char *result = NULL;
6225 unsigned res_len = 0;
6226 unsigned repl_len = strlen(repl);
6227
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006228 /* Null pattern never matches, including if "var" is empty */
6229 if (!pattern[0])
6230 return result; /* NULL, no replaces happened */
6231
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006232 while (1) {
6233 int size;
6234 char *s = strstr_pattern(val, pattern, &size);
6235 if (!s)
6236 break;
6237
6238 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006239 strcpy(mempcpy(result + res_len, val, s - val), repl);
6240 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006241 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6242
6243 val = s + size;
6244 if (exp_op == '/')
6245 break;
6246 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006247 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006248 result = xrealloc(result, res_len + strlen(val) + 1);
6249 strcpy(result + res_len, val);
6250 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6251 }
6252 debug_printf_varexp("result:'%s'\n", result);
6253 return result;
6254}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006255#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006256
Denys Vlasenko168579a2018-07-19 13:45:54 +02006257static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006258 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006259{
6260 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6261 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6262 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6263 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006264 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006265 } else { /* quoted "$VAR" */
6266 output->has_quoted_part = 1;
6267 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6268 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6269 if (val && val[0])
6270 o_addQstr(output, val);
6271 }
6272 return n;
6273}
6274
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006275/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006276 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006277static NOINLINE int expand_one_var(o_string *output, int n,
6278 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006279{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006280 const char *val;
6281 char *to_be_freed;
6282 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006283 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006284 char exp_op;
6285 char exp_save = exp_save; /* for compiler */
6286 char *exp_saveptr; /* points to expansion operator */
6287 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006288 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006289
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006290 val = NULL;
6291 to_be_freed = NULL;
6292 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006293 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006294 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006295 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006296 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006297 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006298 exp_op = 0;
6299
Denys Vlasenkob762c782018-07-17 14:21:38 +02006300 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006301 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6302 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6303 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006304 ) {
6305 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006306 var++;
6307 exp_op = 'L';
6308 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006309 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006310 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006311 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006312 ) {
6313 /* ${?:0}, ${#[:]%0} etc */
6314 exp_saveptr = var + 1;
6315 } else {
6316 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6317 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6318 }
6319 exp_op = exp_save = *exp_saveptr;
6320 if (exp_op) {
6321 exp_word = exp_saveptr + 1;
6322 if (exp_op == ':') {
6323 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006324//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006325 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006326 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006327 ) {
6328 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6329 exp_op = ':';
6330 exp_word--;
6331 }
6332 }
6333 *exp_saveptr = '\0';
6334 } /* else: it's not an expansion op, but bare ${var} */
6335 }
6336
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006337 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006338 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006339 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006340 int nn = xatoi_positive(var);
6341 if (nn < G.global_argc)
6342 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006343 /* else val remains NULL: $N with too big N */
6344 } else {
6345 switch (var[0]) {
6346 case '$': /* pid */
6347 val = utoa(G.root_pid);
6348 break;
6349 case '!': /* bg pid */
6350 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6351 break;
6352 case '?': /* exitcode */
6353 val = utoa(G.last_exitcode);
6354 break;
6355 case '#': /* argc */
6356 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6357 break;
6358 default:
6359 val = get_local_var_value(var);
6360 }
6361 }
6362
6363 /* Handle any expansions */
6364 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006365 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006366 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006367 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006368 debug_printf_expand("%s\n", val);
6369 } else if (exp_op) {
6370 if (exp_op == '%' || exp_op == '#') {
6371 /* Standard-mandated substring removal ops:
6372 * ${parameter%word} - remove smallest suffix pattern
6373 * ${parameter%%word} - remove largest suffix pattern
6374 * ${parameter#word} - remove smallest prefix pattern
6375 * ${parameter##word} - remove largest prefix pattern
6376 *
6377 * Word is expanded to produce a glob pattern.
6378 * Then var's value is matched to it and matching part removed.
6379 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006380//FIXME: ${x#...${...}...}
6381//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6382//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006383 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006384 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006385 char *exp_exp_word;
6386 char *loc;
6387 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006388 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006389 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006390 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006391 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006392 if (exp_exp_word)
6393 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006394 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6395 /*
6396 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006397 * G.global_argv and results of utoa and get_local_var_value
6398 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006399 * scan_and_match momentarily stores NULs there.
6400 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006401 t = (char*)val;
6402 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006403 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 +02006404 free(exp_exp_word);
6405 if (loc) { /* match was found */
6406 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006407 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006408 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006409 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006410 }
6411 }
6412 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006413#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006414 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006415 /* It's ${var/[/]pattern[/repl]} thing.
6416 * Note that in encoded form it has TWO parts:
6417 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006418 * and if // is used, it is encoded as \:
6419 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006420 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006421 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006422 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006423 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006424 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006425 * >az >bz
6426 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6427 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6428 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6429 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006430 * (note that a*z _pattern_ is never globbed!)
6431 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006432 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006433 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006434 if (!pattern)
6435 pattern = xstrdup(exp_word);
6436 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6437 *p++ = SPECIAL_VAR_SYMBOL;
6438 exp_word = p;
6439 p = strchr(p, SPECIAL_VAR_SYMBOL);
6440 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006441 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006442 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6443 /* HACK ALERT. We depend here on the fact that
6444 * G.global_argv and results of utoa and get_local_var_value
6445 * are actually in writable memory:
6446 * replace_pattern momentarily stores NULs there. */
6447 t = (char*)val;
6448 to_be_freed = replace_pattern(t,
6449 pattern,
6450 (repl ? repl : exp_word),
6451 exp_op);
6452 if (to_be_freed) /* at least one replace happened */
6453 val = to_be_freed;
6454 free(pattern);
6455 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006456 } else {
6457 /* Empty variable always gives nothing */
6458 // "v=''; echo ${v/*/w}" prints "", not "w"
6459 /* Just skip "replace" part */
6460 *p++ = SPECIAL_VAR_SYMBOL;
6461 p = strchr(p, SPECIAL_VAR_SYMBOL);
6462 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006463 }
6464 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006465#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006466 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006467#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006468 /* It's ${var:N[:M]} bashism.
6469 * Note that in encoded form it has TWO parts:
6470 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6471 */
6472 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006473 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006474
Denys Vlasenko063847d2010-09-15 13:33:02 +02006475 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6476 if (errmsg)
6477 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006478 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6479 *p++ = SPECIAL_VAR_SYMBOL;
6480 exp_word = p;
6481 p = strchr(p, SPECIAL_VAR_SYMBOL);
6482 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006483 len = expand_and_evaluate_arith(exp_word, &errmsg);
6484 if (errmsg)
6485 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006486 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006487 if (beg < 0) {
6488 /* negative beg counts from the end */
6489 beg = (arith_t)strlen(val) + beg;
6490 if (beg < 0) /* ${v: -999999} is "" */
6491 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006492 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006493 debug_printf_varexp("from val:'%s'\n", val);
6494 if (len < 0) {
6495 /* in bash, len=-n means strlen()-n */
6496 len = (arith_t)strlen(val) - beg + len;
6497 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006498 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006499 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006500 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006501 arith_err:
6502 val = NULL;
6503 } else {
6504 /* Paranoia. What if user entered 9999999999999
6505 * which fits in arith_t but not int? */
6506 if (len >= INT_MAX)
6507 len = INT_MAX;
6508 val = to_be_freed = xstrndup(val + beg, len);
6509 }
6510 debug_printf_varexp("val:'%s'\n", val);
6511#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006512 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006513 val = NULL;
6514#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006515 } else { /* one of "-=+?" */
6516 /* Standard-mandated substitution ops:
6517 * ${var?word} - indicate error if unset
6518 * If var is unset, word (or a message indicating it is unset
6519 * if word is null) is written to standard error
6520 * and the shell exits with a non-zero exit status.
6521 * Otherwise, the value of var is substituted.
6522 * ${var-word} - use default value
6523 * If var is unset, word is substituted.
6524 * ${var=word} - assign and use default value
6525 * If var is unset, word is assigned to var.
6526 * In all cases, final value of var is substituted.
6527 * ${var+word} - use alternative value
6528 * If var is unset, null is substituted.
6529 * Otherwise, word is substituted.
6530 *
6531 * Word is subjected to tilde expansion, parameter expansion,
6532 * command substitution, and arithmetic expansion.
6533 * If word is not needed, it is not expanded.
6534 *
6535 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6536 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006537 *
6538 * Word-splitting and single quote behavior:
6539 *
6540 * $ f() { for i; do echo "|$i|"; done; };
6541 *
6542 * $ x=; f ${x:?'x y' z}
6543 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6544 * $ x=; f "${x:?'x y' z}"
6545 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6546 *
6547 * $ x=; f ${x:='x y' z}
6548 * |x|
6549 * |y|
6550 * |z|
6551 * $ x=; f "${x:='x y' z}"
6552 * |'x y' z|
6553 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006554 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006555 * |x y|
6556 * |z|
6557 * $ x=x; f "${x:+'x y' z}"
6558 * |'x y' z|
6559 *
6560 * $ x=; f ${x:-'x y' z}
6561 * |x y|
6562 * |z|
6563 * $ x=; f "${x:-'x y' z}"
6564 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006565 */
6566 int use_word = (!val || ((exp_save == ':') && !val[0]));
6567 if (exp_op == '+')
6568 use_word = !use_word;
6569 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6570 (exp_save == ':') ? "true" : "false", use_word);
6571 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006572 if (exp_op == '+' || exp_op == '-') {
6573 /* ${var+word} - use alternative value */
6574 /* ${var-word} - use default value */
6575 n = encode_then_append_var_plusminus(output, n, exp_word,
6576 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006577 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006578 val = NULL;
6579 } else {
6580 /* ${var?word} - indicate error if unset */
6581 /* ${var=word} - assign and use default value */
6582 to_be_freed = encode_then_expand_vararg(exp_word,
6583 /*handle_squotes:*/ !(arg0 & 0x80),
6584 /*unbackslash:*/ 0
6585 );
6586 if (to_be_freed)
6587 exp_word = to_be_freed;
6588 if (exp_op == '?') {
6589 /* mimic bash message */
6590 msg_and_die_if_script("%s: %s",
6591 var,
6592 exp_word[0]
6593 ? exp_word
6594 : "parameter null or not set"
6595 /* ash has more specific messages, a-la: */
6596 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6597 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006598//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006599//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006600// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6601// bash: x: x y z
6602// $
6603// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006604 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006605 val = exp_word;
6606 }
6607 if (exp_op == '=') {
6608 /* ${var=[word]} or ${var:=[word]} */
6609 if (isdigit(var[0]) || var[0] == '#') {
6610 /* mimic bash message */
6611 msg_and_die_if_script("$%s: cannot assign in this way", var);
6612 val = NULL;
6613 } else {
6614 char *new_var = xasprintf("%s=%s", var, val);
6615 set_local_var(new_var, /*flag:*/ 0);
6616 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006617 }
6618 }
6619 }
6620 } /* one of "-=+?" */
6621
6622 *exp_saveptr = exp_save;
6623 } /* if (exp_op) */
6624
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006625 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006626 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006627
Denys Vlasenko168579a2018-07-19 13:45:54 +02006628 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006629
6630 free(to_be_freed);
6631 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006632}
6633
6634/* Expand all variable references in given string, adding words to list[]
6635 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6636 * to be filled). This routine is extremely tricky: has to deal with
6637 * variables/parameters with whitespace, $* and $@, and constructs like
6638 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006639static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006640{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006641 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006642 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006643 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006644 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006645 char *p;
6646
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006647 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6648 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006649 debug_print_list("expand_vars_to_list[0]", output, n);
6650
6651 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6652 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006653#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006654 char arith_buf[sizeof(arith_t)*3 + 2];
6655#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006656
Denys Vlasenko168579a2018-07-19 13:45:54 +02006657 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006658 o_addchr(output, '\0');
6659 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006660 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006661 }
6662
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006663 o_addblock(output, arg, p - arg);
6664 debug_print_list("expand_vars_to_list[1]", output, n);
6665 arg = ++p;
6666 p = strchr(p, SPECIAL_VAR_SYMBOL);
6667
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006668 /* Fetch special var name (if it is indeed one of them)
6669 * and quote bit, force the bit on if singleword expansion -
6670 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006671 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006672
6673 /* Is this variable quoted and thus expansion can't be null?
6674 * "$@" is special. Even if quoted, it can still
6675 * expand to nothing (not even an empty string),
6676 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006677 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006678 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006679
6680 switch (first_ch & 0x7f) {
6681 /* Highest bit in first_ch indicates that var is double-quoted */
6682 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006683 case '@': {
6684 int i;
6685 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006686 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006687 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006688 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006689 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006690 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006691 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006692 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6693 if (G.global_argv[i++][0] && G.global_argv[i]) {
6694 /* this argv[] is not empty and not last:
6695 * put terminating NUL, start new word */
6696 o_addchr(output, '\0');
6697 debug_print_list("expand_vars_to_list[2]", output, n);
6698 n = o_save_ptr(output, n);
6699 debug_print_list("expand_vars_to_list[3]", output, n);
6700 }
6701 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006702 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006703 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006704 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006705 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006706 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006707 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006708 while (1) {
6709 o_addQstr(output, G.global_argv[i]);
6710 if (++i >= G.global_argc)
6711 break;
6712 o_addchr(output, '\0');
6713 debug_print_list("expand_vars_to_list[4]", output, n);
6714 n = o_save_ptr(output, n);
6715 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006716 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006717 while (1) {
6718 o_addQstr(output, G.global_argv[i]);
6719 if (!G.global_argv[++i])
6720 break;
6721 if (G.ifs[0])
6722 o_addchr(output, G.ifs[0]);
6723 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006724 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006725 }
6726 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006727 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006728 case SPECIAL_VAR_SYMBOL: {
6729 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006730 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006731 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006732 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006733 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006734 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006735 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006736 case SPECIAL_VAR_QUOTED_SVS:
6737 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006738 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006739 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006740 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006741 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006742#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006743 case '`': {
6744 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006745 o_string subst_result = NULL_O_STRING;
6746
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006747 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006748 arg++;
6749 /* Can't just stuff it into output o_string,
6750 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006751 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006752 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6753 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006754 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006755 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006756 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006757 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006758 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006759 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006760#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006761#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006762 case '+': {
6763 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006764 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006765
6766 arg++; /* skip '+' */
6767 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6768 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006769 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006770 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6771 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006772 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006773 break;
6774 }
6775#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006776 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006777 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006778 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006779 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006780 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6781
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006782 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6783 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006784 if (*p != SPECIAL_VAR_SYMBOL)
6785 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006786 arg = ++p;
6787 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6788
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006789 if (*arg) {
6790 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006791 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006792 o_addchr(output, '\0');
6793 n = o_save_ptr(output, n);
6794 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006795 debug_print_list("expand_vars_to_list[a]", output, n);
6796 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006797 * if needed (much earlier), do not use o_addQstr here!
6798 */
6799 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006800 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006801 } else
6802 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006803 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6804 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006805 ) {
6806 n--;
6807 /* allow to reuse list[n] later without re-growth */
6808 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006809 }
6810
6811 return n;
6812}
6813
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006814static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006815{
6816 int n;
6817 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006818 o_string output = NULL_O_STRING;
6819
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006820 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006821
6822 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006823 for (;;) {
6824 /* go to next list[n] */
6825 output.ended_in_ifs = 0;
6826 n = o_save_ptr(&output, n);
6827
6828 if (!*argv)
6829 break;
6830
6831 /* expand argv[i] */
6832 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006833 /* if (!output->has_empty_slot) -- need this?? */
6834 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006835 }
6836 debug_print_list("expand_variables", &output, n);
6837
6838 /* output.data (malloced in one block) gets returned in "list" */
6839 list = o_finalize_list(&output, n);
6840 debug_print_strings("expand_variables[1]", list);
6841 return list;
6842}
6843
6844static char **expand_strvec_to_strvec(char **argv)
6845{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006846 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006847}
6848
Denys Vlasenko11752d42018-04-03 08:20:58 +02006849#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006850static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6851{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006852 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006853}
6854#endif
6855
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006856/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006857 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006858 *
6859 * NB: should NOT do globbing!
6860 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6861 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006862static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006863{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006864#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006865 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006866 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006867#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006868 char *argv[2], **list;
6869
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006870 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006871 /* This is generally an optimization, but it also
6872 * handles "", which otherwise trips over !list[0] check below.
6873 * (is this ever happens that we actually get str="" here?)
6874 */
6875 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6876 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006877 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006878 return xstrdup(str);
6879 }
6880
6881 argv[0] = (char*)str;
6882 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006883 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006884 if (!list[0]) {
6885 /* Example where it happens:
6886 * x=; echo ${x:-"$@"}
6887 */
6888 ((char*)list)[0] = '\0';
6889 } else {
6890 if (HUSH_DEBUG)
6891 if (list[1])
6892 bb_error_msg_and_die("BUG in varexp2");
6893 /* actually, just move string 2*sizeof(char*) bytes back */
6894 overlapping_strcpy((char*)list, list[0]);
6895 if (do_unbackslash)
6896 unbackslash((char*)list);
6897 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006898 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006899 return (char*)list;
6900}
6901
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006902#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006903static char* expand_strvec_to_string(char **argv)
6904{
6905 char **list;
6906
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006907 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006908 /* Convert all NULs to spaces */
6909 if (list[0]) {
6910 int n = 1;
6911 while (list[n]) {
6912 if (HUSH_DEBUG)
6913 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6914 bb_error_msg_and_die("BUG in varexp3");
6915 /* bash uses ' ' regardless of $IFS contents */
6916 list[n][-1] = ' ';
6917 n++;
6918 }
6919 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006920 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006921 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6922 return (char*)list;
6923}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006924#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006925
6926static char **expand_assignments(char **argv, int count)
6927{
6928 int i;
6929 char **p;
6930
6931 G.expanded_assignments = p = NULL;
6932 /* Expand assignments into one string each */
6933 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006934 p = add_string_to_strings(p,
6935 expand_string_to_string(argv[i],
6936 EXP_FLAG_ESC_GLOB_CHARS,
6937 /*unbackslash:*/ 1
6938 )
6939 );
6940 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006941 }
6942 G.expanded_assignments = NULL;
6943 return p;
6944}
6945
6946
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006947static void switch_off_special_sigs(unsigned mask)
6948{
6949 unsigned sig = 0;
6950 while ((mask >>= 1) != 0) {
6951 sig++;
6952 if (!(mask & 1))
6953 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006954#if ENABLE_HUSH_TRAP
6955 if (G_traps) {
6956 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006957 /* trap is '', has to remain SIG_IGN */
6958 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006959 free(G_traps[sig]);
6960 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006961 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006962#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006963 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006964 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006965 }
6966}
6967
Denys Vlasenkob347df92011-08-09 22:49:15 +02006968#if BB_MMU
6969/* never called */
6970void re_execute_shell(char ***to_free, const char *s,
6971 char *g_argv0, char **g_argv,
6972 char **builtin_argv) NORETURN;
6973
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006974static void reset_traps_to_defaults(void)
6975{
6976 /* This function is always called in a child shell
6977 * after fork (not vfork, NOMMU doesn't use this function).
6978 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006979 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006980 unsigned mask;
6981
6982 /* Child shells are not interactive.
6983 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6984 * Testcase: (while :; do :; done) + ^Z should background.
6985 * Same goes for SIGTERM, SIGHUP, SIGINT.
6986 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006987 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006988 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006989 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006990
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006991 /* Switch off special sigs */
6992 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006993# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006994 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006995# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006996 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006997 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6998 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006999
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007000# if ENABLE_HUSH_TRAP
7001 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007002 return;
7003
7004 /* Reset all sigs to default except ones with empty traps */
7005 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007006 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007007 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007008 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007009 continue; /* empty trap: has to remain SIG_IGN */
7010 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007011 free(G_traps[sig]);
7012 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007013 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007014 if (sig == 0)
7015 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007016 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007017 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007018# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007019}
7020
7021#else /* !BB_MMU */
7022
7023static void re_execute_shell(char ***to_free, const char *s,
7024 char *g_argv0, char **g_argv,
7025 char **builtin_argv) NORETURN;
7026static void re_execute_shell(char ***to_free, const char *s,
7027 char *g_argv0, char **g_argv,
7028 char **builtin_argv)
7029{
7030# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7031 /* delims + 2 * (number of bytes in printed hex numbers) */
7032 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7033 char *heredoc_argv[4];
7034 struct variable *cur;
7035# if ENABLE_HUSH_FUNCTIONS
7036 struct function *funcp;
7037# endif
7038 char **argv, **pp;
7039 unsigned cnt;
7040 unsigned long long empty_trap_mask;
7041
7042 if (!g_argv0) { /* heredoc */
7043 argv = heredoc_argv;
7044 argv[0] = (char *) G.argv0_for_re_execing;
7045 argv[1] = (char *) "-<";
7046 argv[2] = (char *) s;
7047 argv[3] = NULL;
7048 pp = &argv[3]; /* used as pointer to empty environment */
7049 goto do_exec;
7050 }
7051
7052 cnt = 0;
7053 pp = builtin_argv;
7054 if (pp) while (*pp++)
7055 cnt++;
7056
7057 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007058 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007059 int sig;
7060 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007061 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007062 empty_trap_mask |= 1LL << sig;
7063 }
7064 }
7065
7066 sprintf(param_buf, NOMMU_HACK_FMT
7067 , (unsigned) G.root_pid
7068 , (unsigned) G.root_ppid
7069 , (unsigned) G.last_bg_pid
7070 , (unsigned) G.last_exitcode
7071 , cnt
7072 , empty_trap_mask
7073 IF_HUSH_LOOPS(, G.depth_of_loop)
7074 );
7075# undef NOMMU_HACK_FMT
7076 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7077 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7078 */
7079 cnt += 6;
7080 for (cur = G.top_var; cur; cur = cur->next) {
7081 if (!cur->flg_export || cur->flg_read_only)
7082 cnt += 2;
7083 }
7084# if ENABLE_HUSH_FUNCTIONS
7085 for (funcp = G.top_func; funcp; funcp = funcp->next)
7086 cnt += 3;
7087# endif
7088 pp = g_argv;
7089 while (*pp++)
7090 cnt++;
7091 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7092 *pp++ = (char *) G.argv0_for_re_execing;
7093 *pp++ = param_buf;
7094 for (cur = G.top_var; cur; cur = cur->next) {
7095 if (strcmp(cur->varstr, hush_version_str) == 0)
7096 continue;
7097 if (cur->flg_read_only) {
7098 *pp++ = (char *) "-R";
7099 *pp++ = cur->varstr;
7100 } else if (!cur->flg_export) {
7101 *pp++ = (char *) "-V";
7102 *pp++ = cur->varstr;
7103 }
7104 }
7105# if ENABLE_HUSH_FUNCTIONS
7106 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7107 *pp++ = (char *) "-F";
7108 *pp++ = funcp->name;
7109 *pp++ = funcp->body_as_string;
7110 }
7111# endif
7112 /* We can pass activated traps here. Say, -Tnn:trap_string
7113 *
7114 * However, POSIX says that subshells reset signals with traps
7115 * to SIG_DFL.
7116 * I tested bash-3.2 and it not only does that with true subshells
7117 * of the form ( list ), but with any forked children shells.
7118 * I set trap "echo W" WINCH; and then tried:
7119 *
7120 * { echo 1; sleep 20; echo 2; } &
7121 * while true; do echo 1; sleep 20; echo 2; break; done &
7122 * true | { echo 1; sleep 20; echo 2; } | cat
7123 *
7124 * In all these cases sending SIGWINCH to the child shell
7125 * did not run the trap. If I add trap "echo V" WINCH;
7126 * _inside_ group (just before echo 1), it works.
7127 *
7128 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007129 */
7130 *pp++ = (char *) "-c";
7131 *pp++ = (char *) s;
7132 if (builtin_argv) {
7133 while (*++builtin_argv)
7134 *pp++ = *builtin_argv;
7135 *pp++ = (char *) "";
7136 }
7137 *pp++ = g_argv0;
7138 while (*g_argv)
7139 *pp++ = *g_argv++;
7140 /* *pp = NULL; - is already there */
7141 pp = environ;
7142
7143 do_exec:
7144 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007145 /* Don't propagate SIG_IGN to the child */
7146 if (SPECIAL_JOBSTOP_SIGS != 0)
7147 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007148 execve(bb_busybox_exec_path, argv, pp);
7149 /* Fallback. Useful for init=/bin/hush usage etc */
7150 if (argv[0][0] == '/')
7151 execve(argv[0], argv, pp);
7152 xfunc_error_retval = 127;
7153 bb_error_msg_and_die("can't re-execute the shell");
7154}
7155#endif /* !BB_MMU */
7156
7157
7158static int run_and_free_list(struct pipe *pi);
7159
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007160/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007161 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7162 * end_trigger controls how often we stop parsing
7163 * NUL: parse all, execute, return
7164 * ';': parse till ';' or newline, execute, repeat till EOF
7165 */
7166static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007167{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007168 /* Why we need empty flag?
7169 * An obscure corner case "false; ``; echo $?":
7170 * empty command in `` should still set $? to 0.
7171 * But we can't just set $? to 0 at the start,
7172 * this breaks "false; echo `echo $?`" case.
7173 */
7174 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007175 while (1) {
7176 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007177
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007178#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007179 if (end_trigger == ';') {
7180 G.promptmode = 0; /* PS1 */
7181 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7182 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007183#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007184 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007185 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7186 /* If we are in "big" script
7187 * (not in `cmd` or something similar)...
7188 */
7189 if (pipe_list == ERR_PTR && end_trigger == ';') {
7190 /* Discard cached input (rest of line) */
7191 int ch = inp->last_char;
7192 while (ch != EOF && ch != '\n') {
7193 //bb_error_msg("Discarded:'%c'", ch);
7194 ch = i_getch(inp);
7195 }
7196 /* Force prompt */
7197 inp->p = NULL;
7198 /* This stream isn't empty */
7199 empty = 0;
7200 continue;
7201 }
7202 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007203 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007204 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007205 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007206 debug_print_tree(pipe_list, 0);
7207 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7208 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007209 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007210 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007211 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007212 }
Eric Andersen25f27032001-04-26 23:22:31 +00007213}
7214
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007215static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007216{
7217 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007218 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
7219
Eric Andersen25f27032001-04-26 23:22:31 +00007220 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007221 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007222 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007223}
7224
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007225static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007226{
Eric Andersen25f27032001-04-26 23:22:31 +00007227 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007228 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007229
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007230 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007231 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007232 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007233 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007234}
7235
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007236#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007237static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007238{
7239 pid_t pid;
7240 int channel[2];
7241# if !BB_MMU
7242 char **to_free = NULL;
7243# endif
7244
7245 xpipe(channel);
7246 pid = BB_MMU ? xfork() : xvfork();
7247 if (pid == 0) { /* child */
7248 disable_restore_tty_pgrp_on_exit();
7249 /* Process substitution is not considered to be usual
7250 * 'command execution'.
7251 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7252 */
7253 bb_signals(0
7254 + (1 << SIGTSTP)
7255 + (1 << SIGTTIN)
7256 + (1 << SIGTTOU)
7257 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007258 close(channel[0]); /* NB: close _first_, then move fd! */
7259 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007260# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007261 /* Awful hack for `trap` or $(trap).
7262 *
7263 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7264 * contains an example where "trap" is executed in a subshell:
7265 *
7266 * save_traps=$(trap)
7267 * ...
7268 * eval "$save_traps"
7269 *
7270 * Standard does not say that "trap" in subshell shall print
7271 * parent shell's traps. It only says that its output
7272 * must have suitable form, but then, in the above example
7273 * (which is not supposed to be normative), it implies that.
7274 *
7275 * bash (and probably other shell) does implement it
7276 * (traps are reset to defaults, but "trap" still shows them),
7277 * but as a result, "trap" logic is hopelessly messed up:
7278 *
7279 * # trap
7280 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7281 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7282 * # true | trap <--- trap is in subshell - no output (ditto)
7283 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7284 * trap -- 'echo Ho' SIGWINCH
7285 * # echo `(trap)` <--- in subshell in subshell - output
7286 * trap -- 'echo Ho' SIGWINCH
7287 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7288 * trap -- 'echo Ho' SIGWINCH
7289 *
7290 * The rules when to forget and when to not forget traps
7291 * get really complex and nonsensical.
7292 *
7293 * Our solution: ONLY bare $(trap) or `trap` is special.
7294 */
7295 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007296 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007297 && skip_whitespace(s + 4)[0] == '\0'
7298 ) {
7299 static const char *const argv[] = { NULL, NULL };
7300 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007301 fflush_all(); /* important */
7302 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007303 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007304# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007305# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007306 /* Prevent it from trying to handle ctrl-z etc */
7307 IF_HUSH_JOB(G.run_list_level = 1;)
7308 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007309 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007310 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007311 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007312 parse_and_run_string(s);
7313 _exit(G.last_exitcode);
7314# else
7315 /* We re-execute after vfork on NOMMU. This makes this script safe:
7316 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7317 * huge=`cat BIG` # was blocking here forever
7318 * echo OK
7319 */
7320 re_execute_shell(&to_free,
7321 s,
7322 G.global_argv[0],
7323 G.global_argv + 1,
7324 NULL);
7325# endif
7326 }
7327
7328 /* parent */
7329 *pid_p = pid;
7330# if ENABLE_HUSH_FAST
7331 G.count_SIGCHLD++;
7332//bb_error_msg("[%d] fork in generate_stream_from_string:"
7333// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7334// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7335# endif
7336 enable_restore_tty_pgrp_on_exit();
7337# if !BB_MMU
7338 free(to_free);
7339# endif
7340 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007341 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007342}
7343
7344/* Return code is exit status of the process that is run. */
7345static int process_command_subs(o_string *dest, const char *s)
7346{
7347 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007348 pid_t pid;
7349 int status, ch, eol_cnt;
7350
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007351 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007352
7353 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007354 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007355 while ((ch = getc(fp)) != EOF) {
7356 if (ch == '\0')
7357 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007358 if (ch == '\n') {
7359 eol_cnt++;
7360 continue;
7361 }
7362 while (eol_cnt) {
7363 o_addchr(dest, '\n');
7364 eol_cnt--;
7365 }
7366 o_addQchr(dest, ch);
7367 }
7368
7369 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007370 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007371 /* We need to extract exitcode. Test case
7372 * "true; echo `sleep 1; false` $?"
7373 * should print 1 */
7374 safe_waitpid(pid, &status, 0);
7375 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7376 return WEXITSTATUS(status);
7377}
7378#endif /* ENABLE_HUSH_TICK */
7379
7380
7381static void setup_heredoc(struct redir_struct *redir)
7382{
7383 struct fd_pair pair;
7384 pid_t pid;
7385 int len, written;
7386 /* the _body_ of heredoc (misleading field name) */
7387 const char *heredoc = redir->rd_filename;
7388 char *expanded;
7389#if !BB_MMU
7390 char **to_free;
7391#endif
7392
7393 expanded = NULL;
7394 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007395 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007396 if (expanded)
7397 heredoc = expanded;
7398 }
7399 len = strlen(heredoc);
7400
7401 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7402 xpiped_pair(pair);
7403 xmove_fd(pair.rd, redir->rd_fd);
7404
7405 /* Try writing without forking. Newer kernels have
7406 * dynamically growing pipes. Must use non-blocking write! */
7407 ndelay_on(pair.wr);
7408 while (1) {
7409 written = write(pair.wr, heredoc, len);
7410 if (written <= 0)
7411 break;
7412 len -= written;
7413 if (len == 0) {
7414 close(pair.wr);
7415 free(expanded);
7416 return;
7417 }
7418 heredoc += written;
7419 }
7420 ndelay_off(pair.wr);
7421
7422 /* Okay, pipe buffer was not big enough */
7423 /* Note: we must not create a stray child (bastard? :)
7424 * for the unsuspecting parent process. Child creates a grandchild
7425 * and exits before parent execs the process which consumes heredoc
7426 * (that exec happens after we return from this function) */
7427#if !BB_MMU
7428 to_free = NULL;
7429#endif
7430 pid = xvfork();
7431 if (pid == 0) {
7432 /* child */
7433 disable_restore_tty_pgrp_on_exit();
7434 pid = BB_MMU ? xfork() : xvfork();
7435 if (pid != 0)
7436 _exit(0);
7437 /* grandchild */
7438 close(redir->rd_fd); /* read side of the pipe */
7439#if BB_MMU
7440 full_write(pair.wr, heredoc, len); /* may loop or block */
7441 _exit(0);
7442#else
7443 /* Delegate blocking writes to another process */
7444 xmove_fd(pair.wr, STDOUT_FILENO);
7445 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7446#endif
7447 }
7448 /* parent */
7449#if ENABLE_HUSH_FAST
7450 G.count_SIGCHLD++;
7451//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7452#endif
7453 enable_restore_tty_pgrp_on_exit();
7454#if !BB_MMU
7455 free(to_free);
7456#endif
7457 close(pair.wr);
7458 free(expanded);
7459 wait(NULL); /* wait till child has died */
7460}
7461
Denys Vlasenko2db74612017-07-07 22:07:28 +02007462struct squirrel {
7463 int orig_fd;
7464 int moved_to;
7465 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7466 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7467};
7468
Denys Vlasenko621fc502017-07-24 12:42:17 +02007469static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7470{
7471 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7472 sq[i].orig_fd = orig;
7473 sq[i].moved_to = moved;
7474 sq[i+1].orig_fd = -1; /* end marker */
7475 return sq;
7476}
7477
Denys Vlasenko2db74612017-07-07 22:07:28 +02007478static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7479{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007480 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007481 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007482
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007483 i = 0;
7484 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007485 /* If we collide with an already moved fd... */
7486 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007487 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007488 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7489 if (sq[i].moved_to < 0) /* what? */
7490 xfunc_die();
7491 return sq;
7492 }
7493 if (fd == sq[i].orig_fd) {
7494 /* Example: echo Hello >/dev/null 1>&2 */
7495 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7496 return sq;
7497 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007498 }
7499
Denys Vlasenko2db74612017-07-07 22:07:28 +02007500 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007501 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007502 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7503 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007504 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007505 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007506}
7507
Denys Vlasenko657e9002017-07-30 23:34:04 +02007508static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7509{
7510 int i;
7511
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007512 i = 0;
7513 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007514 /* If we collide with an already moved fd... */
7515 if (fd == sq[i].orig_fd) {
7516 /* Examples:
7517 * "echo 3>FILE 3>&- 3>FILE"
7518 * "echo 3>&- 3>FILE"
7519 * No need for last redirect to insert
7520 * another "need to close 3" indicator.
7521 */
7522 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7523 return sq;
7524 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007525 }
7526
7527 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7528 return append_squirrel(sq, i, fd, -1);
7529}
7530
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007531/* fd: redirect wants this fd to be used (e.g. 3>file).
7532 * Move all conflicting internally used fds,
7533 * and remember them so that we can restore them later.
7534 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007535static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007536{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007537 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7538 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007539
7540#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007541 if (fd == G.interactive_fd) {
7542 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007543 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007544 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7545 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007546 }
7547#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007548 /* Are we called from setup_redirects(squirrel==NULL)
7549 * in redirect in a [v]forked child?
7550 */
7551 if (sqp == NULL) {
7552 /* No need to move script fds.
7553 * For NOMMU case, it's actively wrong: we'd change ->fd
7554 * fields in memory for the parent, but parent's fds
7555 * aren't be moved, it would use wrong fd!
7556 * Reproducer: "cmd 3>FILE" in script.
7557 * If we would call move_HFILEs_on_redirect(), child would:
7558 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7559 * close(3) = 0
7560 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7561 */
7562 //bb_error_msg("sqp == NULL: [v]forked child");
7563 return 0;
7564 }
7565
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007566 /* If this one of script's fds? */
7567 if (move_HFILEs_on_redirect(fd, avoid_fd))
7568 return 1; /* yes. "we closed fd" (actually moved it) */
7569
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007570 /* Are we called for "exec 3>FILE"? Came through
7571 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7572 * This case used to fail for this script:
7573 * exec 3>FILE
7574 * echo Ok
7575 * ...100000 more lines...
7576 * echo Ok
7577 * as follows:
7578 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7579 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7580 * dup2(4, 3) = 3
7581 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7582 * close(4) = 0
7583 * write(1, "Ok\n", 3) = 3
7584 * ... = 3
7585 * write(1, "Ok\n", 3) = 3
7586 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7587 * ^^^^^^^^ oops, wrong fd!!!
7588 * With this case separate from sqp == NULL and *after* move_HFILEs,
7589 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007590 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007591 if (sqp == ERR_PTR) {
7592 /* Don't preserve redirected fds: exec is _meant_ to change these */
7593 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007594 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007595 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007596
Denys Vlasenko2db74612017-07-07 22:07:28 +02007597 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7598 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7599 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007600}
7601
Denys Vlasenko2db74612017-07-07 22:07:28 +02007602static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007603{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007604 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007605 int i;
7606 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007607 if (sq[i].moved_to >= 0) {
7608 /* We simply die on error */
7609 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7610 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7611 } else {
7612 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7613 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7614 close(sq[i].orig_fd);
7615 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007616 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007617 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007618 }
7619
Denys Vlasenko2db74612017-07-07 22:07:28 +02007620 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007621}
7622
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007623#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007624static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007625{
7626 if (G_interactive_fd)
7627 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007628 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007629}
7630#endif
7631
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007632static int internally_opened_fd(int fd, struct squirrel *sq)
7633{
7634 int i;
7635
7636#if ENABLE_HUSH_INTERACTIVE
7637 if (fd == G.interactive_fd)
7638 return 1;
7639#endif
7640 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007641 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007642 return 1;
7643
7644 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7645 if (fd == sq[i].moved_to)
7646 return 1;
7647 }
7648 return 0;
7649}
7650
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007651/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7652 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007653static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007654{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007655 struct redir_struct *redir;
7656
7657 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007658 int newfd;
7659 int closed;
7660
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007661 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007662 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007663 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007664 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7665 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007666 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007667 redir->rd_filename);
7668 setup_heredoc(redir);
7669 continue;
7670 }
7671
7672 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007673 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007674 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007675 int mode;
7676
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007677 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007678 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007679 * "cmd >" (no filename)
7680 * "cmd > <file" (2nd redirect starts too early)
7681 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007682 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007683 continue;
7684 }
7685 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007686 p = expand_string_to_string(redir->rd_filename,
7687 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007688 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007689 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007690 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007691 /* Error message from open_or_warn can be lost
7692 * if stderr has been redirected, but bash
7693 * and ash both lose it as well
7694 * (though zsh doesn't!)
7695 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007696 return 1;
7697 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007698 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007699 /* open() gave us precisely the fd we wanted.
7700 * This means that this fd was not busy
7701 * (not opened to anywhere).
7702 * Remember to close it on restore:
7703 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007704 *sqp = add_squirrel_closed(*sqp, newfd);
7705 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007706 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007707 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007708 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7709 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007710 }
7711
Denys Vlasenko657e9002017-07-30 23:34:04 +02007712 if (newfd == redir->rd_fd)
7713 continue;
7714
7715 /* if "N>FILE": move newfd to redir->rd_fd */
7716 /* if "N>&M": dup newfd to redir->rd_fd */
7717 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7718
7719 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7720 if (newfd == REDIRFD_CLOSE) {
7721 /* "N>&-" means "close me" */
7722 if (!closed) {
7723 /* ^^^ optimization: saving may already
7724 * have closed it. If not... */
7725 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007726 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007727 /* Sometimes we do another close on restore, getting EBADF.
7728 * Consider "echo 3>FILE 3>&-"
7729 * first redirect remembers "need to close 3",
7730 * and second redirect closes 3! Restore code then closes 3 again.
7731 */
7732 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007733 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007734 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007735 //errno = EBADF;
7736 //bb_perror_msg_and_die("can't duplicate file descriptor");
7737 newfd = -1; /* same effect as code above */
7738 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007739 xdup2(newfd, redir->rd_fd);
7740 if (redir->rd_dup == REDIRFD_TO_FILE)
7741 /* "rd_fd > FILE" */
7742 close(newfd);
7743 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007744 }
7745 }
7746 return 0;
7747}
7748
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007749static char *find_in_path(const char *arg)
7750{
7751 char *ret = NULL;
7752 const char *PATH = get_local_var_value("PATH");
7753
7754 if (!PATH)
7755 return NULL;
7756
7757 while (1) {
7758 const char *end = strchrnul(PATH, ':');
7759 int sz = end - PATH; /* must be int! */
7760
7761 free(ret);
7762 if (sz != 0) {
7763 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7764 } else {
7765 /* We have xxx::yyyy in $PATH,
7766 * it means "use current dir" */
7767 ret = xstrdup(arg);
7768 }
7769 if (access(ret, F_OK) == 0)
7770 break;
7771
7772 if (*end == '\0') {
7773 free(ret);
7774 return NULL;
7775 }
7776 PATH = end + 1;
7777 }
7778
7779 return ret;
7780}
7781
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007782static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007783 const struct built_in_command *x,
7784 const struct built_in_command *end)
7785{
7786 while (x != end) {
7787 if (strcmp(name, x->b_cmd) != 0) {
7788 x++;
7789 continue;
7790 }
7791 debug_printf_exec("found builtin '%s'\n", name);
7792 return x;
7793 }
7794 return NULL;
7795}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007796static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007797{
7798 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7799}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007800static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007801{
7802 const struct built_in_command *x = find_builtin1(name);
7803 if (x)
7804 return x;
7805 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7806}
7807
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007808static void remove_nested_vars(void)
7809{
7810 struct variable *cur;
7811 struct variable **cur_pp;
7812
7813 cur_pp = &G.top_var;
7814 while ((cur = *cur_pp) != NULL) {
7815 if (cur->var_nest_level <= G.var_nest_level) {
7816 cur_pp = &cur->next;
7817 continue;
7818 }
7819 /* Unexport */
7820 if (cur->flg_export) {
7821 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7822 bb_unsetenv(cur->varstr);
7823 }
7824 /* Remove from global list */
7825 *cur_pp = cur->next;
7826 /* Free */
7827 if (!cur->max_len) {
7828 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7829 free(cur->varstr);
7830 }
7831 free(cur);
7832 }
7833}
7834
7835static void enter_var_nest_level(void)
7836{
7837 G.var_nest_level++;
7838 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7839
7840 /* Try: f() { echo -n .; f; }; f
7841 * struct variable::var_nest_level is uint16_t,
7842 * thus limiting recursion to < 2^16.
7843 * In any case, with 8 Mbyte stack SEGV happens
7844 * not too long after 2^16 recursions anyway.
7845 */
7846 if (G.var_nest_level > 0xff00)
7847 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7848}
7849
7850static void leave_var_nest_level(void)
7851{
7852 G.var_nest_level--;
7853 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7854 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7855 bb_error_msg_and_die("BUG: nesting underflow");
7856
7857 remove_nested_vars();
7858}
7859
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007860#if ENABLE_HUSH_FUNCTIONS
7861static struct function **find_function_slot(const char *name)
7862{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007863 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007864 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007865
7866 while ((funcp = *funcpp) != NULL) {
7867 if (strcmp(name, funcp->name) == 0) {
7868 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007869 break;
7870 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007871 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007872 }
7873 return funcpp;
7874}
7875
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007876static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007877{
7878 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007879 return funcp;
7880}
7881
7882/* Note: takes ownership on name ptr */
7883static struct function *new_function(char *name)
7884{
7885 struct function **funcpp = find_function_slot(name);
7886 struct function *funcp = *funcpp;
7887
7888 if (funcp != NULL) {
7889 struct command *cmd = funcp->parent_cmd;
7890 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7891 if (!cmd) {
7892 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7893 free(funcp->name);
7894 /* Note: if !funcp->body, do not free body_as_string!
7895 * This is a special case of "-F name body" function:
7896 * body_as_string was not malloced! */
7897 if (funcp->body) {
7898 free_pipe_list(funcp->body);
7899# if !BB_MMU
7900 free(funcp->body_as_string);
7901# endif
7902 }
7903 } else {
7904 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7905 cmd->argv[0] = funcp->name;
7906 cmd->group = funcp->body;
7907# if !BB_MMU
7908 cmd->group_as_string = funcp->body_as_string;
7909# endif
7910 }
7911 } else {
7912 debug_printf_exec("remembering new function '%s'\n", name);
7913 funcp = *funcpp = xzalloc(sizeof(*funcp));
7914 /*funcp->next = NULL;*/
7915 }
7916
7917 funcp->name = name;
7918 return funcp;
7919}
7920
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007921# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007922static void unset_func(const char *name)
7923{
7924 struct function **funcpp = find_function_slot(name);
7925 struct function *funcp = *funcpp;
7926
7927 if (funcp != NULL) {
7928 debug_printf_exec("freeing function '%s'\n", funcp->name);
7929 *funcpp = funcp->next;
7930 /* funcp is unlinked now, deleting it.
7931 * Note: if !funcp->body, the function was created by
7932 * "-F name body", do not free ->body_as_string
7933 * and ->name as they were not malloced. */
7934 if (funcp->body) {
7935 free_pipe_list(funcp->body);
7936 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007937# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007938 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007939# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007940 }
7941 free(funcp);
7942 }
7943}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007944# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007945
7946# if BB_MMU
7947#define exec_function(to_free, funcp, argv) \
7948 exec_function(funcp, argv)
7949# endif
7950static void exec_function(char ***to_free,
7951 const struct function *funcp,
7952 char **argv) NORETURN;
7953static void exec_function(char ***to_free,
7954 const struct function *funcp,
7955 char **argv)
7956{
7957# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007958 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007959
7960 argv[0] = G.global_argv[0];
7961 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007962 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007963
7964// Example when we are here: "cmd | func"
7965// func will run with saved-redirect fds open.
7966// $ f() { echo /proc/self/fd/*; }
7967// $ true | f
7968// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7969// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7970// Same in script:
7971// $ . ./SCRIPT
7972// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7973// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7974// They are CLOEXEC so external programs won't see them, but
7975// for "more correctness" we might want to close those extra fds here:
7976//? close_saved_fds_and_FILE_fds();
7977
Denys Vlasenko332e4112018-04-04 22:32:59 +02007978 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007979 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007980 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007981 IF_HUSH_LOCAL(G.func_nest_level++;)
7982
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007983 /* On MMU, funcp->body is always non-NULL */
7984 n = run_list(funcp->body);
7985 fflush_all();
7986 _exit(n);
7987# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007988//? close_saved_fds_and_FILE_fds();
7989
7990//TODO: check whether "true | func_with_return" works
7991
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007992 re_execute_shell(to_free,
7993 funcp->body_as_string,
7994 G.global_argv[0],
7995 argv + 1,
7996 NULL);
7997# endif
7998}
7999
8000static int run_function(const struct function *funcp, char **argv)
8001{
8002 int rc;
8003 save_arg_t sv;
8004 smallint sv_flg;
8005
8006 save_and_replace_G_args(&sv, argv);
8007
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008008 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008009 sv_flg = G_flag_return_in_progress;
8010 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008011
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008012 /* Make "local" variables properly shadow previous ones */
8013 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008014 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008015
8016 /* On MMU, funcp->body is always non-NULL */
8017# if !BB_MMU
8018 if (!funcp->body) {
8019 /* Function defined by -F */
8020 parse_and_run_string(funcp->body_as_string);
8021 rc = G.last_exitcode;
8022 } else
8023# endif
8024 {
8025 rc = run_list(funcp->body);
8026 }
8027
Denys Vlasenko332e4112018-04-04 22:32:59 +02008028 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008029 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008030
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008031 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008032
8033 restore_G_args(&sv, argv);
8034
8035 return rc;
8036}
8037#endif /* ENABLE_HUSH_FUNCTIONS */
8038
8039
8040#if BB_MMU
8041#define exec_builtin(to_free, x, argv) \
8042 exec_builtin(x, argv)
8043#else
8044#define exec_builtin(to_free, x, argv) \
8045 exec_builtin(to_free, argv)
8046#endif
8047static void exec_builtin(char ***to_free,
8048 const struct built_in_command *x,
8049 char **argv) NORETURN;
8050static void exec_builtin(char ***to_free,
8051 const struct built_in_command *x,
8052 char **argv)
8053{
8054#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008055 int rcode;
8056 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008057//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008058 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008059 fflush_all();
8060 _exit(rcode);
8061#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008062 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008063 /* On NOMMU, we must never block!
8064 * Example: { sleep 99 | read line; } & echo Ok
8065 */
8066 re_execute_shell(to_free,
8067 argv[0],
8068 G.global_argv[0],
8069 G.global_argv + 1,
8070 argv);
8071#endif
8072}
8073
8074
8075static void execvp_or_die(char **argv) NORETURN;
8076static void execvp_or_die(char **argv)
8077{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008078 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008079 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008080 /* Don't propagate SIG_IGN to the child */
8081 if (SPECIAL_JOBSTOP_SIGS != 0)
8082 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008083 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008084 e = 2;
8085 if (errno == EACCES) e = 126;
8086 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008087 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008088 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008089}
8090
8091#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008092static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008093{
8094 unsigned len;
8095 const char *cp;
8096
8097 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008098
8099 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8100 /* test a char with: bash -c 'set -x; echo "CH"' */
8101 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8102 " " "\001\002\003\004\005\006\007"
8103 "\010\011\012\013\014\015\016\017"
8104 "\020\021\022\023\024\025\026\027"
8105 "\030\031\032\033\034\035\036\037"
8106 )
8107 ] == '\0'
8108 ) {
8109 /* string has no special chars */
8110 x_mode_addstr(str);
8111 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008112 }
8113
8114 cp = str;
8115 for (;;) {
8116 /* print '....' up to EOL or first squote */
8117 len = (int)(strchrnul(cp, '\'') - cp);
8118 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008119 x_mode_addchr('\'');
8120 x_mode_addblock(cp, len);
8121 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008122 cp += len;
8123 }
8124 if (*cp == '\0')
8125 break;
8126 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008127 x_mode_addchr('\\');
8128 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008129 cp++;
8130 }
8131}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008132static void dump_cmd_in_x_mode(char **argv)
8133{
8134 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008135 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008136
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008137 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008138 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008139 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008140 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008141 x_mode_addchr(' ');
8142 if (argv[n][0] == '\0') {
8143 x_mode_addchr('\'');
8144 x_mode_addchr('\'');
8145 } else {
8146 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008147 }
8148 n++;
8149 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008150 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008151 }
8152}
8153#else
8154# define dump_cmd_in_x_mode(argv) ((void)0)
8155#endif
8156
Denys Vlasenko57000292018-01-12 14:41:45 +01008157#if ENABLE_HUSH_COMMAND
8158static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8159{
8160 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008161
Denys Vlasenko57000292018-01-12 14:41:45 +01008162 if (!opt_vV)
8163 return;
8164
8165 to_free = NULL;
8166 if (!explanation) {
8167 char *path = getenv("PATH");
8168 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008169 if (!explanation)
8170 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008171 if (opt_vV != 'V')
8172 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8173 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008174 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008175 free(to_free);
8176 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008177 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008178}
8179#else
8180# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8181#endif
8182
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008183#if BB_MMU
8184#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8185 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8186#define pseudo_exec(nommu_save, command, argv_expanded) \
8187 pseudo_exec(command, argv_expanded)
8188#endif
8189
8190/* Called after [v]fork() in run_pipe, or from builtin_exec.
8191 * Never returns.
8192 * Don't exit() here. If you don't exec, use _exit instead.
8193 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008194 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008195 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008196static void pseudo_exec_argv(nommu_save_t *nommu_save,
8197 char **argv, int assignment_cnt,
8198 char **argv_expanded) NORETURN;
8199static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8200 char **argv, int assignment_cnt,
8201 char **argv_expanded)
8202{
Denys Vlasenko57000292018-01-12 14:41:45 +01008203 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008204 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008205 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008206 IF_HUSH_COMMAND(char opt_vV = 0;)
8207 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008208
8209 new_env = expand_assignments(argv, assignment_cnt);
8210 dump_cmd_in_x_mode(new_env);
8211
8212 if (!argv[assignment_cnt]) {
8213 /* Case when we are here: ... | var=val | ...
8214 * (note that we do not exit early, i.e., do not optimize out
8215 * expand_assignments(): think about ... | var=`sleep 1` | ...
8216 */
8217 free_strings(new_env);
8218 _exit(EXIT_SUCCESS);
8219 }
8220
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008221 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008222#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008223 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008224#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008225 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008226 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008227#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008228 set_vars_and_save_old(new_env);
8229 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008230
8231 if (argv_expanded) {
8232 argv = argv_expanded;
8233 } else {
8234 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8235#if !BB_MMU
8236 nommu_save->argv = argv;
8237#endif
8238 }
8239 dump_cmd_in_x_mode(argv);
8240
8241#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8242 if (strchr(argv[0], '/') != NULL)
8243 goto skip;
8244#endif
8245
Denys Vlasenko75481d32017-07-31 05:27:09 +02008246#if ENABLE_HUSH_FUNCTIONS
8247 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008248 funcp = find_function(argv[0]);
8249 if (funcp)
8250 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008251#endif
8252
Denys Vlasenko57000292018-01-12 14:41:45 +01008253#if ENABLE_HUSH_COMMAND
8254 /* "command BAR": run BAR without looking it up among functions
8255 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8256 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8257 */
8258 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8259 char *p;
8260
8261 argv++;
8262 p = *argv;
8263 if (p[0] != '-' || !p[1])
8264 continue; /* bash allows "command command command [-OPT] BAR" */
8265
8266 for (;;) {
8267 p++;
8268 switch (*p) {
8269 case '\0':
8270 argv++;
8271 p = *argv;
8272 if (p[0] != '-' || !p[1])
8273 goto after_opts;
8274 continue; /* next arg is also -opts, process it too */
8275 case 'v':
8276 case 'V':
8277 opt_vV = *p;
8278 continue;
8279 default:
8280 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8281 }
8282 }
8283 }
8284 after_opts:
8285# if ENABLE_HUSH_FUNCTIONS
8286 if (opt_vV && find_function(argv[0]))
8287 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8288# endif
8289#endif
8290
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008291 /* Check if the command matches any of the builtins.
8292 * Depending on context, this might be redundant. But it's
8293 * easier to waste a few CPU cycles than it is to figure out
8294 * if this is one of those cases.
8295 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008296 /* Why "BB_MMU ? :" difference in logic? -
8297 * On NOMMU, it is more expensive to re-execute shell
8298 * just in order to run echo or test builtin.
8299 * It's better to skip it here and run corresponding
8300 * non-builtin later. */
8301 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8302 if (x) {
8303 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8304 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008305 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008306
8307#if ENABLE_FEATURE_SH_STANDALONE
8308 /* Check if the command matches any busybox applets */
8309 {
8310 int a = find_applet_by_name(argv[0]);
8311 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008312 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008313# if BB_MMU /* see above why on NOMMU it is not allowed */
8314 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008315 /* Do not leak open fds from opened script files etc.
8316 * Testcase: interactive "ls -l /proc/self/fd"
8317 * should not show tty fd open.
8318 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008319 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008320//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008321//This casuses test failures in
8322//redir_children_should_not_see_saved_fd_2.tests
8323//redir_children_should_not_see_saved_fd_3.tests
8324//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008325 /* Without this, "rm -i FILE" can't be ^C'ed: */
8326 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008327 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008328 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008329 }
8330# endif
8331 /* Re-exec ourselves */
8332 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008333 /* Don't propagate SIG_IGN to the child */
8334 if (SPECIAL_JOBSTOP_SIGS != 0)
8335 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008336 execv(bb_busybox_exec_path, argv);
8337 /* If they called chroot or otherwise made the binary no longer
8338 * executable, fall through */
8339 }
8340 }
8341#endif
8342
8343#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8344 skip:
8345#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008346 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008347 execvp_or_die(argv);
8348}
8349
8350/* Called after [v]fork() in run_pipe
8351 */
8352static void pseudo_exec(nommu_save_t *nommu_save,
8353 struct command *command,
8354 char **argv_expanded) NORETURN;
8355static void pseudo_exec(nommu_save_t *nommu_save,
8356 struct command *command,
8357 char **argv_expanded)
8358{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008359#if ENABLE_HUSH_FUNCTIONS
8360 if (command->cmd_type == CMD_FUNCDEF) {
8361 /* Ignore funcdefs in pipes:
8362 * true | f() { cmd }
8363 */
8364 _exit(0);
8365 }
8366#endif
8367
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008368 if (command->argv) {
8369 pseudo_exec_argv(nommu_save, command->argv,
8370 command->assignment_cnt, argv_expanded);
8371 }
8372
8373 if (command->group) {
8374 /* Cases when we are here:
8375 * ( list )
8376 * { list } &
8377 * ... | ( list ) | ...
8378 * ... | { list } | ...
8379 */
8380#if BB_MMU
8381 int rcode;
8382 debug_printf_exec("pseudo_exec: run_list\n");
8383 reset_traps_to_defaults();
8384 rcode = run_list(command->group);
8385 /* OK to leak memory by not calling free_pipe_list,
8386 * since this process is about to exit */
8387 _exit(rcode);
8388#else
8389 re_execute_shell(&nommu_save->argv_from_re_execing,
8390 command->group_as_string,
8391 G.global_argv[0],
8392 G.global_argv + 1,
8393 NULL);
8394#endif
8395 }
8396
8397 /* Case when we are here: ... | >file */
8398 debug_printf_exec("pseudo_exec'ed null command\n");
8399 _exit(EXIT_SUCCESS);
8400}
8401
8402#if ENABLE_HUSH_JOB
8403static const char *get_cmdtext(struct pipe *pi)
8404{
8405 char **argv;
8406 char *p;
8407 int len;
8408
8409 /* This is subtle. ->cmdtext is created only on first backgrounding.
8410 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8411 * On subsequent bg argv is trashed, but we won't use it */
8412 if (pi->cmdtext)
8413 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008414
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008415 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008416 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008417 pi->cmdtext = xzalloc(1);
8418 return pi->cmdtext;
8419 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008420 len = 0;
8421 do {
8422 len += strlen(*argv) + 1;
8423 } while (*++argv);
8424 p = xmalloc(len);
8425 pi->cmdtext = p;
8426 argv = pi->cmds[0].argv;
8427 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008428 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008429 *p++ = ' ';
8430 } while (*++argv);
8431 p[-1] = '\0';
8432 return pi->cmdtext;
8433}
8434
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008435static void remove_job_from_table(struct pipe *pi)
8436{
8437 struct pipe *prev_pipe;
8438
8439 if (pi == G.job_list) {
8440 G.job_list = pi->next;
8441 } else {
8442 prev_pipe = G.job_list;
8443 while (prev_pipe->next != pi)
8444 prev_pipe = prev_pipe->next;
8445 prev_pipe->next = pi->next;
8446 }
8447 G.last_jobid = 0;
8448 if (G.job_list)
8449 G.last_jobid = G.job_list->jobid;
8450}
8451
8452static void delete_finished_job(struct pipe *pi)
8453{
8454 remove_job_from_table(pi);
8455 free_pipe(pi);
8456}
8457
8458static void clean_up_last_dead_job(void)
8459{
8460 if (G.job_list && !G.job_list->alive_cmds)
8461 delete_finished_job(G.job_list);
8462}
8463
Denys Vlasenko16096292017-07-10 10:00:28 +02008464static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008465{
8466 struct pipe *job, **jobp;
8467 int i;
8468
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008469 clean_up_last_dead_job();
8470
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008471 /* Find the end of the list, and find next job ID to use */
8472 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008473 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008474 while ((job = *jobp) != NULL) {
8475 if (job->jobid > i)
8476 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008477 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008478 }
8479 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008480
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008481 /* Create a new job struct at the end */
8482 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008483 job->next = NULL;
8484 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8485 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8486 for (i = 0; i < pi->num_cmds; i++) {
8487 job->cmds[i].pid = pi->cmds[i].pid;
8488 /* all other fields are not used and stay zero */
8489 }
8490 job->cmdtext = xstrdup(get_cmdtext(pi));
8491
8492 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008493 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008494 G.last_jobid = job->jobid;
8495}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008496#endif /* JOB */
8497
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008498static int job_exited_or_stopped(struct pipe *pi)
8499{
8500 int rcode, i;
8501
8502 if (pi->alive_cmds != pi->stopped_cmds)
8503 return -1;
8504
8505 /* All processes in fg pipe have exited or stopped */
8506 rcode = 0;
8507 i = pi->num_cmds;
8508 while (--i >= 0) {
8509 rcode = pi->cmds[i].cmd_exitcode;
8510 /* usually last process gives overall exitstatus,
8511 * but with "set -o pipefail", last *failed* process does */
8512 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8513 break;
8514 }
8515 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8516 return rcode;
8517}
8518
Denys Vlasenko7e675362016-10-28 21:57:31 +02008519static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008520{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008521#if ENABLE_HUSH_JOB
8522 struct pipe *pi;
8523#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008524 int i, dead;
8525
8526 dead = WIFEXITED(status) || WIFSIGNALED(status);
8527
8528#if DEBUG_JOBS
8529 if (WIFSTOPPED(status))
8530 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8531 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8532 if (WIFSIGNALED(status))
8533 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8534 childpid, WTERMSIG(status), WEXITSTATUS(status));
8535 if (WIFEXITED(status))
8536 debug_printf_jobs("pid %d exited, exitcode %d\n",
8537 childpid, WEXITSTATUS(status));
8538#endif
8539 /* Were we asked to wait for a fg pipe? */
8540 if (fg_pipe) {
8541 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008542
Denys Vlasenko7e675362016-10-28 21:57:31 +02008543 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008544 int rcode;
8545
Denys Vlasenko7e675362016-10-28 21:57:31 +02008546 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8547 if (fg_pipe->cmds[i].pid != childpid)
8548 continue;
8549 if (dead) {
8550 int ex;
8551 fg_pipe->cmds[i].pid = 0;
8552 fg_pipe->alive_cmds--;
8553 ex = WEXITSTATUS(status);
8554 /* bash prints killer signal's name for *last*
8555 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8556 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8557 */
8558 if (WIFSIGNALED(status)) {
8559 int sig = WTERMSIG(status);
8560 if (i == fg_pipe->num_cmds-1)
8561 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8562 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8563 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8564 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8565 * Maybe we need to use sig | 128? */
8566 ex = sig + 128;
8567 }
8568 fg_pipe->cmds[i].cmd_exitcode = ex;
8569 } else {
8570 fg_pipe->stopped_cmds++;
8571 }
8572 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8573 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008574 rcode = job_exited_or_stopped(fg_pipe);
8575 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008576/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8577 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8578 * and "killall -STOP cat" */
8579 if (G_interactive_fd) {
8580#if ENABLE_HUSH_JOB
8581 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008582 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008583#endif
8584 return rcode;
8585 }
8586 if (fg_pipe->alive_cmds == 0)
8587 return rcode;
8588 }
8589 /* There are still running processes in the fg_pipe */
8590 return -1;
8591 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008592 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008593 }
8594
8595#if ENABLE_HUSH_JOB
8596 /* We were asked to wait for bg or orphaned children */
8597 /* No need to remember exitcode in this case */
8598 for (pi = G.job_list; pi; pi = pi->next) {
8599 for (i = 0; i < pi->num_cmds; i++) {
8600 if (pi->cmds[i].pid == childpid)
8601 goto found_pi_and_prognum;
8602 }
8603 }
8604 /* Happens when shell is used as init process (init=/bin/sh) */
8605 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8606 return -1; /* this wasn't a process from fg_pipe */
8607
8608 found_pi_and_prognum:
8609 if (dead) {
8610 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008611 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008612 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008613 rcode = 128 + WTERMSIG(status);
8614 pi->cmds[i].cmd_exitcode = rcode;
8615 if (G.last_bg_pid == pi->cmds[i].pid)
8616 G.last_bg_pid_exitcode = rcode;
8617 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008618 pi->alive_cmds--;
8619 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008620 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008621 printf(JOB_STATUS_FORMAT, pi->jobid,
8622 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008623 delete_finished_job(pi);
8624 } else {
8625/*
8626 * bash deletes finished jobs from job table only in interactive mode,
8627 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8628 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8629 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8630 * We only retain one "dead" job, if it's the single job on the list.
8631 * This covers most of real-world scenarios where this is useful.
8632 */
8633 if (pi != G.job_list)
8634 delete_finished_job(pi);
8635 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008636 }
8637 } else {
8638 /* child stopped */
8639 pi->stopped_cmds++;
8640 }
8641#endif
8642 return -1; /* this wasn't a process from fg_pipe */
8643}
8644
8645/* Check to see if any processes have exited -- if they have,
8646 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008647 *
8648 * If non-NULL fg_pipe: wait for its completion or stop.
8649 * Return its exitcode or zero if stopped.
8650 *
8651 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8652 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8653 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8654 * or 0 if no children changed status.
8655 *
8656 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8657 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8658 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008659 */
8660static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8661{
8662 int attributes;
8663 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008664 int rcode = 0;
8665
8666 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8667
8668 attributes = WUNTRACED;
8669 if (fg_pipe == NULL)
8670 attributes |= WNOHANG;
8671
8672 errno = 0;
8673#if ENABLE_HUSH_FAST
8674 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8675//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8676//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8677 /* There was neither fork nor SIGCHLD since last waitpid */
8678 /* Avoid doing waitpid syscall if possible */
8679 if (!G.we_have_children) {
8680 errno = ECHILD;
8681 return -1;
8682 }
8683 if (fg_pipe == NULL) { /* is WNOHANG set? */
8684 /* We have children, but they did not exit
8685 * or stop yet (we saw no SIGCHLD) */
8686 return 0;
8687 }
8688 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8689 }
8690#endif
8691
8692/* Do we do this right?
8693 * bash-3.00# sleep 20 | false
8694 * <ctrl-Z pressed>
8695 * [3]+ Stopped sleep 20 | false
8696 * bash-3.00# echo $?
8697 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8698 * [hush 1.14.0: yes we do it right]
8699 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008700 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008701 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008702#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008703 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008704 i = G.count_SIGCHLD;
8705#endif
8706 childpid = waitpid(-1, &status, attributes);
8707 if (childpid <= 0) {
8708 if (childpid && errno != ECHILD)
8709 bb_perror_msg("waitpid");
8710#if ENABLE_HUSH_FAST
8711 else { /* Until next SIGCHLD, waitpid's are useless */
8712 G.we_have_children = (childpid == 0);
8713 G.handled_SIGCHLD = i;
8714//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8715 }
8716#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008717 /* ECHILD (no children), or 0 (no change in children status) */
8718 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008719 break;
8720 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008721 rcode = process_wait_result(fg_pipe, childpid, status);
8722 if (rcode >= 0) {
8723 /* fg_pipe exited or stopped */
8724 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008725 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008726 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008727 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008728 rcode = WEXITSTATUS(status);
8729 if (WIFSIGNALED(status))
8730 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008731 if (WIFSTOPPED(status))
8732 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8733 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008734 rcode++;
8735 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008736 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008737 /* This wasn't one of our processes, or */
8738 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008739 } /* while (waitpid succeeds)... */
8740
8741 return rcode;
8742}
8743
8744#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008745static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008746{
8747 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008748 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008749 if (G_saved_tty_pgrp) {
8750 /* Job finished, move the shell to the foreground */
8751 p = getpgrp(); /* our process group id */
8752 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8753 tcsetpgrp(G_interactive_fd, p);
8754 }
8755 return rcode;
8756}
8757#endif
8758
8759/* Start all the jobs, but don't wait for anything to finish.
8760 * See checkjobs().
8761 *
8762 * Return code is normally -1, when the caller has to wait for children
8763 * to finish to determine the exit status of the pipe. If the pipe
8764 * is a simple builtin command, however, the action is done by the
8765 * time run_pipe returns, and the exit code is provided as the
8766 * return value.
8767 *
8768 * Returns -1 only if started some children. IOW: we have to
8769 * mask out retvals of builtins etc with 0xff!
8770 *
8771 * The only case when we do not need to [v]fork is when the pipe
8772 * is single, non-backgrounded, non-subshell command. Examples:
8773 * cmd ; ... { list } ; ...
8774 * cmd && ... { list } && ...
8775 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008776 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008777 * or (if SH_STANDALONE) an applet, and we can run the { list }
8778 * with run_list. If it isn't one of these, we fork and exec cmd.
8779 *
8780 * Cases when we must fork:
8781 * non-single: cmd | cmd
8782 * backgrounded: cmd & { list } &
8783 * subshell: ( list ) [&]
8784 */
8785#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008786#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8787 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008788#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008789static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008790 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008791 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008792 char **argv_expanded)
8793{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008794 /* Assignments occur before redirects. Try:
8795 * a=`sleep 1` sleep 2 3>/qwe/rty
8796 */
8797
8798 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8799 dump_cmd_in_x_mode(new_env);
8800 dump_cmd_in_x_mode(argv_expanded);
8801 /* this takes ownership of new_env[i] elements, and frees new_env: */
8802 set_vars_and_save_old(new_env);
8803
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008804 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008805}
8806static NOINLINE int run_pipe(struct pipe *pi)
8807{
8808 static const char *const null_ptr = NULL;
8809
8810 int cmd_no;
8811 int next_infd;
8812 struct command *command;
8813 char **argv_expanded;
8814 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008815 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008816 int rcode;
8817
8818 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8819 debug_enter();
8820
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008821 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8822 * Result should be 3 lines: q w e, qwe, q w e
8823 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008824 if (G.ifs_whitespace != G.ifs)
8825 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008826 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008827 if (G.ifs) {
8828 char *p;
8829 G.ifs_whitespace = (char*)G.ifs;
8830 p = skip_whitespace(G.ifs);
8831 if (*p) {
8832 /* Not all $IFS is whitespace */
8833 char *d;
8834 int len = p - G.ifs;
8835 p = skip_non_whitespace(p);
8836 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8837 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8838 while (*p) {
8839 if (isspace(*p))
8840 *d++ = *p;
8841 p++;
8842 }
8843 *d = '\0';
8844 }
8845 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008846 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008847 G.ifs_whitespace = (char*)G.ifs;
8848 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008849
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008850 IF_HUSH_JOB(pi->pgrp = -1;)
8851 pi->stopped_cmds = 0;
8852 command = &pi->cmds[0];
8853 argv_expanded = NULL;
8854
8855 if (pi->num_cmds != 1
8856 || pi->followup == PIPE_BG
8857 || command->cmd_type == CMD_SUBSHELL
8858 ) {
8859 goto must_fork;
8860 }
8861
8862 pi->alive_cmds = 1;
8863
8864 debug_printf_exec(": group:%p argv:'%s'\n",
8865 command->group, command->argv ? command->argv[0] : "NONE");
8866
8867 if (command->group) {
8868#if ENABLE_HUSH_FUNCTIONS
8869 if (command->cmd_type == CMD_FUNCDEF) {
8870 /* "executing" func () { list } */
8871 struct function *funcp;
8872
8873 funcp = new_function(command->argv[0]);
8874 /* funcp->name is already set to argv[0] */
8875 funcp->body = command->group;
8876# if !BB_MMU
8877 funcp->body_as_string = command->group_as_string;
8878 command->group_as_string = NULL;
8879# endif
8880 command->group = NULL;
8881 command->argv[0] = NULL;
8882 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8883 funcp->parent_cmd = command;
8884 command->child_func = funcp;
8885
8886 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8887 debug_leave();
8888 return EXIT_SUCCESS;
8889 }
8890#endif
8891 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008892 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008893 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008894 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008895 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008896//FIXME: we need to pass squirrel down into run_list()
8897//for SH_STANDALONE case, or else this construct:
8898// { find /proc/self/fd; true; } >FILE; cmd2
8899//has no way of closing saved fd#1 for "find",
8900//and in SH_STANDALONE mode, "find" is not execed,
8901//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008902 rcode = run_list(command->group) & 0xff;
8903 }
8904 restore_redirects(squirrel);
8905 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8906 debug_leave();
8907 debug_printf_exec("run_pipe: return %d\n", rcode);
8908 return rcode;
8909 }
8910
8911 argv = command->argv ? command->argv : (char **) &null_ptr;
8912 {
8913 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008914 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8915 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008916 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008917 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008918
Denys Vlasenko5807e182018-02-08 19:19:04 +01008919#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008920 if (G.lineno_var)
8921 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8922#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008923
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008924 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008925 /* Assignments, but no command.
8926 * Ensure redirects take effect (that is, create files).
8927 * Try "a=t >file"
8928 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008929 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008930 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008931 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008932 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008933 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008934
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008935 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008936 i = 0;
8937 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008938 char *p = expand_string_to_string(argv[i],
8939 EXP_FLAG_ESC_GLOB_CHARS,
8940 /*unbackslash:*/ 1
8941 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008942#if ENABLE_HUSH_MODE_X
8943 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008944 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008945 if (i == 0)
8946 x_mode_prefix();
8947 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008948 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008949 if (*eq) eq++;
8950 x_mode_addblock(p, (eq - p));
8951 x_mode_print_optionally_squoted(eq);
8952 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008953 }
8954#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008955 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008956 if (set_local_var(p, /*flag:*/ 0)) {
8957 /* assignment to readonly var / putenv error? */
8958 rcode = 1;
8959 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008960 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008961 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008962 /* Redirect error sets $? to 1. Otherwise,
8963 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008964 * Else, clear $?:
8965 * false; q=`exit 2`; echo $? - should print 2
8966 * false; x=1; echo $? - should print 0
8967 * Because of the 2nd case, we can't just use G.last_exitcode.
8968 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008969 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008970 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008971 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8972 debug_leave();
8973 debug_printf_exec("run_pipe: return %d\n", rcode);
8974 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008975 }
8976
8977 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008978#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008979 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008980 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008981 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008982#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008983 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008984
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008985 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008986 if (!argv_expanded[0]) {
8987 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008988 /* `false` still has to set exitcode 1 */
8989 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008990 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008991 }
8992
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008993 old_vars = NULL;
8994 sv_shadowed = G.shadowed_vars_pp;
8995
Denys Vlasenko75481d32017-07-31 05:27:09 +02008996 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008997 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8998 IF_HUSH_FUNCTIONS(x = NULL;)
8999 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009000 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009001 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009002 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9003 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009004 /*
9005 * Variable assignments are executed, but then "forgotten":
9006 * a=`sleep 1;echo A` exec 3>&-; echo $a
9007 * sleeps, but prints nothing.
9008 */
9009 enter_var_nest_level();
9010 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009011 rcode = redirect_and_varexp_helper(command,
9012 /*squirrel:*/ ERR_PTR,
9013 argv_expanded
9014 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009015 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009016 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009017
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009018 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009019 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009020
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009021 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009022 * a=b true; env | grep ^a=
9023 */
9024 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009025 /* Collect all variables "shadowed" by helper
9026 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9027 * into old_vars list:
9028 */
9029 G.shadowed_vars_pp = &old_vars;
9030 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009031 if (rcode == 0) {
9032 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009033 /* Do not collect *to old_vars list* vars shadowed
9034 * by e.g. "local VAR" builtin (collect them
9035 * in the previously nested list instead):
9036 * don't want them to be restored immediately
9037 * after "local" completes.
9038 */
9039 G.shadowed_vars_pp = sv_shadowed;
9040
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009041 debug_printf_exec(": builtin '%s' '%s'...\n",
9042 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009043 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009044 rcode = x->b_function(argv_expanded) & 0xff;
9045 fflush_all();
9046 }
9047#if ENABLE_HUSH_FUNCTIONS
9048 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009049 debug_printf_exec(": function '%s' '%s'...\n",
9050 funcp->name, argv_expanded[1]);
9051 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009052 /*
9053 * But do collect *to old_vars list* vars shadowed
9054 * within function execution. To that end, restore
9055 * this pointer _after_ function run:
9056 */
9057 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009058 }
9059#endif
9060 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009061 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009062 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009063 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009064 if (n < 0 || !APPLET_IS_NOFORK(n))
9065 goto must_fork;
9066
9067 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009068 /* Collect all variables "shadowed" by helper into old_vars list */
9069 G.shadowed_vars_pp = &old_vars;
9070 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9071 G.shadowed_vars_pp = sv_shadowed;
9072
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009073 if (rcode == 0) {
9074 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9075 argv_expanded[0], argv_expanded[1]);
9076 /*
9077 * Note: signals (^C) can't interrupt here.
9078 * We remember them and they will be acted upon
9079 * after applet returns.
9080 * This makes applets which can run for a long time
9081 * and/or wait for user input ineligible for NOFORK:
9082 * for example, "yes" or "rm" (rm -i waits for input).
9083 */
9084 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009085 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009086 } else
9087 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009088
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009089 restore_redirects(squirrel);
9090 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009091 leave_var_nest_level();
9092 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009093
9094 /*
9095 * Try "usleep 99999999" + ^C + "echo $?"
9096 * with FEATURE_SH_NOFORK=y.
9097 */
9098 if (!funcp) {
9099 /* It was builtin or nofork.
9100 * if this would be a real fork/execed program,
9101 * it should have died if a fatal sig was received.
9102 * But OTOH, there was no separate process,
9103 * the sig was sent to _shell_, not to non-existing
9104 * child.
9105 * Let's just handle ^C only, this one is obvious:
9106 * we aren't ok with exitcode 0 when ^C was pressed
9107 * during builtin/nofork.
9108 */
9109 if (sigismember(&G.pending_set, SIGINT))
9110 rcode = 128 + SIGINT;
9111 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009112 free(argv_expanded);
9113 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9114 debug_leave();
9115 debug_printf_exec("run_pipe return %d\n", rcode);
9116 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009117 }
9118
9119 must_fork:
9120 /* NB: argv_expanded may already be created, and that
9121 * might include `cmd` runs! Do not rerun it! We *must*
9122 * use argv_expanded if it's non-NULL */
9123
9124 /* Going to fork a child per each pipe member */
9125 pi->alive_cmds = 0;
9126 next_infd = 0;
9127
9128 cmd_no = 0;
9129 while (cmd_no < pi->num_cmds) {
9130 struct fd_pair pipefds;
9131#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009132 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009133 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009134 nommu_save.old_vars = NULL;
9135 nommu_save.argv = NULL;
9136 nommu_save.argv_from_re_execing = NULL;
9137#endif
9138 command = &pi->cmds[cmd_no];
9139 cmd_no++;
9140 if (command->argv) {
9141 debug_printf_exec(": pipe member '%s' '%s'...\n",
9142 command->argv[0], command->argv[1]);
9143 } else {
9144 debug_printf_exec(": pipe member with no argv\n");
9145 }
9146
9147 /* pipes are inserted between pairs of commands */
9148 pipefds.rd = 0;
9149 pipefds.wr = 1;
9150 if (cmd_no < pi->num_cmds)
9151 xpiped_pair(pipefds);
9152
Denys Vlasenko5807e182018-02-08 19:19:04 +01009153#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009154 if (G.lineno_var)
9155 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
9156#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009157
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009158 command->pid = BB_MMU ? fork() : vfork();
9159 if (!command->pid) { /* child */
9160#if ENABLE_HUSH_JOB
9161 disable_restore_tty_pgrp_on_exit();
9162 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9163
9164 /* Every child adds itself to new process group
9165 * with pgid == pid_of_first_child_in_pipe */
9166 if (G.run_list_level == 1 && G_interactive_fd) {
9167 pid_t pgrp;
9168 pgrp = pi->pgrp;
9169 if (pgrp < 0) /* true for 1st process only */
9170 pgrp = getpid();
9171 if (setpgid(0, pgrp) == 0
9172 && pi->followup != PIPE_BG
9173 && G_saved_tty_pgrp /* we have ctty */
9174 ) {
9175 /* We do it in *every* child, not just first,
9176 * to avoid races */
9177 tcsetpgrp(G_interactive_fd, pgrp);
9178 }
9179 }
9180#endif
9181 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9182 /* 1st cmd in backgrounded pipe
9183 * should have its stdin /dev/null'ed */
9184 close(0);
9185 if (open(bb_dev_null, O_RDONLY))
9186 xopen("/", O_RDONLY);
9187 } else {
9188 xmove_fd(next_infd, 0);
9189 }
9190 xmove_fd(pipefds.wr, 1);
9191 if (pipefds.rd > 1)
9192 close(pipefds.rd);
9193 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009194 * and the pipe fd (fd#1) is available for dup'ing:
9195 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9196 * of cmd1 goes into pipe.
9197 */
9198 if (setup_redirects(command, NULL)) {
9199 /* Happens when redir file can't be opened:
9200 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9201 * FOO
9202 * hush: can't open '/qwe/rty': No such file or directory
9203 * BAZ
9204 * (echo BAR is not executed, it hits _exit(1) below)
9205 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009206 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009207 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009208
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009209 /* Stores to nommu_save list of env vars putenv'ed
9210 * (NOMMU, on MMU we don't need that) */
9211 /* cast away volatility... */
9212 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9213 /* pseudo_exec() does not return */
9214 }
9215
9216 /* parent or error */
9217#if ENABLE_HUSH_FAST
9218 G.count_SIGCHLD++;
9219//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9220#endif
9221 enable_restore_tty_pgrp_on_exit();
9222#if !BB_MMU
9223 /* Clean up after vforked child */
9224 free(nommu_save.argv);
9225 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009226 G.var_nest_level = sv_var_nest_level;
9227 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009228 add_vars(nommu_save.old_vars);
9229#endif
9230 free(argv_expanded);
9231 argv_expanded = NULL;
9232 if (command->pid < 0) { /* [v]fork failed */
9233 /* Clearly indicate, was it fork or vfork */
9234 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
9235 } else {
9236 pi->alive_cmds++;
9237#if ENABLE_HUSH_JOB
9238 /* Second and next children need to know pid of first one */
9239 if (pi->pgrp < 0)
9240 pi->pgrp = command->pid;
9241#endif
9242 }
9243
9244 if (cmd_no > 1)
9245 close(next_infd);
9246 if (cmd_no < pi->num_cmds)
9247 close(pipefds.wr);
9248 /* Pass read (output) pipe end to next iteration */
9249 next_infd = pipefds.rd;
9250 }
9251
9252 if (!pi->alive_cmds) {
9253 debug_leave();
9254 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9255 return 1;
9256 }
9257
9258 debug_leave();
9259 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9260 return -1;
9261}
9262
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009263/* NB: called by pseudo_exec, and therefore must not modify any
9264 * global data until exec/_exit (we can be a child after vfork!) */
9265static int run_list(struct pipe *pi)
9266{
9267#if ENABLE_HUSH_CASE
9268 char *case_word = NULL;
9269#endif
9270#if ENABLE_HUSH_LOOPS
9271 struct pipe *loop_top = NULL;
9272 char **for_lcur = NULL;
9273 char **for_list = NULL;
9274#endif
9275 smallint last_followup;
9276 smalluint rcode;
9277#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9278 smalluint cond_code = 0;
9279#else
9280 enum { cond_code = 0 };
9281#endif
9282#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009283 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009284 smallint last_rword; /* ditto */
9285#endif
9286
9287 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9288 debug_enter();
9289
9290#if ENABLE_HUSH_LOOPS
9291 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009292 {
9293 struct pipe *cpipe;
9294 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9295 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9296 continue;
9297 /* current word is FOR or IN (BOLD in comments below) */
9298 if (cpipe->next == NULL) {
9299 syntax_error("malformed for");
9300 debug_leave();
9301 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9302 return 1;
9303 }
9304 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9305 if (cpipe->next->res_word == RES_DO)
9306 continue;
9307 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9308 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9309 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9310 ) {
9311 syntax_error("malformed for");
9312 debug_leave();
9313 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9314 return 1;
9315 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009316 }
9317 }
9318#endif
9319
9320 /* Past this point, all code paths should jump to ret: label
9321 * in order to return, no direct "return" statements please.
9322 * This helps to ensure that no memory is leaked. */
9323
9324#if ENABLE_HUSH_JOB
9325 G.run_list_level++;
9326#endif
9327
9328#if HAS_KEYWORDS
9329 rword = RES_NONE;
9330 last_rword = RES_XXXX;
9331#endif
9332 last_followup = PIPE_SEQ;
9333 rcode = G.last_exitcode;
9334
9335 /* Go through list of pipes, (maybe) executing them. */
9336 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009337 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009338 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009339
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009340 if (G.flag_SIGINT)
9341 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009342 if (G_flag_return_in_progress == 1)
9343 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009344
9345 IF_HAS_KEYWORDS(rword = pi->res_word;)
9346 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9347 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009348
9349 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009350 if (
9351#if ENABLE_HUSH_IF
9352 rword == RES_IF || rword == RES_ELIF ||
9353#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009354 pi->followup != PIPE_SEQ
9355 ) {
9356 G.errexit_depth++;
9357 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009358#if ENABLE_HUSH_LOOPS
9359 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9360 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9361 ) {
9362 /* start of a loop: remember where loop starts */
9363 loop_top = pi;
9364 G.depth_of_loop++;
9365 }
9366#endif
9367 /* Still in the same "if...", "then..." or "do..." branch? */
9368 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9369 if ((rcode == 0 && last_followup == PIPE_OR)
9370 || (rcode != 0 && last_followup == PIPE_AND)
9371 ) {
9372 /* It is "<true> || CMD" or "<false> && CMD"
9373 * and we should not execute CMD */
9374 debug_printf_exec("skipped cmd because of || or &&\n");
9375 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009376 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009377 }
9378 }
9379 last_followup = pi->followup;
9380 IF_HAS_KEYWORDS(last_rword = rword;)
9381#if ENABLE_HUSH_IF
9382 if (cond_code) {
9383 if (rword == RES_THEN) {
9384 /* if false; then ... fi has exitcode 0! */
9385 G.last_exitcode = rcode = EXIT_SUCCESS;
9386 /* "if <false> THEN cmd": skip cmd */
9387 continue;
9388 }
9389 } else {
9390 if (rword == RES_ELSE || rword == RES_ELIF) {
9391 /* "if <true> then ... ELSE/ELIF cmd":
9392 * skip cmd and all following ones */
9393 break;
9394 }
9395 }
9396#endif
9397#if ENABLE_HUSH_LOOPS
9398 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9399 if (!for_lcur) {
9400 /* first loop through for */
9401
9402 static const char encoded_dollar_at[] ALIGN1 = {
9403 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9404 }; /* encoded representation of "$@" */
9405 static const char *const encoded_dollar_at_argv[] = {
9406 encoded_dollar_at, NULL
9407 }; /* argv list with one element: "$@" */
9408 char **vals;
9409
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009410 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009411 vals = (char**)encoded_dollar_at_argv;
9412 if (pi->next->res_word == RES_IN) {
9413 /* if no variable values after "in" we skip "for" */
9414 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009415 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9416 break;
9417 }
9418 vals = pi->next->cmds[0].argv;
9419 } /* else: "for var; do..." -> assume "$@" list */
9420 /* create list of variable values */
9421 debug_print_strings("for_list made from", vals);
9422 for_list = expand_strvec_to_strvec(vals);
9423 for_lcur = for_list;
9424 debug_print_strings("for_list", for_list);
9425 }
9426 if (!*for_lcur) {
9427 /* "for" loop is over, clean up */
9428 free(for_list);
9429 for_list = NULL;
9430 for_lcur = NULL;
9431 break;
9432 }
9433 /* Insert next value from for_lcur */
9434 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009435 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009436 continue;
9437 }
9438 if (rword == RES_IN) {
9439 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9440 }
9441 if (rword == RES_DONE) {
9442 continue; /* "done" has no cmds too */
9443 }
9444#endif
9445#if ENABLE_HUSH_CASE
9446 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009447 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009448 case_word = expand_string_to_string(pi->cmds->argv[0],
9449 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009450 debug_printf_exec("CASE word1:'%s'\n", case_word);
9451 //unbackslash(case_word);
9452 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009453 continue;
9454 }
9455 if (rword == RES_MATCH) {
9456 char **argv;
9457
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009458 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009459 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9460 break;
9461 /* all prev words didn't match, does this one match? */
9462 argv = pi->cmds->argv;
9463 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009464 char *pattern;
9465 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9466 pattern = expand_string_to_string(*argv,
9467 EXP_FLAG_ESC_GLOB_CHARS,
9468 /*unbackslash:*/ 0
9469 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009470 /* TODO: which FNM_xxx flags to use? */
9471 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009472 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9473 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009474 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009475 if (cond_code == 0) {
9476 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009477 free(case_word);
9478 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009479 break;
9480 }
9481 argv++;
9482 }
9483 continue;
9484 }
9485 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009486 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009487 if (cond_code != 0)
9488 continue; /* not matched yet, skip this pipe */
9489 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009490 if (rword == RES_ESAC) {
9491 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9492 if (case_word) {
9493 /* "case" did not match anything: still set $? (to 0) */
9494 G.last_exitcode = rcode = EXIT_SUCCESS;
9495 }
9496 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009497#endif
9498 /* Just pressing <enter> in shell should check for jobs.
9499 * OTOH, in non-interactive shell this is useless
9500 * and only leads to extra job checks */
9501 if (pi->num_cmds == 0) {
9502 if (G_interactive_fd)
9503 goto check_jobs_and_continue;
9504 continue;
9505 }
9506
9507 /* After analyzing all keywords and conditions, we decided
9508 * to execute this pipe. NB: have to do checkjobs(NULL)
9509 * after run_pipe to collect any background children,
9510 * even if list execution is to be stopped. */
9511 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009512#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009513 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009514#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009515 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9516 if (r != -1) {
9517 /* We ran a builtin, function, or group.
9518 * rcode is already known
9519 * and we don't need to wait for anything. */
9520 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9521 G.last_exitcode = rcode;
9522 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009523#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009524 /* Was it "break" or "continue"? */
9525 if (G.flag_break_continue) {
9526 smallint fbc = G.flag_break_continue;
9527 /* We might fall into outer *loop*,
9528 * don't want to break it too */
9529 if (loop_top) {
9530 G.depth_break_continue--;
9531 if (G.depth_break_continue == 0)
9532 G.flag_break_continue = 0;
9533 /* else: e.g. "continue 2" should *break* once, *then* continue */
9534 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9535 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009536 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009537 break;
9538 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009539 /* "continue": simulate end of loop */
9540 rword = RES_DONE;
9541 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009542 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009543#endif
9544 if (G_flag_return_in_progress == 1) {
9545 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9546 break;
9547 }
9548 } else if (pi->followup == PIPE_BG) {
9549 /* What does bash do with attempts to background builtins? */
9550 /* even bash 3.2 doesn't do that well with nested bg:
9551 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9552 * I'm NOT treating inner &'s as jobs */
9553#if ENABLE_HUSH_JOB
9554 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009555 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009556#endif
9557 /* Last command's pid goes to $! */
9558 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009559 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009560 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009561/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009562 rcode = EXIT_SUCCESS;
9563 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009564 } else {
9565#if ENABLE_HUSH_JOB
9566 if (G.run_list_level == 1 && G_interactive_fd) {
9567 /* Waits for completion, then fg's main shell */
9568 rcode = checkjobs_and_fg_shell(pi);
9569 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009570 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009571 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009572#endif
9573 /* This one just waits for completion */
9574 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9575 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9576 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009577 G.last_exitcode = rcode;
9578 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009579 }
9580
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009581 /* Handle "set -e" */
9582 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9583 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9584 if (G.errexit_depth == 0)
9585 hush_exit(rcode);
9586 }
9587 G.errexit_depth = sv_errexit_depth;
9588
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009589 /* Analyze how result affects subsequent commands */
9590#if ENABLE_HUSH_IF
9591 if (rword == RES_IF || rword == RES_ELIF)
9592 cond_code = rcode;
9593#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009594 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009595 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009596 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009597#if ENABLE_HUSH_LOOPS
9598 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009599 if (pi->next
9600 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009601 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009602 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009603 if (rword == RES_WHILE) {
9604 if (rcode) {
9605 /* "while false; do...done" - exitcode 0 */
9606 G.last_exitcode = rcode = EXIT_SUCCESS;
9607 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009608 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009609 }
9610 }
9611 if (rword == RES_UNTIL) {
9612 if (!rcode) {
9613 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009614 break;
9615 }
9616 }
9617 }
9618#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009619 } /* for (pi) */
9620
9621#if ENABLE_HUSH_JOB
9622 G.run_list_level--;
9623#endif
9624#if ENABLE_HUSH_LOOPS
9625 if (loop_top)
9626 G.depth_of_loop--;
9627 free(for_list);
9628#endif
9629#if ENABLE_HUSH_CASE
9630 free(case_word);
9631#endif
9632 debug_leave();
9633 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9634 return rcode;
9635}
9636
9637/* Select which version we will use */
9638static int run_and_free_list(struct pipe *pi)
9639{
9640 int rcode = 0;
9641 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009642 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009643 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9644 rcode = run_list(pi);
9645 }
9646 /* free_pipe_list has the side effect of clearing memory.
9647 * In the long run that function can be merged with run_list,
9648 * but doing that now would hobble the debugging effort. */
9649 free_pipe_list(pi);
9650 debug_printf_exec("run_and_free_list return %d\n", rcode);
9651 return rcode;
9652}
9653
9654
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009655static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009656{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009657 sighandler_t old_handler;
9658 unsigned sig = 0;
9659 while ((mask >>= 1) != 0) {
9660 sig++;
9661 if (!(mask & 1))
9662 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009663 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009664 /* POSIX allows shell to re-enable SIGCHLD
9665 * even if it was SIG_IGN on entry.
9666 * Therefore we skip IGN check for it:
9667 */
9668 if (sig == SIGCHLD)
9669 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009670 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9671 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9672 */
9673 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009674 if (old_handler == SIG_IGN) {
9675 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009676 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009677#if ENABLE_HUSH_TRAP
9678 if (!G_traps)
9679 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9680 free(G_traps[sig]);
9681 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9682#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009683 }
9684 }
9685}
9686
9687/* Called a few times only (or even once if "sh -c") */
9688static void install_special_sighandlers(void)
9689{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009690 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009691
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009692 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009693 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009694 if (G_interactive_fd) {
9695 mask |= SPECIAL_INTERACTIVE_SIGS;
9696 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009697 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009698 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009699 /* Careful, do not re-install handlers we already installed */
9700 if (G.special_sig_mask != mask) {
9701 unsigned diff = mask & ~G.special_sig_mask;
9702 G.special_sig_mask = mask;
9703 install_sighandlers(diff);
9704 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009705}
9706
9707#if ENABLE_HUSH_JOB
9708/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009709/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009710static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009711{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009712 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009713
9714 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009715 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009716 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9717 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009718 + (1 << SIGBUS ) * HUSH_DEBUG
9719 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009720 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009721 + (1 << SIGABRT)
9722 /* bash 3.2 seems to handle these just like 'fatal' ones */
9723 + (1 << SIGPIPE)
9724 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009725 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009726 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009727 * we never want to restore pgrp on exit, and this fn is not called
9728 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009729 /*+ (1 << SIGHUP )*/
9730 /*+ (1 << SIGTERM)*/
9731 /*+ (1 << SIGINT )*/
9732 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009733 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009734
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009735 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009736}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009737#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009738
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009739static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009740{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009741 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009742 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009743 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009744 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009745 break;
9746 case 'x':
9747 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009748 IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009749 break;
9750 case 'o':
9751 if (!o_opt) {
9752 /* "set -+o" without parameter.
9753 * in bash, set -o produces this output:
9754 * pipefail off
9755 * and set +o:
9756 * set +o pipefail
9757 * We always use the second form.
9758 */
9759 const char *p = o_opt_strings;
9760 idx = 0;
9761 while (*p) {
9762 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9763 idx++;
9764 p += strlen(p) + 1;
9765 }
9766 break;
9767 }
9768 idx = index_in_strings(o_opt_strings, o_opt);
9769 if (idx >= 0) {
9770 G.o_opt[idx] = state;
9771 break;
9772 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009773 case 'e':
9774 G.o_opt[OPT_O_ERREXIT] = state;
9775 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009776 default:
9777 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009778 }
9779 return EXIT_SUCCESS;
9780}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009781
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009782int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009783int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009784{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009785 enum {
9786 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009787 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009788 };
9789 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009790 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009791 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009792 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009793 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009794
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009795 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009796 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009797 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009798
Denys Vlasenko10c01312011-05-11 11:49:21 +02009799#if ENABLE_HUSH_FAST
9800 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9801#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009802#if !BB_MMU
9803 G.argv0_for_re_execing = argv[0];
9804#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009805
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009806 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009807 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9808 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009809 shell_ver = xzalloc(sizeof(*shell_ver));
9810 shell_ver->flg_export = 1;
9811 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009812 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009813 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009814 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009815
Denys Vlasenko605067b2010-09-06 12:10:51 +02009816 /* Create shell local variables from the values
9817 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009818 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009819 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009820 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009821 if (e) while (*e) {
9822 char *value = strchr(*e, '=');
9823 if (value) { /* paranoia */
9824 cur_var->next = xzalloc(sizeof(*cur_var));
9825 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009826 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009827 cur_var->max_len = strlen(*e);
9828 cur_var->flg_export = 1;
9829 }
9830 e++;
9831 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009832 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009833 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9834 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009835
9836 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009837 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009838
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009839#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9840 /* Set (but not export) PS1/2 unless already set */
9841 if (!get_local_var_value("PS1"))
9842 set_local_var_from_halves("PS1", "\\w \\$ ");
9843 if (!get_local_var_value("PS2"))
9844 set_local_var_from_halves("PS2", "> ");
9845#endif
9846
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009847#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009848 /* Set (but not export) HOSTNAME unless already set */
9849 if (!get_local_var_value("HOSTNAME")) {
9850 struct utsname uts;
9851 uname(&uts);
9852 set_local_var_from_halves("HOSTNAME", uts.nodename);
9853 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02009854#endif
9855 /* IFS is not inherited from the parent environment */
9856 set_local_var_from_halves("IFS", defifs);
9857
Denys Vlasenko6db47842009-09-05 20:15:17 +02009858 /* bash also exports SHLVL and _,
9859 * and sets (but doesn't export) the following variables:
9860 * BASH=/bin/bash
9861 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9862 * BASH_VERSION='3.2.0(1)-release'
9863 * HOSTTYPE=i386
9864 * MACHTYPE=i386-pc-linux-gnu
9865 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009866 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009867 * EUID=<NNNNN>
9868 * UID=<NNNNN>
9869 * GROUPS=()
9870 * LINES=<NNN>
9871 * COLUMNS=<NNN>
9872 * BASH_ARGC=()
9873 * BASH_ARGV=()
9874 * BASH_LINENO=()
9875 * BASH_SOURCE=()
9876 * DIRSTACK=()
9877 * PIPESTATUS=([0]="0")
9878 * HISTFILE=/<xxx>/.bash_history
9879 * HISTFILESIZE=500
9880 * HISTSIZE=500
9881 * MAILCHECK=60
9882 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9883 * SHELL=/bin/bash
9884 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9885 * TERM=dumb
9886 * OPTERR=1
9887 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +02009888 * PS4='+ '
9889 */
9890
Denys Vlasenko5807e182018-02-08 19:19:04 +01009891#if ENABLE_HUSH_LINENO_VAR
9892 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009893 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9894 set_local_var(p, /*flags*/ 0);
9895 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9896 }
9897#endif
9898
Denis Vlasenko38f63192007-01-22 09:03:07 +00009899#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009900 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009901#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009902
Eric Andersen94ac2442001-05-22 19:05:18 +00009903 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009904 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009905
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009906 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009907
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009908 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009909 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009910 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009911 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009912 * in order to intercept (more) signals.
9913 */
9914
9915 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009916 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009917 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009918 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009919 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009920 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009921#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009922 "<:$:R:V:"
9923# if ENABLE_HUSH_FUNCTIONS
9924 "F:"
9925# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009926#endif
9927 );
9928 if (opt <= 0)
9929 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009930 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009931 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009932 /* Possibilities:
9933 * sh ... -c 'script'
9934 * sh ... -c 'script' ARG0 [ARG1...]
9935 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009936 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009937 * "" needs to be replaced with NULL
9938 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009939 * Note: the form without ARG0 never happens:
9940 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009941 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009942 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009943 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009944 G.root_ppid = getppid();
9945 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009946 G.global_argv = argv + optind;
9947 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009948 if (builtin_argc) {
9949 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9950 const struct built_in_command *x;
9951
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009952 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009953 x = find_builtin(optarg);
9954 if (x) { /* paranoia */
9955 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9956 G.global_argv += builtin_argc;
9957 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009958 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009959 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009960 }
9961 goto final_return;
9962 }
9963 if (!G.global_argv[0]) {
9964 /* -c 'script' (no params): prevent empty $0 */
9965 G.global_argv--; /* points to argv[i] of 'script' */
9966 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009967 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009968 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009969 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009970 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009971 goto final_return;
9972 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009973 /* Well, we cannot just declare interactiveness,
9974 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009975 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009976 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009977 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009978 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009979 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009980 case 'l':
9981 flags |= OPT_login;
9982 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009983#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009984 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009985 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009986 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009987 case '$': {
9988 unsigned long long empty_trap_mask;
9989
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009990 G.root_pid = bb_strtou(optarg, &optarg, 16);
9991 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009992 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9993 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009994 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9995 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009996 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009997 optarg++;
9998 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009999 optarg++;
10000 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10001 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010002 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010003 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010004# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010005 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010006 for (sig = 1; sig < NSIG; sig++) {
10007 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010008 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010009 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010010 }
10011 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010012# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010013 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010014# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010015 optarg++;
10016 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010017# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010018# if ENABLE_HUSH_FUNCTIONS
10019 /* nommu uses re-exec trick for "... | func | ...",
10020 * should allow "return".
10021 * This accidentally allows returns in subshells.
10022 */
10023 G_flag_return_in_progress = -1;
10024# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010025 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010026 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010027 case 'R':
10028 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010029 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010030 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010031# if ENABLE_HUSH_FUNCTIONS
10032 case 'F': {
10033 struct function *funcp = new_function(optarg);
10034 /* funcp->name is already set to optarg */
10035 /* funcp->body is set to NULL. It's a special case. */
10036 funcp->body_as_string = argv[optind];
10037 optind++;
10038 break;
10039 }
10040# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010041#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010042 case 'n':
10043 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +020010044 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010045 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010046 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010047 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010048#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010049 fprintf(stderr, "Usage: sh [FILE]...\n"
10050 " or: sh -c command [args]...\n\n");
10051 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010052#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010053 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +000010054#endif
Eric Andersen25f27032001-04-26 23:22:31 +000010055 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010056 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010057
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010058 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10059 G.global_argc = argc - (optind - 1);
10060 G.global_argv = argv + (optind - 1);
10061 G.global_argv[0] = argv[0];
10062
Denys Vlasenkodea47882009-10-09 15:40:49 +020010063 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010064 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010065 G.root_ppid = getppid();
10066 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010067
10068 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010069 if (flags & OPT_login) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010070 HFILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010071 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010072 input = hfopen("/etc/profile");
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010073 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010074 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010075 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010076 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010077 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010078 /* bash: after sourcing /etc/profile,
10079 * tries to source (in the given order):
10080 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010081 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010082 * bash also sources ~/.bash_logout on exit.
10083 * If called as sh, skips .bash_XXX files.
10084 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010085 }
10086
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010087 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
10088 if (!(flags & OPT_s) && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010089 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010090 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010091 * "bash <script>" (which is never interactive (unless -i?))
10092 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010093 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010094 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010095 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010096 G.global_argc--;
10097 G.global_argv++;
10098 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010099 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010100 input = hfopen(G.global_argv[0]);
10101 if (!input) {
10102 bb_simple_perror_msg_and_die(G.global_argv[0]);
10103 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010104 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010105 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010106 parse_and_run_file(input);
10107#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010108 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010109#endif
10110 goto final_return;
10111 }
10112
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010113 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010114 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010115 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010116
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010117 /* A shell is interactive if the '-i' flag was given,
10118 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010119 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010120 * no arguments remaining or the -s flag given
10121 * standard input is a terminal
10122 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010123 * Refer to Posix.2, the description of the 'sh' utility.
10124 */
10125#if ENABLE_HUSH_JOB
10126 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010127 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10128 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10129 if (G_saved_tty_pgrp < 0)
10130 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010131
10132 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010133 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010134 if (G_interactive_fd < 0) {
10135 /* try to dup to any fd */
10136 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010137 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010138 /* give up */
10139 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010140 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010141 }
10142 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010143// TODO: track & disallow any attempts of user
10144// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +000010145 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010146 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010147 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010148 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010149
Mike Frysinger38478a62009-05-20 04:48:06 -040010150 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010151 /* If we were run as 'hush &', sleep until we are
10152 * in the foreground (tty pgrp == our pgrp).
10153 * If we get started under a job aware app (like bash),
10154 * make sure we are now in charge so we don't fight over
10155 * who gets the foreground */
10156 while (1) {
10157 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010158 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10159 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010160 break;
10161 /* send TTIN to ourself (should stop us) */
10162 kill(- shell_pgrp, SIGTTIN);
10163 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010164 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010165
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010166 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010167 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010168
Mike Frysinger38478a62009-05-20 04:48:06 -040010169 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010170 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010171 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010172 /* Put ourselves in our own process group
10173 * (bash, too, does this only if ctty is available) */
10174 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10175 /* Grab control of the terminal */
10176 tcsetpgrp(G_interactive_fd, getpid());
10177 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010178 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010179
10180# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10181 {
10182 const char *hp = get_local_var_value("HISTFILE");
10183 if (!hp) {
10184 hp = get_local_var_value("HOME");
10185 if (hp)
10186 hp = concat_path_file(hp, ".hush_history");
10187 } else {
10188 hp = xstrdup(hp);
10189 }
10190 if (hp) {
10191 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010192 //set_local_var(xasprintf("HISTFILE=%s", ...));
10193 }
10194# if ENABLE_FEATURE_SH_HISTFILESIZE
10195 hp = get_local_var_value("HISTFILESIZE");
10196 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10197# endif
10198 }
10199# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010200 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010201 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010202 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010203#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010204 /* No job control compiled in, only prompt/line editing */
10205 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010206 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010207 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010208 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010209 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010210 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010211 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010212 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010213 }
10214 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010215 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010216 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010217 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010218 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010219#else
10220 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010221 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010222#endif
10223 /* bash:
10224 * if interactive but not a login shell, sources ~/.bashrc
10225 * (--norc turns this off, --rcfile <file> overrides)
10226 */
10227
10228 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +020010229 /* note: ash and hush share this string */
10230 printf("\n\n%s %s\n"
10231 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10232 "\n",
10233 bb_banner,
10234 "hush - the humble shell"
10235 );
Mike Frysingerb2705e12009-03-23 08:44:02 +000010236 }
10237
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010238 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010239
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010240 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010241 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010242}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010243
10244
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010245/*
10246 * Built-ins
10247 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010248static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010249{
10250 return 0;
10251}
10252
Denys Vlasenko265062d2017-01-10 15:13:30 +010010253#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010254static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010255{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010256 int argc = string_array_len(argv);
10257 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010258}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010259#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010260#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010261static int FAST_FUNC builtin_test(char **argv)
10262{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010263 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010264}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010265#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010266#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010267static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010268{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010269 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010270}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010271#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010272#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010273static int FAST_FUNC builtin_printf(char **argv)
10274{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010275 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010276}
10277#endif
10278
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010279#if ENABLE_HUSH_HELP
10280static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10281{
10282 const struct built_in_command *x;
10283
10284 printf(
10285 "Built-in commands:\n"
10286 "------------------\n");
10287 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10288 if (x->b_descr)
10289 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10290 }
10291 return EXIT_SUCCESS;
10292}
10293#endif
10294
10295#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10296static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10297{
10298 show_history(G.line_input_state);
10299 return EXIT_SUCCESS;
10300}
10301#endif
10302
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010303static char **skip_dash_dash(char **argv)
10304{
10305 argv++;
10306 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10307 argv++;
10308 return argv;
10309}
10310
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010311static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010312{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010313 const char *newdir;
10314
10315 argv = skip_dash_dash(argv);
10316 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010317 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010318 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010319 * bash says "bash: cd: HOME not set" and does nothing
10320 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010321 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010322 const char *home = get_local_var_value("HOME");
10323 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010324 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010325 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010326 /* Mimic bash message exactly */
10327 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010328 return EXIT_FAILURE;
10329 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010330 /* Read current dir (get_cwd(1) is inside) and set PWD.
10331 * Note: do not enforce exporting. If PWD was unset or unexported,
10332 * set it again, but do not export. bash does the same.
10333 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010334 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010335 return EXIT_SUCCESS;
10336}
10337
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010338static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10339{
10340 puts(get_cwd(0));
10341 return EXIT_SUCCESS;
10342}
10343
10344static int FAST_FUNC builtin_eval(char **argv)
10345{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010346 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010347
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010348 if (!argv[0])
10349 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010350
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010351 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010352 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010353 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010354 /* bash:
10355 * eval "echo Hi; done" ("done" is syntax error):
10356 * "echo Hi" will not execute too.
10357 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010358 parse_and_run_string(argv[0]);
10359 } else {
10360 /* "The eval utility shall construct a command by
10361 * concatenating arguments together, separating
10362 * each with a <space> character."
10363 */
10364 char *str, *p;
10365 unsigned len = 0;
10366 char **pp = argv;
10367 do
10368 len += strlen(*pp) + 1;
10369 while (*++pp);
10370 str = p = xmalloc(len);
10371 pp = argv;
10372 for (;;) {
10373 p = stpcpy(p, *pp);
10374 pp++;
10375 if (!*pp)
10376 break;
10377 *p++ = ' ';
10378 }
10379 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010380 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010381 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010382 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010383 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010384 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010385}
10386
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010387static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010388{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010389 argv = skip_dash_dash(argv);
10390 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010391 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010392
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010393 /* Careful: we can end up here after [v]fork. Do not restore
10394 * tty pgrp then, only top-level shell process does that */
10395 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10396 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10397
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010398 /* Saved-redirect fds, script fds and G_interactive_fd are still
10399 * open here. However, they are all CLOEXEC, and execv below
10400 * closes them. Try interactive "exec ls -l /proc/self/fd",
10401 * it should show no extra open fds in the "ls" process.
10402 * If we'd try to run builtins/NOEXECs, this would need improving.
10403 */
10404 //close_saved_fds_and_FILE_fds();
10405
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010406 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010407 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010408 * and tcsetpgrp, and this is inherently racy.
10409 */
10410 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010411}
10412
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010413static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010414{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010415 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010416
10417 /* interactive bash:
10418 * # trap "echo EEE" EXIT
10419 * # exit
10420 * exit
10421 * There are stopped jobs.
10422 * (if there are _stopped_ jobs, running ones don't count)
10423 * # exit
10424 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010425 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010426 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010427 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010428 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010429
10430 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010431 argv = skip_dash_dash(argv);
10432 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010433 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010434 /* mimic bash: exit 123abc == exit 255 + error msg */
10435 xfunc_error_retval = 255;
10436 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010437 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010438}
10439
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010440#if ENABLE_HUSH_TYPE
10441/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10442static int FAST_FUNC builtin_type(char **argv)
10443{
10444 int ret = EXIT_SUCCESS;
10445
10446 while (*++argv) {
10447 const char *type;
10448 char *path = NULL;
10449
10450 if (0) {} /* make conditional compile easier below */
10451 /*else if (find_alias(*argv))
10452 type = "an alias";*/
10453#if ENABLE_HUSH_FUNCTIONS
10454 else if (find_function(*argv))
10455 type = "a function";
10456#endif
10457 else if (find_builtin(*argv))
10458 type = "a shell builtin";
10459 else if ((path = find_in_path(*argv)) != NULL)
10460 type = path;
10461 else {
10462 bb_error_msg("type: %s: not found", *argv);
10463 ret = EXIT_FAILURE;
10464 continue;
10465 }
10466
10467 printf("%s is %s\n", *argv, type);
10468 free(path);
10469 }
10470
10471 return ret;
10472}
10473#endif
10474
10475#if ENABLE_HUSH_READ
10476/* Interruptibility of read builtin in bash
10477 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10478 *
10479 * Empty trap makes read ignore corresponding signal, for any signal.
10480 *
10481 * SIGINT:
10482 * - terminates non-interactive shell;
10483 * - interrupts read in interactive shell;
10484 * if it has non-empty trap:
10485 * - executes trap and returns to command prompt in interactive shell;
10486 * - executes trap and returns to read in non-interactive shell;
10487 * SIGTERM:
10488 * - is ignored (does not interrupt) read in interactive shell;
10489 * - terminates non-interactive shell;
10490 * if it has non-empty trap:
10491 * - executes trap and returns to read;
10492 * SIGHUP:
10493 * - terminates shell (regardless of interactivity);
10494 * if it has non-empty trap:
10495 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010496 * SIGCHLD from children:
10497 * - does not interrupt read regardless of interactivity:
10498 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010499 */
10500static int FAST_FUNC builtin_read(char **argv)
10501{
10502 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010503 struct builtin_read_params params;
10504
10505 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010506
10507 /* "!": do not abort on errors.
10508 * Option string must start with "sr" to match BUILTIN_READ_xxx
10509 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010510 params.read_flags = getopt32(argv,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010511#if BASH_READ_D
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010512 "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010513#else
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010514 "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010515#endif
10516 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010517 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010518 return EXIT_FAILURE;
10519 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010520 params.argv = argv;
10521 params.setvar = set_local_var_from_halves;
10522 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010523
10524 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010525 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010526
10527 if ((uintptr_t)r == 1 && errno == EINTR) {
10528 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010529 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010530 goto again;
10531 }
10532
10533 if ((uintptr_t)r > 1) {
10534 bb_error_msg("%s", r);
10535 r = (char*)(uintptr_t)1;
10536 }
10537
10538 return (uintptr_t)r;
10539}
10540#endif
10541
10542#if ENABLE_HUSH_UMASK
10543static int FAST_FUNC builtin_umask(char **argv)
10544{
10545 int rc;
10546 mode_t mask;
10547
10548 rc = 1;
10549 mask = umask(0);
10550 argv = skip_dash_dash(argv);
10551 if (argv[0]) {
10552 mode_t old_mask = mask;
10553
10554 /* numeric umasks are taken as-is */
10555 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10556 if (!isdigit(argv[0][0]))
10557 mask ^= 0777;
10558 mask = bb_parse_mode(argv[0], mask);
10559 if (!isdigit(argv[0][0]))
10560 mask ^= 0777;
10561 if ((unsigned)mask > 0777) {
10562 mask = old_mask;
10563 /* bash messages:
10564 * bash: umask: 'q': invalid symbolic mode operator
10565 * bash: umask: 999: octal number out of range
10566 */
10567 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10568 rc = 0;
10569 }
10570 } else {
10571 /* Mimic bash */
10572 printf("%04o\n", (unsigned) mask);
10573 /* fall through and restore mask which we set to 0 */
10574 }
10575 umask(mask);
10576
10577 return !rc; /* rc != 0 - success */
10578}
10579#endif
10580
Denys Vlasenko41ade052017-01-08 18:56:24 +010010581#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010582static void print_escaped(const char *s)
10583{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010584 if (*s == '\'')
10585 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010586 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010587 const char *p = strchrnul(s, '\'');
10588 /* print 'xxxx', possibly just '' */
10589 printf("'%.*s'", (int)(p - s), s);
10590 if (*p == '\0')
10591 break;
10592 s = p;
10593 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010594 /* s points to '; print "'''...'''" */
10595 putchar('"');
10596 do putchar('\''); while (*++s == '\'');
10597 putchar('"');
10598 } while (*s);
10599}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010600#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010601
Denys Vlasenko1e660422017-07-17 21:10:50 +020010602#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010603static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010604{
10605 do {
10606 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010607 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010608
10609 /* So far we do not check that name is valid (TODO?) */
10610
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010611 if (*name_end == '\0') {
10612 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010613
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010614 vpp = get_ptr_to_local_var(name, name_end - name);
10615 var = vpp ? *vpp : NULL;
10616
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010617 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010618 /* export -n NAME (without =VALUE) */
10619 if (var) {
10620 var->flg_export = 0;
10621 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10622 unsetenv(name);
10623 } /* else: export -n NOT_EXISTING_VAR: no-op */
10624 continue;
10625 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010626 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010627 /* export NAME (without =VALUE) */
10628 if (var) {
10629 var->flg_export = 1;
10630 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10631 putenv(var->varstr);
10632 continue;
10633 }
10634 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010635 if (flags & SETFLAG_MAKE_RO) {
10636 /* readonly NAME (without =VALUE) */
10637 if (var) {
10638 var->flg_read_only = 1;
10639 continue;
10640 }
10641 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010642# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010643 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010644 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010645 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10646 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010647 /* "local x=abc; ...; local x" - ignore second local decl */
10648 continue;
10649 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010650 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010651# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010652 /* Exporting non-existing variable.
10653 * bash does not put it in environment,
10654 * but remembers that it is exported,
10655 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010656 * We just set it to "" and export.
10657 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010658 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010659 * bash sets the value to "".
10660 */
10661 /* Or, it's "readonly NAME" (without =VALUE).
10662 * bash remembers NAME and disallows its creation
10663 * in the future.
10664 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010665 name = xasprintf("%s=", name);
10666 } else {
10667 /* (Un)exporting/making local NAME=VALUE */
10668 name = xstrdup(name);
10669 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010670 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010671 if (set_local_var(name, flags))
10672 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010673 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010674 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010675}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010676#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010677
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010678#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010679static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010680{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010681 unsigned opt_unexport;
10682
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010683#if ENABLE_HUSH_EXPORT_N
10684 /* "!": do not abort on errors */
10685 opt_unexport = getopt32(argv, "!n");
10686 if (opt_unexport == (uint32_t)-1)
10687 return EXIT_FAILURE;
10688 argv += optind;
10689#else
10690 opt_unexport = 0;
10691 argv++;
10692#endif
10693
10694 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010695 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010696 if (e) {
10697 while (*e) {
10698#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010699 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010700#else
10701 /* ash emits: export VAR='VAL'
10702 * bash: declare -x VAR="VAL"
10703 * we follow ash example */
10704 const char *s = *e++;
10705 const char *p = strchr(s, '=');
10706
10707 if (!p) /* wtf? take next variable */
10708 continue;
10709 /* export var= */
10710 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010711 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010712 putchar('\n');
10713#endif
10714 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010715 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010716 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010717 return EXIT_SUCCESS;
10718 }
10719
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010720 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010721}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010722#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010723
Denys Vlasenko295fef82009-06-03 12:47:26 +020010724#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010725static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010726{
10727 if (G.func_nest_level == 0) {
10728 bb_error_msg("%s: not in a function", argv[0]);
10729 return EXIT_FAILURE; /* bash compat */
10730 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010731 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010732 /* Since all builtins run in a nested variable level,
10733 * need to use level - 1 here. Or else the variable will be removed at once
10734 * after builtin returns.
10735 */
10736 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010737}
10738#endif
10739
Denys Vlasenko1e660422017-07-17 21:10:50 +020010740#if ENABLE_HUSH_READONLY
10741static int FAST_FUNC builtin_readonly(char **argv)
10742{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010743 argv++;
10744 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010745 /* bash: readonly [-p]: list all readonly VARs
10746 * (-p has no effect in bash)
10747 */
10748 struct variable *e;
10749 for (e = G.top_var; e; e = e->next) {
10750 if (e->flg_read_only) {
10751//TODO: quote value: readonly VAR='VAL'
10752 printf("readonly %s\n", e->varstr);
10753 }
10754 }
10755 return EXIT_SUCCESS;
10756 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010757 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010758}
10759#endif
10760
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010761#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010762/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10763static int FAST_FUNC builtin_unset(char **argv)
10764{
10765 int ret;
10766 unsigned opts;
10767
10768 /* "!": do not abort on errors */
10769 /* "+": stop at 1st non-option */
10770 opts = getopt32(argv, "!+vf");
10771 if (opts == (unsigned)-1)
10772 return EXIT_FAILURE;
10773 if (opts == 3) {
10774 bb_error_msg("unset: -v and -f are exclusive");
10775 return EXIT_FAILURE;
10776 }
10777 argv += optind;
10778
10779 ret = EXIT_SUCCESS;
10780 while (*argv) {
10781 if (!(opts & 2)) { /* not -f */
10782 if (unset_local_var(*argv)) {
10783 /* unset <nonexistent_var> doesn't fail.
10784 * Error is when one tries to unset RO var.
10785 * Message was printed by unset_local_var. */
10786 ret = EXIT_FAILURE;
10787 }
10788 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010789# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010790 else {
10791 unset_func(*argv);
10792 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010793# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010794 argv++;
10795 }
10796 return ret;
10797}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010798#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010799
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010800#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010801/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10802 * built-in 'set' handler
10803 * SUSv3 says:
10804 * set [-abCefhmnuvx] [-o option] [argument...]
10805 * set [+abCefhmnuvx] [+o option] [argument...]
10806 * set -- [argument...]
10807 * set -o
10808 * set +o
10809 * Implementations shall support the options in both their hyphen and
10810 * plus-sign forms. These options can also be specified as options to sh.
10811 * Examples:
10812 * Write out all variables and their values: set
10813 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10814 * Turn on the -x and -v options: set -xv
10815 * Unset all positional parameters: set --
10816 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10817 * Set the positional parameters to the expansion of x, even if x expands
10818 * with a leading '-' or '+': set -- $x
10819 *
10820 * So far, we only support "set -- [argument...]" and some of the short names.
10821 */
10822static int FAST_FUNC builtin_set(char **argv)
10823{
10824 int n;
10825 char **pp, **g_argv;
10826 char *arg = *++argv;
10827
10828 if (arg == NULL) {
10829 struct variable *e;
10830 for (e = G.top_var; e; e = e->next)
10831 puts(e->varstr);
10832 return EXIT_SUCCESS;
10833 }
10834
10835 do {
10836 if (strcmp(arg, "--") == 0) {
10837 ++argv;
10838 goto set_argv;
10839 }
10840 if (arg[0] != '+' && arg[0] != '-')
10841 break;
10842 for (n = 1; arg[n]; ++n) {
10843 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10844 goto error;
10845 if (arg[n] == 'o' && argv[1])
10846 argv++;
10847 }
10848 } while ((arg = *++argv) != NULL);
10849 /* Now argv[0] is 1st argument */
10850
10851 if (arg == NULL)
10852 return EXIT_SUCCESS;
10853 set_argv:
10854
10855 /* NB: G.global_argv[0] ($0) is never freed/changed */
10856 g_argv = G.global_argv;
10857 if (G.global_args_malloced) {
10858 pp = g_argv;
10859 while (*++pp)
10860 free(*pp);
10861 g_argv[1] = NULL;
10862 } else {
10863 G.global_args_malloced = 1;
10864 pp = xzalloc(sizeof(pp[0]) * 2);
10865 pp[0] = g_argv[0]; /* retain $0 */
10866 g_argv = pp;
10867 }
10868 /* This realloc's G.global_argv */
10869 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10870
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010871 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010872
10873 return EXIT_SUCCESS;
10874
10875 /* Nothing known, so abort */
10876 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010877 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010878 return EXIT_FAILURE;
10879}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010880#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010881
10882static int FAST_FUNC builtin_shift(char **argv)
10883{
10884 int n = 1;
10885 argv = skip_dash_dash(argv);
10886 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010887 n = bb_strtou(argv[0], NULL, 10);
10888 if (errno || n < 0) {
10889 /* shared string with ash.c */
10890 bb_error_msg("Illegal number: %s", argv[0]);
10891 /*
10892 * ash aborts in this case.
10893 * bash prints error message and set $? to 1.
10894 * Interestingly, for "shift 99999" bash does not
10895 * print error message, but does set $? to 1
10896 * (and does no shifting at all).
10897 */
10898 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010899 }
10900 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010901 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010902 int m = 1;
10903 while (m <= n)
10904 free(G.global_argv[m++]);
10905 }
10906 G.global_argc -= n;
10907 memmove(&G.global_argv[1], &G.global_argv[n+1],
10908 G.global_argc * sizeof(G.global_argv[0]));
10909 return EXIT_SUCCESS;
10910 }
10911 return EXIT_FAILURE;
10912}
10913
Denys Vlasenko74d40582017-08-11 01:32:46 +020010914#if ENABLE_HUSH_GETOPTS
10915static int FAST_FUNC builtin_getopts(char **argv)
10916{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010917/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10918
Denys Vlasenko74d40582017-08-11 01:32:46 +020010919TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010920If a required argument is not found, and getopts is not silent,
10921a question mark (?) is placed in VAR, OPTARG is unset, and a
10922diagnostic message is printed. If getopts is silent, then a
10923colon (:) is placed in VAR and OPTARG is set to the option
10924character found.
10925
10926Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010927
10928"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010929*/
10930 char cbuf[2];
10931 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010932 int c, n, exitcode, my_opterr;
10933 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010934
10935 optstring = *++argv;
10936 if (!optstring || !(var = *++argv)) {
10937 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10938 return EXIT_FAILURE;
10939 }
10940
Denys Vlasenko238ff982017-08-29 13:38:30 +020010941 if (argv[1])
10942 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10943 else
10944 argv = G.global_argv;
10945 cbuf[1] = '\0';
10946
10947 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010948 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010949 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010950 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010951 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010952 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010953
10954 /* getopts stops on first non-option. Add "+" to force that */
10955 /*if (optstring[0] != '+')*/ {
10956 char *s = alloca(strlen(optstring) + 2);
10957 sprintf(s, "+%s", optstring);
10958 optstring = s;
10959 }
10960
Denys Vlasenko238ff982017-08-29 13:38:30 +020010961 /* Naively, now we should just
10962 * cp = get_local_var_value("OPTIND");
10963 * optind = cp ? atoi(cp) : 0;
10964 * optarg = NULL;
10965 * opterr = my_opterr;
10966 * c = getopt(string_array_len(argv), argv, optstring);
10967 * and be done? Not so fast...
10968 * Unlike normal getopt() usage in C programs, here
10969 * each successive call will (usually) have the same argv[] CONTENTS,
10970 * but not the ADDRESSES. Worse yet, it's possible that between
10971 * invocations of "getopts", there will be calls to shell builtins
10972 * which use getopt() internally. Example:
10973 * while getopts "abc" RES -a -bc -abc de; do
10974 * unset -ff func
10975 * done
10976 * This would not work correctly: getopt() call inside "unset"
10977 * modifies internal libc state which is tracking position in
10978 * multi-option strings ("-abc"). At best, it can skip options
10979 * or return the same option infinitely. With glibc implementation
10980 * of getopt(), it would use outright invalid pointers and return
10981 * garbage even _without_ "unset" mangling internal state.
10982 *
10983 * We resort to resetting getopt() state and calling it N times,
10984 * until we get Nth result (or failure).
10985 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10986 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010987 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010988 count = 0;
10989 n = string_array_len(argv);
10990 do {
10991 optarg = NULL;
10992 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10993 c = getopt(n, argv, optstring);
10994 if (c < 0)
10995 break;
10996 count++;
10997 } while (count <= G.getopt_count);
10998
10999 /* Set OPTIND. Prevent resetting of the magic counter! */
11000 set_local_var_from_halves("OPTIND", utoa(optind));
11001 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011002 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011003
11004 /* Set OPTARG */
11005 /* Always set or unset, never left as-is, even on exit/error:
11006 * "If no option was found, or if the option that was found
11007 * does not have an option-argument, OPTARG shall be unset."
11008 */
11009 cp = optarg;
11010 if (c == '?') {
11011 /* If ":optstring" and unknown option is seen,
11012 * it is stored to OPTARG.
11013 */
11014 if (optstring[1] == ':') {
11015 cbuf[0] = optopt;
11016 cp = cbuf;
11017 }
11018 }
11019 if (cp)
11020 set_local_var_from_halves("OPTARG", cp);
11021 else
11022 unset_local_var("OPTARG");
11023
11024 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011025 exitcode = EXIT_SUCCESS;
11026 if (c < 0) { /* -1: end of options */
11027 exitcode = EXIT_FAILURE;
11028 c = '?';
11029 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011030
Denys Vlasenko238ff982017-08-29 13:38:30 +020011031 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011032 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011033 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011034
Denys Vlasenko74d40582017-08-11 01:32:46 +020011035 return exitcode;
11036}
11037#endif
11038
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011039static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011040{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011041 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011042 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011043 save_arg_t sv;
11044 char *args_need_save;
11045#if ENABLE_HUSH_FUNCTIONS
11046 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011047#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011048
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011049 argv = skip_dash_dash(argv);
11050 filename = argv[0];
11051 if (!filename) {
11052 /* bash says: "bash: .: filename argument required" */
11053 return 2; /* bash compat */
11054 }
11055 arg_path = NULL;
11056 if (!strchr(filename, '/')) {
11057 arg_path = find_in_path(filename);
11058 if (arg_path)
11059 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011060 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011061 errno = ENOENT;
11062 bb_simple_perror_msg(filename);
11063 return EXIT_FAILURE;
11064 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011065 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011066 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011067 free(arg_path);
11068 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011069 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011070 /* POSIX: non-interactive shell should abort here,
11071 * not merely fail. So far no one complained :)
11072 */
11073 return EXIT_FAILURE;
11074 }
11075
11076#if ENABLE_HUSH_FUNCTIONS
11077 sv_flg = G_flag_return_in_progress;
11078 /* "we are inside sourced file, ok to use return" */
11079 G_flag_return_in_progress = -1;
11080#endif
11081 args_need_save = argv[1]; /* used as a boolean variable */
11082 if (args_need_save)
11083 save_and_replace_G_args(&sv, argv);
11084
11085 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11086 G.last_exitcode = 0;
11087 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011088 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011089
11090 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11091 restore_G_args(&sv, argv);
11092#if ENABLE_HUSH_FUNCTIONS
11093 G_flag_return_in_progress = sv_flg;
11094#endif
11095
11096 return G.last_exitcode;
11097}
11098
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011099#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011100static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011101{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011102 int sig;
11103 char *new_cmd;
11104
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011105 if (!G_traps)
11106 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011107
11108 argv++;
11109 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011110 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011111 /* No args: print all trapped */
11112 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011113 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011114 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011115 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011116 /* note: bash adds "SIG", but only if invoked
11117 * as "bash". If called as "sh", or if set -o posix,
11118 * then it prints short signal names.
11119 * We are printing short names: */
11120 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011121 }
11122 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011123 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011124 return EXIT_SUCCESS;
11125 }
11126
11127 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011128 /* If first arg is a number: reset all specified signals */
11129 sig = bb_strtou(*argv, NULL, 10);
11130 if (errno == 0) {
11131 int ret;
11132 process_sig_list:
11133 ret = EXIT_SUCCESS;
11134 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011135 sighandler_t handler;
11136
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011137 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011138 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011139 ret = EXIT_FAILURE;
11140 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011141 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011142 continue;
11143 }
11144
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011145 free(G_traps[sig]);
11146 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011147
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011148 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011149 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011150
11151 /* There is no signal for 0 (EXIT) */
11152 if (sig == 0)
11153 continue;
11154
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011155 if (new_cmd)
11156 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11157 else
11158 /* We are removing trap handler */
11159 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011160 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011161 }
11162 return ret;
11163 }
11164
11165 if (!argv[1]) { /* no second arg */
11166 bb_error_msg("trap: invalid arguments");
11167 return EXIT_FAILURE;
11168 }
11169
11170 /* First arg is "-": reset all specified to default */
11171 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11172 /* Everything else: set arg as signal handler
11173 * (includes "" case, which ignores signal) */
11174 if (argv[0][0] == '-') {
11175 if (argv[0][1] == '\0') { /* "-" */
11176 /* new_cmd remains NULL: "reset these sigs" */
11177 goto reset_traps;
11178 }
11179 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11180 argv++;
11181 }
11182 /* else: "-something", no special meaning */
11183 }
11184 new_cmd = *argv;
11185 reset_traps:
11186 argv++;
11187 goto process_sig_list;
11188}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011189#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011190
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011191#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011192static struct pipe *parse_jobspec(const char *str)
11193{
11194 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011195 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011196
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011197 if (sscanf(str, "%%%u", &jobnum) != 1) {
11198 if (str[0] != '%'
11199 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11200 ) {
11201 bb_error_msg("bad argument '%s'", str);
11202 return NULL;
11203 }
11204 /* It is "%%", "%+" or "%" - current job */
11205 jobnum = G.last_jobid;
11206 if (jobnum == 0) {
11207 bb_error_msg("no current job");
11208 return NULL;
11209 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011210 }
11211 for (pi = G.job_list; pi; pi = pi->next) {
11212 if (pi->jobid == jobnum) {
11213 return pi;
11214 }
11215 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011216 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011217 return NULL;
11218}
11219
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011220static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11221{
11222 struct pipe *job;
11223 const char *status_string;
11224
11225 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11226 for (job = G.job_list; job; job = job->next) {
11227 if (job->alive_cmds == job->stopped_cmds)
11228 status_string = "Stopped";
11229 else
11230 status_string = "Running";
11231
11232 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11233 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011234
11235 clean_up_last_dead_job();
11236
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011237 return EXIT_SUCCESS;
11238}
11239
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011240/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011241static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011242{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011243 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011244 struct pipe *pi;
11245
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011246 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011247 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011248
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011249 /* If they gave us no args, assume they want the last backgrounded task */
11250 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011251 for (pi = G.job_list; pi; pi = pi->next) {
11252 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011253 goto found;
11254 }
11255 }
11256 bb_error_msg("%s: no current job", argv[0]);
11257 return EXIT_FAILURE;
11258 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011259
11260 pi = parse_jobspec(argv[1]);
11261 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011262 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011263 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011264 /* TODO: bash prints a string representation
11265 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011266 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011267 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011268 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011269 }
11270
11271 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011272 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11273 for (i = 0; i < pi->num_cmds; i++) {
11274 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011275 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011276 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011277
11278 i = kill(- pi->pgrp, SIGCONT);
11279 if (i < 0) {
11280 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011281 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011282 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011283 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011284 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011285 }
11286
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011287 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011288 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011289 return checkjobs_and_fg_shell(pi);
11290 }
11291 return EXIT_SUCCESS;
11292}
11293#endif
11294
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011295#if ENABLE_HUSH_KILL
11296static int FAST_FUNC builtin_kill(char **argv)
11297{
11298 int ret = 0;
11299
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011300# if ENABLE_HUSH_JOB
11301 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11302 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011303
11304 do {
11305 struct pipe *pi;
11306 char *dst;
11307 int j, n;
11308
11309 if (argv[i][0] != '%')
11310 continue;
11311 /*
11312 * "kill %N" - job kill
11313 * Converting to pgrp / pid kill
11314 */
11315 pi = parse_jobspec(argv[i]);
11316 if (!pi) {
11317 /* Eat bad jobspec */
11318 j = i;
11319 do {
11320 j++;
11321 argv[j - 1] = argv[j];
11322 } while (argv[j]);
11323 ret = 1;
11324 i--;
11325 continue;
11326 }
11327 /*
11328 * In jobs started under job control, we signal
11329 * entire process group by kill -PGRP_ID.
11330 * This happens, f.e., in interactive shell.
11331 *
11332 * Otherwise, we signal each child via
11333 * kill PID1 PID2 PID3.
11334 * Testcases:
11335 * sh -c 'sleep 1|sleep 1 & kill %1'
11336 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11337 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11338 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011339 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011340 dst = alloca(n * sizeof(int)*4);
11341 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011342 if (G_interactive_fd)
11343 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011344 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011345 struct command *cmd = &pi->cmds[j];
11346 /* Skip exited members of the job */
11347 if (cmd->pid == 0)
11348 continue;
11349 /*
11350 * kill_main has matching code to expect
11351 * leading space. Needed to not confuse
11352 * negative pids with "kill -SIGNAL_NO" syntax
11353 */
11354 dst += sprintf(dst, " %u", (int)cmd->pid);
11355 }
11356 *dst = '\0';
11357 } while (argv[++i]);
11358 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011359# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011360
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011361 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011362 ret = run_applet_main(argv, kill_main);
11363 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011364 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011365 return ret;
11366}
11367#endif
11368
11369#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011370/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011371#if !ENABLE_HUSH_JOB
11372# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11373#endif
11374static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011375{
11376 int ret = 0;
11377 for (;;) {
11378 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011379 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011380
Denys Vlasenko830ea352016-11-08 04:59:11 +010011381 if (!sigisemptyset(&G.pending_set))
11382 goto check_sig;
11383
Denys Vlasenko7e675362016-10-28 21:57:31 +020011384 /* waitpid is not interruptible by SA_RESTARTed
11385 * signals which we use. Thus, this ugly dance:
11386 */
11387
11388 /* Make sure possible SIGCHLD is stored in kernel's
11389 * pending signal mask before we call waitpid.
11390 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011391 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011392 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011393 sigfillset(&oldset); /* block all signals, remember old set */
11394 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011395
11396 if (!sigisemptyset(&G.pending_set)) {
11397 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011398 goto restore;
11399 }
11400
11401 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011402/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011403 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011404 debug_printf_exec("checkjobs:%d\n", ret);
11405#if ENABLE_HUSH_JOB
11406 if (waitfor_pipe) {
11407 int rcode = job_exited_or_stopped(waitfor_pipe);
11408 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11409 if (rcode >= 0) {
11410 ret = rcode;
11411 sigprocmask(SIG_SETMASK, &oldset, NULL);
11412 break;
11413 }
11414 }
11415#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011416 /* if ECHILD, there are no children (ret is -1 or 0) */
11417 /* if ret == 0, no children changed state */
11418 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011419 if (errno == ECHILD || ret) {
11420 ret--;
11421 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011422 ret = 0;
11423 sigprocmask(SIG_SETMASK, &oldset, NULL);
11424 break;
11425 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011426 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011427 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11428 /* Note: sigsuspend invokes signal handler */
11429 sigsuspend(&oldset);
11430 restore:
11431 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011432 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011433 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011434 sig = check_and_run_traps();
11435 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011436 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011437 ret = 128 + sig;
11438 break;
11439 }
11440 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11441 }
11442 return ret;
11443}
11444
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011445static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011446{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011447 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011448 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011449
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011450 argv = skip_dash_dash(argv);
11451 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011452 /* Don't care about wait results */
11453 /* Note 1: must wait until there are no more children */
11454 /* Note 2: must be interruptible */
11455 /* Examples:
11456 * $ sleep 3 & sleep 6 & wait
11457 * [1] 30934 sleep 3
11458 * [2] 30935 sleep 6
11459 * [1] Done sleep 3
11460 * [2] Done sleep 6
11461 * $ sleep 3 & sleep 6 & wait
11462 * [1] 30936 sleep 3
11463 * [2] 30937 sleep 6
11464 * [1] Done sleep 3
11465 * ^C <-- after ~4 sec from keyboard
11466 * $
11467 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011468 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011469 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011470
Denys Vlasenko7e675362016-10-28 21:57:31 +020011471 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011472 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011473 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011474#if ENABLE_HUSH_JOB
11475 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011476 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011477 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011478 wait_pipe = parse_jobspec(*argv);
11479 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011480 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011481 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011482 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011483 } else {
11484 /* waiting on "last dead job" removes it */
11485 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011486 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011487 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011488 /* else: parse_jobspec() already emitted error msg */
11489 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011490 }
11491#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011492 /* mimic bash message */
11493 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011494 ret = EXIT_FAILURE;
11495 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011496 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011497
Denys Vlasenko7e675362016-10-28 21:57:31 +020011498 /* Do we have such child? */
11499 ret = waitpid(pid, &status, WNOHANG);
11500 if (ret < 0) {
11501 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011502 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011503 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011504 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011505 /* "wait $!" but last bg task has already exited. Try:
11506 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11507 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011508 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011509 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011510 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011511 } else {
11512 /* Example: "wait 1". mimic bash message */
11513 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011514 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011515 } else {
11516 /* ??? */
11517 bb_perror_msg("wait %s", *argv);
11518 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011519 continue; /* bash checks all argv[] */
11520 }
11521 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011522 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011523 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011524 } else {
11525 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011526 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011527 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011528 if (WIFSIGNALED(status))
11529 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011530 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011531 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011532
11533 return ret;
11534}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011535#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011536
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011537#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11538static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11539{
11540 if (argv[1]) {
11541 def = bb_strtou(argv[1], NULL, 10);
11542 if (errno || def < def_min || argv[2]) {
11543 bb_error_msg("%s: bad arguments", argv[0]);
11544 def = UINT_MAX;
11545 }
11546 }
11547 return def;
11548}
11549#endif
11550
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011551#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011552static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011553{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011554 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011555 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011556 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011557 /* if we came from builtin_continue(), need to undo "= 1" */
11558 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011559 return EXIT_SUCCESS; /* bash compat */
11560 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011561 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011562
11563 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11564 if (depth == UINT_MAX)
11565 G.flag_break_continue = BC_BREAK;
11566 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011567 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011568
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011569 return EXIT_SUCCESS;
11570}
11571
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011572static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011573{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011574 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11575 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011576}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011577#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011578
11579#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011580static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011581{
11582 int rc;
11583
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011584 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011585 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11586 return EXIT_FAILURE; /* bash compat */
11587 }
11588
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011589 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011590
11591 /* bash:
11592 * out of range: wraps around at 256, does not error out
11593 * non-numeric param:
11594 * f() { false; return qwe; }; f; echo $?
11595 * bash: return: qwe: numeric argument required <== we do this
11596 * 255 <== we also do this
11597 */
11598 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11599 return rc;
11600}
11601#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011602
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011603#if ENABLE_HUSH_TIMES
11604static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11605{
11606 static const uint8_t times_tbl[] ALIGN1 = {
11607 ' ', offsetof(struct tms, tms_utime),
11608 '\n', offsetof(struct tms, tms_stime),
11609 ' ', offsetof(struct tms, tms_cutime),
11610 '\n', offsetof(struct tms, tms_cstime),
11611 0
11612 };
11613 const uint8_t *p;
11614 unsigned clk_tck;
11615 struct tms buf;
11616
11617 clk_tck = bb_clk_tck();
11618
11619 times(&buf);
11620 p = times_tbl;
11621 do {
11622 unsigned sec, frac;
11623 unsigned long t;
11624 t = *(clock_t *)(((char *) &buf) + p[1]);
11625 sec = t / clk_tck;
11626 frac = t % clk_tck;
11627 printf("%um%u.%03us%c",
11628 sec / 60, sec % 60,
11629 (frac * 1000) / clk_tck,
11630 p[0]);
11631 p += 2;
11632 } while (*p);
11633
11634 return EXIT_SUCCESS;
11635}
11636#endif
11637
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011638#if ENABLE_HUSH_MEMLEAK
11639static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11640{
11641 void *p;
11642 unsigned long l;
11643
11644# ifdef M_TRIM_THRESHOLD
11645 /* Optional. Reduces probability of false positives */
11646 malloc_trim(0);
11647# endif
11648 /* Crude attempt to find where "free memory" starts,
11649 * sans fragmentation. */
11650 p = malloc(240);
11651 l = (unsigned long)p;
11652 free(p);
11653 p = malloc(3400);
11654 if (l < (unsigned long)p) l = (unsigned long)p;
11655 free(p);
11656
11657
11658# if 0 /* debug */
11659 {
11660 struct mallinfo mi = mallinfo();
11661 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11662 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11663 }
11664# endif
11665
11666 if (!G.memleak_value)
11667 G.memleak_value = l;
11668
11669 l -= G.memleak_value;
11670 if ((long)l < 0)
11671 l = 0;
11672 l /= 1024;
11673 if (l > 127)
11674 l = 127;
11675
11676 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11677 return l;
11678}
11679#endif