blob: 051b123e788c225a083c17a76a0108481d924e57 [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)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020066 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020067 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
68 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
69 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020070 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020071 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
72 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020073 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020074 * indirect expansion: ${!VAR}
75 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020076 *
77 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020078 * Some builtins mandated by standards:
79 * newgrp [GRP]: not a builtin in bash but a suid binary
80 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020081 *
82 * Status of [[ support:
83 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
84 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020085 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenkod2241f52020-10-31 03:34:07 +010086 * = is glob match operator, not equality operator: STR = GLOB
Denys Vlasenkod2241f52020-10-31 03:34:07 +010087 * == same as =
88 * =~ is regex match operator: STR =~ REGEX
Denys Vlasenko3632cb12018-04-10 15:25:41 +020089 * TODO:
Denys Vlasenko3632cb12018-04-10 15:25:41 +020090 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
Denys Vlasenkoa7c06532020-10-31 04:32:34 +010091 * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
Eric Andersen25f27032001-04-26 23:22:31 +000092 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020093//config:config HUSH
Denys Vlasenkob097a842018-12-28 03:20:17 +010094//config: bool "hush (68 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +020096//config: select SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020098//config: hush is a small shell. It handles the normal flow control
99//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
100//config: case/esac. Redirections, here documents, $((arithmetic))
101//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200102//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200103//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200104//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200105//config: It does not handle select, aliases, tilde expansion,
106//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200107//config:
Denys Vlasenko67e15292020-06-24 13:39:13 +0200108// This option is visible (has a description) to make it possible to select
109// a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
110//config:config SHELL_HUSH
111//config: bool "Internal shell for embedded script support"
112//config: default n
113//config:
114//config:# hush options
115//config:# It's only needed to get "nice" menuconfig indenting.
116//config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
117//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200118//config:config HUSH_BASH_COMPAT
119//config: bool "bash-compatible extensions"
120//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200121//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200122//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200123//config:config HUSH_BRACE_EXPANSION
124//config: bool "Brace expansion"
125//config: default y
126//config: depends on HUSH_BASH_COMPAT
127//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200128//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200129//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100130//config:config HUSH_BASH_SOURCE_CURDIR
131//config: bool "'source' and '.' builtins search current directory after $PATH"
132//config: default n # do not encourage non-standard behavior
133//config: depends on HUSH_BASH_COMPAT
134//config: help
135//config: This is not compliant with standards. Avoid if possible.
136//config:
Denys Vlasenkocbfdeba2021-03-10 16:31:05 +0100137//config:config HUSH_LINENO_VAR
138//config: bool "$LINENO variable (bashism)"
139//config: default y
140//config: depends on SHELL_HUSH
141//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:config HUSH_INTERACTIVE
143//config: bool "Interactive mode"
144//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200145//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200146//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200147//config: Enable interactive mode (prompt and command editing).
148//config: Without this, hush simply reads and executes commands
149//config: from stdin just like a shell script from a file.
150//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200151//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200152//config:config HUSH_SAVEHISTORY
153//config: bool "Save command history to .hush_history"
154//config: default y
155//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200156//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200157//config:config HUSH_JOB
158//config: bool "Job control"
159//config: default y
160//config: depends on HUSH_INTERACTIVE
161//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200162//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
163//config: command (not entire shell), fg/bg builtins work. Without this option,
164//config: "cmd &" still works by simply spawning a process and immediately
165//config: prompting for next command (or executing next command in a script),
166//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200167//config:
168//config:config HUSH_TICK
Ron Yorston060f0a02018-11-09 12:00:39 +0000169//config: bool "Support command substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200171//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200172//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200173//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200174//config:
175//config:config HUSH_IF
176//config: bool "Support if/then/elif/else/fi"
177//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200178//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200179//config:
180//config:config HUSH_LOOPS
181//config: bool "Support for, while and until loops"
182//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200183//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200184//config:
185//config:config HUSH_CASE
186//config: bool "Support case ... esac statement"
187//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200188//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200190//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200191//config:
192//config:config HUSH_FUNCTIONS
193//config: bool "Support funcname() { commands; } syntax"
194//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200195//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200197//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200198//config:
199//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100200//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: default y
202//config: depends on HUSH_FUNCTIONS
203//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200204//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:
206//config:config HUSH_RANDOM_SUPPORT
207//config: bool "Pseudorandom generator and $RANDOM variable"
208//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200209//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200210//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200211//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
212//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200213//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200214//config:config HUSH_MODE_X
215//config: bool "Support 'hush -x' option and 'set -x' command"
216//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200217//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200218//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200219//config: This instructs hush to print commands before execution.
220//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200221//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100222//config:config HUSH_ECHO
223//config: bool "echo builtin"
224//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200225//config: depends on SHELL_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100226//config:
227//config:config HUSH_PRINTF
228//config: bool "printf builtin"
229//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200230//config: depends on SHELL_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100231//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100232//config:config HUSH_TEST
233//config: bool "test builtin"
234//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200235//config: depends on SHELL_HUSH
Denys Vlasenko265062d2017-01-10 15:13:30 +0100236//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100237//config:config HUSH_HELP
238//config: bool "help builtin"
239//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200240//config: depends on SHELL_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100241//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100242//config:config HUSH_EXPORT
243//config: bool "export builtin"
244//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200245//config: depends on SHELL_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100246//config:
247//config:config HUSH_EXPORT_N
248//config: bool "Support 'export -n' option"
249//config: default y
250//config: depends on HUSH_EXPORT
251//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200252//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100253//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200254//config:config HUSH_READONLY
255//config: bool "readonly builtin"
256//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200257//config: depends on SHELL_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200258//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200259//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200260//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100262//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100263//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200264//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100265//config:
266//config:config HUSH_WAIT
267//config: bool "wait builtin"
268//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200269//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100270//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100271//config:config HUSH_COMMAND
272//config: bool "command builtin"
273//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200274//config: depends on SHELL_HUSH
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100275//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:config HUSH_TRAP
277//config: bool "trap builtin"
278//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200279//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100280//config:
281//config:config HUSH_TYPE
282//config: bool "type builtin"
283//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200284//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100285//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200286//config:config HUSH_TIMES
287//config: bool "times builtin"
288//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200289//config: depends on SHELL_HUSH
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200290//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100291//config:config HUSH_READ
292//config: bool "read builtin"
293//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200294//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100295//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100296//config:config HUSH_SET
297//config: bool "set builtin"
298//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200299//config: depends on SHELL_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100300//config:
301//config:config HUSH_UNSET
302//config: bool "unset builtin"
303//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200304//config: depends on SHELL_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100305//config:
306//config:config HUSH_ULIMIT
307//config: bool "ulimit builtin"
308//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200309//config: depends on SHELL_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100310//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100311//config:config HUSH_UMASK
312//config: bool "umask builtin"
313//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200314//config: depends on SHELL_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100315//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200316//config:config HUSH_GETOPTS
317//config: bool "getopts builtin"
318//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200319//config: depends on SHELL_HUSH
Denys Vlasenko74d40582017-08-11 01:32:46 +0200320//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100321//config:config HUSH_MEMLEAK
322//config: bool "memleak builtin (debugging)"
323//config: default n
Denys Vlasenko67e15292020-06-24 13:39:13 +0200324//config: depends on SHELL_HUSH
325//config:
326//config:endif # hush options
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200327
Denys Vlasenko20704f02011-03-23 17:59:27 +0100328//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100329// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100330//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100331//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100332
Denys Vlasenko67e15292020-06-24 13:39:13 +0200333//kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100334//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
335
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200336/* -i (interactive) is also accepted,
337 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100338 * NOMMU-specific options are not meant to be used by users,
339 * therefore we don't show them either.
340 */
341//usage:#define hush_trivial_usage
Denys Vlasenkoaaf3d5b2021-10-13 11:15:52 +0200342//usage: "[-enxl] [-c 'SCRIPT' [ARG0 ARGS] | FILE ARGS | -s ARGS]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100343//usage:#define hush_full_usage "\n\n"
344//usage: "Unix shell interpreter"
345
Denys Vlasenko67047462016-12-22 15:21:58 +0100346#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
347 || defined(__APPLE__) \
348 )
349# include <malloc.h> /* for malloc_trim */
350#endif
351#include <glob.h>
352/* #include <dmalloc.h> */
353#if ENABLE_HUSH_CASE
354# include <fnmatch.h>
355#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200356#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100357#include <sys/utsname.h> /* for setting $HOSTNAME */
358
359#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
360#include "unicode.h"
361#include "shell_common.h"
362#include "math.h"
363#include "match.h"
364#if ENABLE_HUSH_RANDOM_SUPPORT
365# include "random.h"
366#else
367# define CLEAR_RANDOM_T(rnd) ((void)0)
368#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200369#ifndef O_CLOEXEC
370# define O_CLOEXEC 0
371#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100372#ifndef F_DUPFD_CLOEXEC
373# define F_DUPFD_CLOEXEC F_DUPFD
374#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100375
Denys Vlasenko7c3e96d2021-10-12 01:24:32 +0200376#if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !ENABLE_SHELL_ASH
Ron Yorston71df2d32018-11-27 14:34:25 +0000377# include "embedded_scripts.h"
378#else
379# define NUM_SCRIPTS 0
380#endif
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000381
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100382/* So far, all bash compat is controlled by one config option */
383/* Separate defines document which part of code implements what */
384#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
385#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100386#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob278d822021-07-26 15:29:13 +0200387#define BASH_DOLLAR_SQUOTE ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100388#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Ron Yorstona81700b2019-04-15 10:48:29 +0100389#define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200390#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200391#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100392
393
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200394/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000395#define LEAK_HUNTING 0
396#define BUILD_AS_NOMMU 0
397/* Enable/disable sanity checks. Ok to enable in production,
398 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
399 * Keeping 1 for now even in released versions.
400 */
401#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200402/* Slightly bigger (+200 bytes), but faster hush.
403 * So far it only enables a trick with counting SIGCHLDs and forks,
404 * which allows us to do fewer waitpid's.
405 * (we can detect a case where neither forks were done nor SIGCHLDs happened
406 * and therefore waitpid will return the same result as last time)
407 */
408#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200409/* TODO: implement simplified code for users which do not need ${var%...} ops
410 * So far ${var%...} ops are always enabled:
411 */
412#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000413
414
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000415#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000416# undef BB_MMU
417# undef USE_FOR_NOMMU
418# undef USE_FOR_MMU
419# define BB_MMU 0
420# define USE_FOR_NOMMU(...) __VA_ARGS__
421# define USE_FOR_MMU(...)
422#endif
423
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200424#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100425#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000426/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000427# undef CONFIG_FEATURE_SH_STANDALONE
428# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000429# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100430# undef IF_NOT_FEATURE_SH_STANDALONE
431# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000432# define IF_FEATURE_SH_STANDALONE(...)
433# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000434#endif
435
Denis Vlasenko05743d72008-02-10 12:10:08 +0000436#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000437# undef ENABLE_FEATURE_EDITING
438# define ENABLE_FEATURE_EDITING 0
439# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
440# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200441# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
442# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000443#endif
444
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000445/* Do we support ANY keywords? */
446#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000447# define HAS_KEYWORDS 1
448# define IF_HAS_KEYWORDS(...) __VA_ARGS__
449# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000450#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000451# define HAS_KEYWORDS 0
452# define IF_HAS_KEYWORDS(...)
453# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000454#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000455
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000456/* If you comment out one of these below, it will be #defined later
457 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200458#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000459/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200460#define debug_printf_parse(...) do {} while (0)
461#define debug_printf_heredoc(...) do {} while (0)
462#define debug_print_tree(a, b) do {} while (0)
463#define debug_printf_exec(...) do {} while (0)
464#define debug_printf_env(...) do {} while (0)
465#define debug_printf_jobs(...) do {} while (0)
466#define debug_printf_expand(...) do {} while (0)
467#define debug_printf_varexp(...) do {} while (0)
468#define debug_printf_glob(...) do {} while (0)
469#define debug_printf_redir(...) do {} while (0)
470#define debug_printf_list(...) do {} while (0)
471#define debug_printf_subst(...) do {} while (0)
472#define debug_printf_prompt(...) do {} while (0)
473#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000474
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000475#define ERR_PTR ((void*)(long)1)
476
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100477#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000478
Denys Vlasenkoef8985c2019-05-19 16:29:09 +0200479#define _SPECIAL_VARS_STR "_*@$!?#-"
480#define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
481#define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100482#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200483/* Support / and // replace ops */
484/* Note that // is stored as \ in "encoded" string representation */
485# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
486# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
487# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
488#else
489# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
490# define VAR_SUBST_OPS "%#:-=+?"
491# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
492#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200493
Denys Vlasenko932b9972018-01-11 12:39:48 +0100494#define SPECIAL_VAR_SYMBOL_STR "\3"
495#define SPECIAL_VAR_SYMBOL 3
496/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
497#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000498
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200499struct variable;
500
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000501static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
502
503/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000504 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000505 */
506#if !BB_MMU
507typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200508 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000509 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000510 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000511} nommu_save_t;
512#endif
513
Denys Vlasenko9b782552010-09-08 13:33:26 +0200514enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000515 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000516#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000517 RES_IF ,
518 RES_THEN ,
519 RES_ELIF ,
520 RES_ELSE ,
521 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000522#endif
523#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000524 RES_FOR ,
525 RES_WHILE ,
526 RES_UNTIL ,
527 RES_DO ,
528 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000529#endif
530#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000531 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000532#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000533#if ENABLE_HUSH_CASE
534 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200535 /* three pseudo-keywords support contrived "case" syntax: */
536 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
537 RES_MATCH , /* "word)" */
538 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000539 RES_ESAC ,
540#endif
541 RES_XXXX ,
542 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200543};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000544
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000545typedef struct o_string {
546 char *data;
547 int length; /* position where data is appended */
548 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200549 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000550 /* At least some part of the string was inside '' or "",
551 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200552 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000553 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200554 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000555} o_string;
556enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200557 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
558 EXP_FLAG_GLOB = 0x2,
559 /* Protect newly added chars against globbing
560 * by prepending \ to *, ?, [, \ */
561 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
562};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563/* Used for initialization: o_string foo = NULL_O_STRING; */
564#define NULL_O_STRING { NULL }
565
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200566#ifndef debug_printf_parse
Denys Vlasenko987be932022-02-06 20:07:12 +0100567static const char *const assignment_flag[] ALIGN_PTR = {
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200568 "MAYBE_ASSIGNMENT",
569 "DEFINITELY_ASSIGNMENT",
570 "NOT_ASSIGNMENT",
571 "WORD_IS_KEYWORD",
572};
573#endif
574
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200575/* We almost can use standard FILE api, but we need an ability to move
576 * its fd when redirects coincide with it. No api exists for that
577 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
578 * HFILE is our internal alternative. Only supports reading.
579 * Since we now can, we incorporate linked list of all opened HFILEs
580 * into the struct (used to be a separate mini-list).
581 */
582typedef struct HFILE {
583 char *cur;
584 char *end;
585 struct HFILE *next_hfile;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200586 int fd;
587 char buf[1024];
588} HFILE;
589
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000590typedef struct in_str {
591 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200592 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200593 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200594 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000595} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000596
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200597/* The descrip member of this structure is only used to make
598 * debugging output pretty */
599static const struct {
Denys Vlasenko965b7952020-11-30 13:03:03 +0100600 int32_t mode;
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200601 signed char default_fd;
602 char descrip[3];
Denys Vlasenko965b7952020-11-30 13:03:03 +0100603} redir_table[] ALIGN4 = {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200604 { O_RDONLY, 0, "<" },
605 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
606 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
607 { O_CREAT|O_RDWR, 1, "<>" },
608 { O_RDONLY, 0, "<<" },
609/* Should not be needed. Bogus default_fd helps in debugging */
610/* { O_RDONLY, 77, "<<" }, */
611};
612
Eric Andersen25f27032001-04-26 23:22:31 +0000613struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000614 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000615 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000616 int rd_fd; /* fd to redirect */
617 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
618 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000619 smallint rd_type; /* (enum redir_type) */
620 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000621 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200622 * bit 0: do we need to trim leading tabs?
623 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000624 */
Eric Andersen25f27032001-04-26 23:22:31 +0000625};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000626typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200627 REDIRECT_INPUT = 0,
628 REDIRECT_OVERWRITE = 1,
629 REDIRECT_APPEND = 2,
630 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000631 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200632 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000633
634 REDIRFD_CLOSE = -3,
635 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000636 REDIRFD_TO_FILE = -1,
637 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000638
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000639 HEREDOC_SKIPTABS = 1,
640 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000641} redir_type;
642
Eric Andersen25f27032001-04-26 23:22:31 +0000643
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000644struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000645 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200646 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100647#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100648 unsigned lineno;
649#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200650 smallint cmd_type; /* CMD_xxx */
651#define CMD_NORMAL 0
652#define CMD_SUBSHELL 1
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100653#if BASH_TEST2
654/* used for "[[ EXPR ]]" */
655# define CMD_TEST2_SINGLEWORD_NOGLOB 2
656#endif
Denys Vlasenko77a51a22020-12-29 16:53:11 +0100657#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100658/* used to prevent word splitting and globbing in "export v=t*" */
659# define CMD_SINGLEWORD_NOGLOB 3
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200661#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100662# define CMD_FUNCDEF 4
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200663#endif
664
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100665 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200666 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
667 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000668#if !BB_MMU
669 char *group_as_string;
670#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000671#if ENABLE_HUSH_FUNCTIONS
672 struct function *child_func;
673/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200674 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000675 * When we execute "f1() {a;}" cmd, we create new function and clear
676 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200677 * When we execute "f1() {b;}", we notice that f1 exists,
678 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000679 * we put those fields back into cmd->xxx
680 * (struct function has ->parent_cmd ptr to facilitate that).
681 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
682 * Without this trick, loop would execute a;b;b;b;...
683 * instead of correct sequence a;b;a;b;...
684 * When command is freed, it severs the link
685 * (sets ->child_func->parent_cmd to NULL).
686 */
687#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000688 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000689/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
690 * and on execution these are substituted with their values.
691 * Substitution can make _several_ words out of one argv[n]!
692 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000693 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000694 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000695 struct redir_struct *redirects; /* I/O redirections */
696};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000697/* Is there anything in this command at all? */
698#define IS_NULL_CMD(cmd) \
699 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
700
Eric Andersen25f27032001-04-26 23:22:31 +0000701struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000702 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000703 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000704 int alive_cmds; /* number of commands running (not exited) */
705 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000706#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100707 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000708 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000709 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000710#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000711 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000712 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000713 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
714 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000715};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000716typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100717 PIPE_SEQ = 0,
718 PIPE_AND = 1,
719 PIPE_OR = 2,
720 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000721} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000722/* Is there anything in this pipe at all? */
723#define IS_NULL_PIPE(pi) \
724 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000725
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000726/* This holds pointers to the various results of parsing */
727struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000728 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000729 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000730 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000731 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000732 /* last command in pipe (being constructed right now) */
733 struct command *command;
734 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000735 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200736 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000737#if !BB_MMU
738 o_string as_string;
739#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200740 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000741#if HAS_KEYWORDS
742 smallint ctx_res_w;
743 smallint ctx_inverted; /* "! cmd | cmd" */
744#if ENABLE_HUSH_CASE
745 smallint ctx_dsemicolon; /* ";;" seen */
746#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000747 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
748 int old_flag;
749 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000750 * example: "if pipe1; pipe2; then pipe3; fi"
751 * when we see "if" or "then", we malloc and copy current context,
752 * and make ->stack point to it. then we parse pipeN.
753 * when closing "then" / fi" / whatever is found,
754 * we move list_head into ->stack->command->group,
755 * copy ->stack into current context, and delete ->stack.
756 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000757 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000758 struct parse_context *stack;
759#endif
760};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200761enum {
762 MAYBE_ASSIGNMENT = 0,
763 DEFINITELY_ASSIGNMENT = 1,
764 NOT_ASSIGNMENT = 2,
765 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
766 WORD_IS_KEYWORD = 3,
767};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000768
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000769/* On program start, environ points to initial environment.
770 * putenv adds new pointers into it, unsetenv removes them.
771 * Neither of these (de)allocates the strings.
772 * setenv allocates new strings in malloc space and does putenv,
773 * and thus setenv is unusable (leaky) for shell's purposes */
774#define setenv(...) setenv_is_leaky_dont_use()
775struct variable {
776 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000777 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000778 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200779 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000780 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000781 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000782};
783
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000784enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000785 BC_BREAK = 1,
786 BC_CONTINUE = 2,
787};
788
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000789#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000790struct function {
791 struct function *next;
792 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000793 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000794 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200795# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000796 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200797# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000798};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000799#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000800
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000801
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100802/* set -/+o OPT support. (TODO: make it optional)
803 * bash supports the following opts:
804 * allexport off
805 * braceexpand on
806 * emacs on
807 * errexit off
808 * errtrace off
809 * functrace off
810 * hashall on
811 * histexpand off
812 * history on
813 * ignoreeof off
814 * interactive-comments on
815 * keyword off
816 * monitor on
817 * noclobber off
818 * noexec off
819 * noglob off
820 * nolog off
821 * notify off
822 * nounset off
823 * onecmd off
824 * physical off
825 * pipefail off
826 * posix off
827 * privileged off
828 * verbose off
829 * vi off
830 * xtrace off
831 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800832static const char o_opt_strings[] ALIGN1 =
833 "pipefail\0"
834 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200835 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800836#if ENABLE_HUSH_MODE_X
837 "xtrace\0"
838#endif
839 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100840enum {
841 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800842 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200843 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800844#if ENABLE_HUSH_MODE_X
845 OPT_O_XTRACE,
846#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100847 NUM_OPT_O
848};
849
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000851/* Sorted roughly by size (smaller offsets == smaller code) */
852struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000853 /* interactive_fd != 0 means we are an interactive shell.
854 * If we are, then saved_tty_pgrp can also be != 0, meaning
855 * that controlling tty is available. With saved_tty_pgrp == 0,
856 * job control still works, but terminal signals
857 * (^C, ^Z, ^Y, ^\) won't work at all, and background
858 * process groups can only be created with "cmd &".
859 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
860 * to give tty to the foreground process group,
861 * and will take it back when the group is stopped (^Z)
862 * or killed (^C).
863 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000864#if ENABLE_HUSH_INTERACTIVE
865 /* 'interactive_fd' is a fd# open to ctty, if we have one
866 * _AND_ if we decided to act interactively */
867 int interactive_fd;
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +0200868 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000869# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000870#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000871# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000872#endif
873#if ENABLE_FEATURE_EDITING
874 line_input_t *line_input_state;
875#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000876 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200877 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000878 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200879#if ENABLE_HUSH_RANDOM_SUPPORT
880 random_t random_gen;
881#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000882#if ENABLE_HUSH_JOB
883 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100884 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000885 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000886 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400887# define G_saved_tty_pgrp (G.saved_tty_pgrp)
888#else
889# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000890#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200891 /* How deeply are we in context where "set -e" is ignored */
892 int errexit_depth;
893 /* "set -e" rules (do we follow them correctly?):
894 * Exit if pipe, list, or compound command exits with a non-zero status.
895 * Shell does not exit if failed command is part of condition in
896 * if/while, part of && or || list except the last command, any command
897 * in a pipe but the last, or if the command's return value is being
898 * inverted with !. If a compound command other than a subshell returns a
899 * non-zero status because a command failed while -e was being ignored, the
900 * shell does not exit. A trap on ERR, if set, is executed before the shell
901 * exits [ERR is a bashism].
902 *
903 * If a compound command or function executes in a context where -e is
904 * ignored, none of the commands executed within are affected by the -e
905 * setting. If a compound command or function sets -e while executing in a
906 * context where -e is ignored, that setting does not have any effect until
907 * the compound command or the command containing the function call completes.
908 */
909
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100910 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100911#if ENABLE_HUSH_MODE_X
912# define G_x_mode (G.o_opt[OPT_O_XTRACE])
913#else
914# define G_x_mode 0
915#endif
Denys Vlasenkod8740b22019-05-19 19:11:21 +0200916 char opt_s;
Denys Vlasenkof3634582019-06-03 12:21:04 +0200917 char opt_c;
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200918#if ENABLE_HUSH_INTERACTIVE
919 smallint promptmode; /* 0: PS1, 1: PS2 */
920#endif
Denys Vlasenko12566e72022-01-17 03:02:40 +0100921 /* set by signal handler if SIGINT is received _and_ its trap is not set */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000922 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000923#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000924 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000925#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000926#if ENABLE_HUSH_FUNCTIONS
927 /* 0: outside of a function (or sourced file)
928 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000929 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000930 */
931 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200932# define G_flag_return_in_progress (G.flag_return_in_progress)
933#else
934# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000935#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000936 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100937 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000938 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200939 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200940 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100941#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000942 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000943 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100944# define G_global_args_malloced (G.global_args_malloced)
945#else
946# define G_global_args_malloced 0
947#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100948#if ENABLE_HUSH_BASH_COMPAT
949 int dead_job_exitcode; /* for "wait -n" */
950#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000951 /* how many non-NULL argv's we have. NB: $# + 1 */
952 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000953 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000954#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000955 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000956#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000957#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000958 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000959 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000960#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200961#if ENABLE_HUSH_GETOPTS
962 unsigned getopt_count;
963#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000964 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200965 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000966 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200967 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200968 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200969 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200970 unsigned var_nest_level;
971#if ENABLE_HUSH_FUNCTIONS
972# if ENABLE_HUSH_LOCAL
973 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200974# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200975 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000976#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000977 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200978#if ENABLE_HUSH_FAST
979 unsigned count_SIGCHLD;
980 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200981 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200982#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100983#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +0200984 unsigned parse_lineno;
985 unsigned execute_lineno;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100986#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200987 HFILE *HFILE_list;
Denys Vlasenko21806562019-11-01 14:16:07 +0100988 HFILE *HFILE_stdin;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200989 /* Which signals have non-DFL handler (even with no traps set)?
990 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200991 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200992 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200993 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200994 * Other than these two times, never modified.
995 */
996 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200997#if ENABLE_HUSH_JOB
998 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100999# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001000#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001001# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001002#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001003#if ENABLE_HUSH_TRAP
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01001004 int pre_trap_exitcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01001005# if ENABLE_HUSH_FUNCTIONS
1006 int return_exitcode;
1007# endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001008 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001009# define G_traps G.traps
1010#else
1011# define G_traps ((char**)NULL)
1012#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001013 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +01001014#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001015 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +01001016#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001017#if ENABLE_HUSH_MODE_X
1018 unsigned x_mode_depth;
1019 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1020 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1021 * for all subsequent output.
1022 */
1023 int x_mode_fd;
1024 o_string x_mode_buf;
1025#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001026#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001027 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001028#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001029 struct sigaction sa;
Denys Vlasenkof3634582019-06-03 12:21:04 +02001030 char optstring_buf[sizeof("eixcs")];
Ron Yorstona81700b2019-04-15 10:48:29 +01001031#if BASH_EPOCH_VARS
Denys Vlasenko3c13da32020-12-30 23:48:01 +01001032 char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
Ron Yorstona81700b2019-04-15 10:48:29 +01001033#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001034#if ENABLE_FEATURE_EDITING
1035 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1036#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001037};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001038#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001039/* Not #defining name to G.name - this quickly gets unwieldy
1040 * (too many defines). Also, I actually prefer to see when a variable
1041 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001042#define INIT_G() do { \
1043 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001044 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1045 sigfillset(&G.sa.sa_mask); \
1046 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001047} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001048
1049
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001050/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001051static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001052#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001053static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001054#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001055static int builtin_eval(char **argv) FAST_FUNC;
1056static int builtin_exec(char **argv) FAST_FUNC;
1057static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001058#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001060#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001061#if ENABLE_HUSH_READONLY
1062static int builtin_readonly(char **argv) FAST_FUNC;
1063#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001064#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001065static int builtin_fg_bg(char **argv) FAST_FUNC;
1066static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001067#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001068#if ENABLE_HUSH_GETOPTS
1069static int builtin_getopts(char **argv) FAST_FUNC;
1070#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001071#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001072static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001073#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001074#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001075static int builtin_history(char **argv) FAST_FUNC;
1076#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001077#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001078static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001079#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001080#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001081static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001082#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001083#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001084static int builtin_printf(char **argv) FAST_FUNC;
1085#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001086static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001087#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001088static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001089#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001090#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001091static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001092#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001093static int builtin_shift(char **argv) FAST_FUNC;
1094static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001095#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001096static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001097#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001098#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001099static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001100#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001101#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001102static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001103#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001104#if ENABLE_HUSH_TIMES
1105static int builtin_times(char **argv) FAST_FUNC;
1106#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001107static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001108#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001109static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001110#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001111#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001112static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001113#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001114#if ENABLE_HUSH_KILL
1115static int builtin_kill(char **argv) FAST_FUNC;
1116#endif
1117#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001118static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001119#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001120#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001121static int builtin_break(char **argv) FAST_FUNC;
1122static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001123#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001124#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001125static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001126#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001127
1128/* Table of built-in functions. They can be forked or not, depending on
1129 * context: within pipes, they fork. As simple commands, they do not.
1130 * When used in non-forking context, they can change global variables
1131 * in the parent shell process. If forked, of course they cannot.
1132 * For example, 'unset foo | whatever' will parse and run, but foo will
1133 * still be set at the end. */
1134struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001135 const char *b_cmd;
1136 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001137#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001138 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001139# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001140#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001141# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001142#endif
1143};
1144
Denys Vlasenko965b7952020-11-30 13:03:03 +01001145static const struct built_in_command bltins1[] ALIGN_PTR = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001146 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001147 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001148#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001149 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001150#endif
1151#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001152 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001153#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001154 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001155#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001156 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001157#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001158 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1159 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001160 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001161#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001162 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001163#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001164#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001165 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001166#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001167#if ENABLE_HUSH_GETOPTS
1168 BLTIN("getopts" , builtin_getopts , NULL),
1169#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001170#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001171 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001172#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001173#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001174 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001175#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001176#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001177 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001178#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001179#if ENABLE_HUSH_KILL
1180 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1181#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001182#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001183 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001184#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001185#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001186 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001187#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001188#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001189 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001190#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001191#if ENABLE_HUSH_READONLY
1192 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1193#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001194#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001195 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001196#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001197#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001198 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001199#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001200 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001201#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001202 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001203#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001204#if ENABLE_HUSH_TIMES
1205 BLTIN("times" , builtin_times , NULL),
1206#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001207#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001208 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001209#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001210 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001211#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001212 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001213#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001214#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001215 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001216#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001217#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001218 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001219#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001220#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001221 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001222#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001223#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001224 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001225#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001226};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001227/* These builtins won't be used if we are on NOMMU and need to re-exec
1228 * (it's cheaper to run an external program in this case):
1229 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01001230static const struct built_in_command bltins2[] ALIGN_PTR = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001231#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001232 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001233#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001234#if BASH_TEST2
1235 BLTIN("[[" , builtin_test , NULL),
1236#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001237#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001238 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001239#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001240#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001241 BLTIN("printf" , builtin_printf , NULL),
1242#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001243 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001244#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001245 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001246#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001247};
1248
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001249
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001250/* Debug printouts.
1251 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001252#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001253/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001254# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001255# define debug_enter() (G.debug_indent++)
1256# define debug_leave() (G.debug_indent--)
1257#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001258# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001259# define debug_enter() ((void)0)
1260# define debug_leave() ((void)0)
1261#endif
1262
1263#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001264# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001265#endif
1266
1267#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001268# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001269#endif
1270
Denys Vlasenko3675c372018-07-23 16:31:21 +02001271#ifndef debug_printf_heredoc
1272# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1273#endif
1274
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001275#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001276#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001277#endif
1278
1279#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001280# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001281#endif
1282
1283#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001284# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001285# define DEBUG_JOBS 1
1286#else
1287# define DEBUG_JOBS 0
1288#endif
1289
1290#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001291# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001292# define DEBUG_EXPAND 1
1293#else
1294# define DEBUG_EXPAND 0
1295#endif
1296
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001297#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001298# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001299#endif
1300
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001301#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001302# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001303# define DEBUG_GLOB 1
1304#else
1305# define DEBUG_GLOB 0
1306#endif
1307
Denys Vlasenko2db74612017-07-07 22:07:28 +02001308#ifndef debug_printf_redir
1309# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1310#endif
1311
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001312#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001313# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001314#endif
1315
1316#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001317# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001318#endif
1319
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001320#ifndef debug_printf_prompt
1321# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1322#endif
1323
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001324#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001325# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001326# define DEBUG_CLEAN 1
1327#else
1328# define DEBUG_CLEAN 0
1329#endif
1330
1331#if DEBUG_EXPAND
1332static void debug_print_strings(const char *prefix, char **vv)
1333{
1334 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001335 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001336 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001337 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001338}
1339#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001340# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001341#endif
1342
1343
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001344/* Leak hunting. Use hush_leaktool.sh for post-processing.
1345 */
1346#if LEAK_HUNTING
1347static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001348{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001349 void *ptr = xmalloc((size + 0xff) & ~0xff);
1350 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1351 return ptr;
1352}
1353static void *xxrealloc(int lineno, void *ptr, size_t size)
1354{
1355 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1356 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1357 return ptr;
1358}
1359static char *xxstrdup(int lineno, const char *str)
1360{
1361 char *ptr = xstrdup(str);
1362 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1363 return ptr;
1364}
1365static void xxfree(void *ptr)
1366{
1367 fdprintf(2, "free %p\n", ptr);
1368 free(ptr);
1369}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001370# define xmalloc(s) xxmalloc(__LINE__, s)
1371# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1372# define xstrdup(s) xxstrdup(__LINE__, s)
1373# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001374#endif
1375
1376
1377/* Syntax and runtime errors. They always abort scripts.
1378 * In interactive use they usually discard unparsed and/or unexecuted commands
1379 * and return to the prompt.
1380 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1381 */
1382#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001383# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001384# define syntax_error(lineno, msg) syntax_error(msg)
1385# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1386# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1387# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1388# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001389#endif
1390
Denys Vlasenko39701202017-08-02 19:44:05 +02001391static void die_if_script(void)
1392{
1393 if (!G_interactive_fd) {
1394 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1395 xfunc_error_retval = G.last_exitcode;
1396 xfunc_die();
1397 }
1398}
1399
1400static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001401{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001402 va_list p;
1403
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001404#if HUSH_DEBUG >= 2
1405 bb_error_msg("hush.c:%u", lineno);
1406#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001407 va_start(p, fmt);
1408 bb_verror_msg(fmt, p, NULL);
1409 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001410 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001411}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001412
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001413static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001414{
1415 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001416 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001417 else
James Byrne69374872019-07-02 11:35:03 +02001418 bb_simple_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001419 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001420}
1421
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001422static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001423{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001424 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001425 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001426}
1427
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001428static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001429{
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01001430 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001431//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1432// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001433}
1434
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001435static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001436{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001437 char msg[2] = { ch, '\0' };
1438 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001439}
1440
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001441static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001442{
1443 char msg[2];
1444 msg[0] = ch;
1445 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001446#if HUSH_DEBUG >= 2
1447 bb_error_msg("hush.c:%u", lineno);
1448#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001449 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001450 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001451}
1452
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001453#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001454# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001455# undef syntax_error
1456# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001457# undef syntax_error_unterm_ch
1458# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001459# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001460#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001461# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001462# define syntax_error(msg) syntax_error(__LINE__, msg)
1463# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1464# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1465# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1466# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001467#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001468
Denis Vlasenko552433b2009-04-04 19:29:21 +00001469
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001470/* Utility functions
1471 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001472/* Replace each \x with x in place, return ptr past NUL. */
1473static char *unbackslash(char *src)
1474{
Denys Vlasenko71885402009-09-24 01:44:13 +02001475 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001476 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001477 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001478 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001479 if (*src != '\0') {
1480 /* \x -> x */
1481 *dst++ = *src++;
1482 continue;
1483 }
1484 /* else: "\<nul>". Do not delete this backslash.
1485 * Testcase: eval 'echo ok\'
1486 */
1487 *dst++ = '\\';
1488 /* fallthrough */
1489 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001490 if ((*dst++ = *src++) == '\0')
1491 break;
1492 }
1493 return dst;
1494}
1495
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001496static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001497{
1498 int i;
1499 unsigned count1;
1500 unsigned count2;
1501 char **v;
1502
1503 v = strings;
1504 count1 = 0;
1505 if (v) {
1506 while (*v) {
1507 count1++;
1508 v++;
1509 }
1510 }
1511 count2 = 0;
1512 v = add;
1513 while (*v) {
1514 count2++;
1515 v++;
1516 }
1517 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1518 v[count1 + count2] = NULL;
1519 i = count2;
1520 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001521 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001522 return v;
1523}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001524#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001525static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1526{
1527 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1528 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1529 return ptr;
1530}
1531#define add_strings_to_strings(strings, add, need_to_dup) \
1532 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1533#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001534
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001535/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001536static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001537{
1538 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001539 v[0] = add;
1540 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001541 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001542}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001543#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001544static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1545{
1546 char **ptr = add_string_to_strings(strings, add);
1547 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1548 return ptr;
1549}
1550#define add_string_to_strings(strings, add) \
1551 xx_add_string_to_strings(__LINE__, strings, add)
1552#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001553
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001554static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001555{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001556 char **v;
1557
1558 if (!strings)
1559 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001560 v = strings;
1561 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001562 free(*v);
1563 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001564 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001565 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001566}
1567
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001568static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001569{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001570 int newfd;
1571 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001572 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1573 if (newfd >= 0) {
1574 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1575 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1576 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001577 if (errno == EBUSY)
1578 goto repeat;
1579 if (errno == EINTR)
1580 goto repeat;
1581 }
1582 return newfd;
1583}
1584
Denys Vlasenko657e9002017-07-30 23:34:04 +02001585static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001586{
1587 int newfd;
1588 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001589 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001590 if (newfd < 0) {
1591 if (errno == EBUSY)
1592 goto repeat;
1593 if (errno == EINTR)
1594 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001595 /* fd was not open? */
1596 if (errno == EBADF)
1597 return fd;
1598 xfunc_die();
1599 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001600 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1601 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001602 close(fd);
1603 return newfd;
1604}
1605
1606
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001607/* Manipulating HFILEs */
1608static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001609{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001610 HFILE *fp;
1611 int fd;
1612
1613 fd = STDIN_FILENO;
1614 if (name) {
1615 fd = open(name, O_RDONLY | O_CLOEXEC);
1616 if (fd < 0)
1617 return NULL;
1618 if (O_CLOEXEC == 0) /* ancient libc */
1619 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001620 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001621
1622 fp = xmalloc(sizeof(*fp));
Denys Vlasenko21806562019-11-01 14:16:07 +01001623 if (name == NULL)
1624 G.HFILE_stdin = fp;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001625 fp->fd = fd;
1626 fp->cur = fp->end = fp->buf;
1627 fp->next_hfile = G.HFILE_list;
1628 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001629 return fp;
1630}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001631static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001632{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001633 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001634 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001635 HFILE *cur = *pp;
1636 if (cur == fp) {
1637 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001638 break;
1639 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001640 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001641 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001642 if (fp->fd >= 0)
1643 close(fp->fd);
1644 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001645}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001646static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001647{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001648 int n;
1649
1650 if (fp->fd < 0) {
1651 /* Already saw EOF */
1652 return EOF;
1653 }
Denys Vlasenko521220e2020-12-23 23:44:55 +01001654#if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
1655 /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
1656 * IOW: ^C will not immediately stop line input.
1657 * But poll() is different: it does NOT restart after signals.
1658 */
1659 if (fp == G.HFILE_stdin) {
1660 struct pollfd pfd[1];
1661 pfd[0].fd = fp->fd;
1662 pfd[0].events = POLLIN;
1663 n = poll(pfd, 1, -1);
1664 if (n < 0
1665 /*&& errno == EINTR - assumed true */
1666 && sigismember(&G.pending_set, SIGINT)
1667 ) {
1668 return '\0';
1669 }
1670 }
1671#else
1672/* if FEATURE_EDITING=y, we do not use this routine for interactive input */
1673#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001674 /* Try to buffer more input */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001675 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1676 if (n < 0) {
James Byrne69374872019-07-02 11:35:03 +02001677 bb_simple_perror_msg("read error");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001678 n = 0;
1679 }
Denys Vlasenko93e2a222020-12-23 12:23:21 +01001680 fp->cur = fp->buf;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001681 fp->end = fp->buf + n;
1682 if (n == 0) {
1683 /* EOF/error */
1684 close(fp->fd);
1685 fp->fd = -1;
1686 return EOF;
1687 }
1688 return (unsigned char)(*fp->cur++);
1689}
1690/* Inlined for common case of non-empty buffer.
1691 */
1692static ALWAYS_INLINE int hfgetc(HFILE *fp)
1693{
1694 if (fp->cur < fp->end)
1695 return (unsigned char)(*fp->cur++);
1696 /* Buffer empty */
1697 return refill_HFILE_and_getc(fp);
1698}
1699static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1700{
1701 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001702 while (fl) {
1703 if (fd == fl->fd) {
1704 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001705 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001706 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 +02001707 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001708 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001709 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001710 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001711#if ENABLE_HUSH_MODE_X
1712 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1713 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1714 return 1; /* "found and moved" */
1715 }
1716#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001717 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001718}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001719#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001720static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001721{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001722 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001723 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001724 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001725 * It is disastrous if we share memory with a vforked parent.
1726 * I'm not sure we never come here after vfork.
1727 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001728 *
1729 * ">" instead of ">=": we don't close fd#0,
1730 * interactive shell uses hfopen(NULL) as stdin input
1731 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1732 * If we'd close it here, then e.g. interactive "set | sort"
1733 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001734 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001735 if (fl->fd > 0)
1736 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001737 close(fl->fd);
1738 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001739 }
1740}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001741#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001742static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001743{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001744 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001745 while (fl) {
1746 if (fl->fd == fd)
1747 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001748 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001749 }
1750 return 0;
1751}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001752
1753
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001754/* Helpers for setting new $n and restoring them back
1755 */
1756typedef struct save_arg_t {
1757 char *sv_argv0;
1758 char **sv_g_argv;
1759 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001760 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001761} save_arg_t;
1762
1763static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1764{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001765 sv->sv_argv0 = argv[0];
1766 sv->sv_g_argv = G.global_argv;
1767 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001768 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001769
1770 argv[0] = G.global_argv[0]; /* retain $0 */
1771 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001772 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001773
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001774 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001775}
1776
1777static void restore_G_args(save_arg_t *sv, char **argv)
1778{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001779#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001780 if (G.global_args_malloced) {
1781 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001782 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001783 while (*++pp) /* note: does not free $0 */
1784 free(*pp);
1785 free(G.global_argv);
1786 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001787#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001788 argv[0] = sv->sv_argv0;
1789 G.global_argv = sv->sv_g_argv;
1790 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001791 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001792}
1793
1794
Denis Vlasenkod5762932009-03-31 11:22:57 +00001795/* Basic theory of signal handling in shell
1796 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001797 * This does not describe what hush does, rather, it is current understanding
1798 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001799 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1800 *
1801 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1802 * is finished or backgrounded. It is the same in interactive and
1803 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001804 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001805 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001806 * backgrounds (i.e. stops) or kills all members of currently running
1807 * pipe.
1808 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001809 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001810 * or by SIGINT in interactive shell.
1811 *
1812 * Trap handlers will execute even within trap handlers. (right?)
1813 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001814 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1815 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001816 *
1817 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001818 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001819 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001820 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001821 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001822 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001823 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001824 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001825 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001826 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001827 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001828 *
1829 * SIGQUIT: ignore
1830 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001831 * SIGHUP (interactive):
1832 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001833 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001834 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1835 * that all pipe members are stopped. Try this in bash:
1836 * while :; do :; done - ^Z does not background it
1837 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001838 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001839 * of the command line, show prompt. NB: ^C does not send SIGINT
1840 * to interactive shell while shell is waiting for a pipe,
1841 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001842 * Example 1: this waits 5 sec, but does not execute ls:
1843 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1844 * Example 2: this does not wait and does not execute ls:
1845 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1846 * Example 3: this does not wait 5 sec, but executes ls:
1847 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001848 * Example 4: this does not wait and does not execute ls:
1849 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001850 *
1851 * (What happens to signals which are IGN on shell start?)
1852 * (What happens with signal mask on shell start?)
1853 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001854 * Old implementation
1855 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001856 * We use in-kernel pending signal mask to determine which signals were sent.
1857 * We block all signals which we don't want to take action immediately,
1858 * i.e. we block all signals which need to have special handling as described
1859 * above, and all signals which have traps set.
1860 * After each pipe execution, we extract any pending signals via sigtimedwait()
1861 * and act on them.
1862 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001863 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001864 * sigset_t blocked_set: current blocked signal set
1865 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001866 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001867 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001868 * "trap 'cmd' SIGxxx":
1869 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001870 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001871 * unblock signals with special interactive handling
1872 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001873 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001874 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001875 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001876 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001877 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001878 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001879 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001880 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001881 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001882 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001883 * Standard says "When a subshell is entered, traps that are not being ignored
1884 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001885 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001886 *
1887 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001888 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001889 * masked signals are not visible!
1890 *
1891 * New implementation
1892 * ==================
1893 * We record each signal we are interested in by installing signal handler
1894 * for them - a bit like emulating kernel pending signal mask in userspace.
1895 * We are interested in: signals which need to have special handling
1896 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001897 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001898 * After each pipe execution, we extract any pending signals
1899 * and act on them.
1900 *
1901 * unsigned special_sig_mask: a mask of shell-special signals.
1902 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1903 * char *traps[sig] if trap for sig is set (even if it's '').
1904 * sigset_t pending_set: set of sigs we received.
1905 *
1906 * "trap - SIGxxx":
1907 * if sig is in special_sig_mask, set handler back to:
1908 * record_pending_signo, or to IGN if it's a tty stop signal
1909 * if sig is in fatal_sig_mask, set handler back to sigexit.
1910 * else: set handler back to SIG_DFL
1911 * "trap 'cmd' SIGxxx":
1912 * set handler to record_pending_signo.
1913 * "trap '' SIGxxx":
1914 * set handler to SIG_IGN.
1915 * after [v]fork, if we plan to be a shell:
1916 * set signals with special interactive handling to SIG_DFL
1917 * (because child shell is not interactive),
1918 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1919 * after [v]fork, if we plan to exec:
1920 * POSIX says fork clears pending signal mask in child - no need to clear it.
1921 *
1922 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1923 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1924 *
1925 * Note (compat):
1926 * Standard says "When a subshell is entered, traps that are not being ignored
1927 * are set to the default actions". bash interprets it so that traps which
1928 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001929 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001930enum {
1931 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001932 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001933 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001934 | (1 << SIGHUP)
1935 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001936 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001937#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001938 | (1 << SIGTTIN)
1939 | (1 << SIGTTOU)
1940 | (1 << SIGTSTP)
1941#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001942 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001943};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001944
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001945static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001946{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001947 sigaddset(&G.pending_set, sig);
Denys Vlasenko12566e72022-01-17 03:02:40 +01001948#if ENABLE_FEATURE_EDITING
1949 bb_got_signal = sig; /* for read_line_input: "we got a signal" */
1950#endif
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001951#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001952 if (sig == SIGCHLD) {
1953 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001954//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 +02001955 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001956#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001957}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001958
Denys Vlasenko0806e402011-05-12 23:06:20 +02001959static sighandler_t install_sighandler(int sig, sighandler_t handler)
1960{
1961 struct sigaction old_sa;
1962
1963 /* We could use signal() to install handlers... almost:
1964 * except that we need to mask ALL signals while handlers run.
1965 * I saw signal nesting in strace, race window isn't small.
1966 * SA_RESTART is also needed, but in Linux, signal()
1967 * sets SA_RESTART too.
1968 */
1969 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1970 /* sigfillset(&G.sa.sa_mask); - already done */
1971 /* G.sa.sa_flags = SA_RESTART; - already done */
1972 G.sa.sa_handler = handler;
1973 sigaction(sig, &G.sa, &old_sa);
1974 return old_sa.sa_handler;
1975}
1976
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001977static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001978
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001979static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001980static void restore_ttypgrp_and__exit(void)
1981{
1982 /* xfunc has failed! die die die */
1983 /* no EXIT traps, this is an escape hatch! */
1984 G.exiting = 1;
1985 hush_exit(xfunc_error_retval);
1986}
1987
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001988#if ENABLE_HUSH_JOB
1989
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001990/* Needed only on some libc:
1991 * It was observed that on exit(), fgetc'ed buffered data
1992 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1993 * With the net effect that even after fork(), not vfork(),
1994 * exit() in NOEXECed applet in "sh SCRIPT":
1995 * noexec_applet_here
1996 * echo END_OF_SCRIPT
1997 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1998 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001999 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002000 * and in `cmd` handling.
2001 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
2002 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01002003static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002004static void fflush_and__exit(void)
2005{
2006 fflush_all();
2007 _exit(xfunc_error_retval);
2008}
2009
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002010/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002011# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00002012/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002013# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002014
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002015/* Restores tty foreground process group, and exits.
2016 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002017 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002018 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002019 * We also call it if xfunc is exiting.
2020 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002021static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002022static void sigexit(int sig)
2023{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002024 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00002025 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002026 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
2027 /* Disable all signals: job control, SIGPIPE, etc.
2028 * Mostly paranoid measure, to prevent infinite SIGTTOU.
2029 */
2030 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04002031 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002032 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002033
2034 /* Not a signal, just exit */
2035 if (sig <= 0)
2036 _exit(- sig);
2037
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00002038 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002039}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002040#else
2041
Denys Vlasenko8391c482010-05-22 17:50:43 +02002042# define disable_restore_tty_pgrp_on_exit() ((void)0)
2043# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002044
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002045#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002046
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002047static sighandler_t pick_sighandler(unsigned sig)
2048{
2049 sighandler_t handler = SIG_DFL;
2050 if (sig < sizeof(unsigned)*8) {
2051 unsigned sigmask = (1 << sig);
2052
2053#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002054 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002055 if (G_fatal_sig_mask & sigmask)
2056 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002057 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002058#endif
2059 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002060 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002061 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002062 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002063 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002064 * in an endless loop when we try to do some
2065 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002066 */
2067 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2068 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002069 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002070 }
2071 return handler;
2072}
2073
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002074/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002075static void hush_exit(int exitcode)
2076{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002077#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
Denys Vlasenko00eb23b2020-12-21 21:36:58 +01002078 save_history(G.line_input_state); /* may be NULL */
Denys Vlasenkobede2152011-09-04 16:12:33 +02002079#endif
2080
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002081 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002082 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002083 char *argv[3];
2084 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002085 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002086 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002087 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002088 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002089 * "trap" will still show it, if executed
2090 * in the handler */
2091 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002092 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002093
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002094#if ENABLE_FEATURE_CLEAN_UP
2095 {
2096 struct variable *cur_var;
2097 if (G.cwd != bb_msg_unknown)
2098 free((char*)G.cwd);
2099 cur_var = G.top_var;
2100 while (cur_var) {
2101 struct variable *tmp = cur_var;
2102 if (!cur_var->max_len)
2103 free(cur_var->varstr);
2104 cur_var = cur_var->next;
2105 free(tmp);
2106 }
2107 }
2108#endif
2109
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002110 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002111#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002112 sigexit(- (exitcode & 0xff));
2113#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002114 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002115#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002116}
2117
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002118//TODO: return a mask of ALL handled sigs?
2119static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002120{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002121 int last_sig = 0;
2122
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002123 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002124 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002125
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002126 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002127 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002128 sig = 0;
2129 do {
2130 sig++;
2131 if (sigismember(&G.pending_set, sig)) {
2132 sigdelset(&G.pending_set, sig);
2133 goto got_sig;
2134 }
2135 } while (sig < NSIG);
2136 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002137 got_sig:
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002138#if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002139 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002140 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002141 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002142 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002143 smalluint save_rcode;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002144 int save_pre;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002145 char *argv[3];
2146 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002147 argv[1] = xstrdup(G_traps[sig]);
2148 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002149 argv[2] = NULL;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002150 save_pre = G.pre_trap_exitcode;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01002151 G.pre_trap_exitcode = save_rcode = G.last_exitcode;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002152 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002153 free(argv[1]);
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002154 G.pre_trap_exitcode = save_pre;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002155 G.last_exitcode = save_rcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002156# if ENABLE_HUSH_FUNCTIONS
2157 if (G.return_exitcode >= 0) {
2158 debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
2159 G.last_exitcode = G.return_exitcode;
2160 }
2161# endif
Denys Vlasenkob8709032011-05-08 21:20:01 +02002162 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002163 } /* else: "" trap, ignoring signal */
2164 continue;
2165 }
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002166#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002167 /* not a trap: special action */
2168 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002169 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002170 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002171 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002172 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002173 break;
2174#if ENABLE_HUSH_JOB
2175 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002176//TODO: why are we doing this? ash and dash don't do this,
2177//they have no handler for SIGHUP at all,
2178//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002179 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002180 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002181 /* bash is observed to signal whole process groups,
2182 * not individual processes */
2183 for (job = G.job_list; job; job = job->next) {
2184 if (job->pgrp <= 0)
2185 continue;
2186 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2187 if (kill(- job->pgrp, SIGHUP) == 0)
2188 kill(- job->pgrp, SIGCONT);
2189 }
2190 sigexit(SIGHUP);
2191 }
2192#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002193#if ENABLE_HUSH_FAST
2194 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002195 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002196 G.count_SIGCHLD++;
2197//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2198 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002199 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002200 * This simplifies wait builtin a bit.
2201 */
2202 break;
2203#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002204 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002205 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002206 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002207 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002208 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002209 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002210 * in interactive shell, because TERM is ignored.
2211 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002212 break;
2213 }
2214 }
2215 return last_sig;
2216}
2217
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002218
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002219static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002220{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002221 if (force || G.cwd == NULL) {
2222 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2223 * we must not try to free(bb_msg_unknown) */
2224 if (G.cwd == bb_msg_unknown)
2225 G.cwd = NULL;
2226 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2227 if (!G.cwd)
2228 G.cwd = bb_msg_unknown;
2229 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002230 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002231}
2232
Denis Vlasenko83506862007-11-23 13:11:42 +00002233
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002234/*
2235 * Shell and environment variable support
2236 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002237static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002238{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002239 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002240 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002241
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002242 pp = &G.top_var;
2243 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002244 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002245 return pp;
2246 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002247 }
2248 return NULL;
2249}
2250
Denys Vlasenko03dad222010-01-12 23:29:57 +01002251static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002252{
Denys Vlasenko29082232010-07-16 13:52:32 +02002253 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002254 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002255
2256 if (G.expanded_assignments) {
2257 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002258 while (*cpp) {
2259 char *cp = *cpp;
2260 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2261 return cp + len + 1;
2262 cpp++;
2263 }
2264 }
2265
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002266 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002267 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002268 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002269
Denys Vlasenkodea47882009-10-09 15:40:49 +02002270 if (strcmp(name, "PPID") == 0)
2271 return utoa(G.root_ppid);
2272 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002273#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002274 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002275 return utoa(next_random(&G.random_gen));
2276#endif
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002277#if ENABLE_HUSH_LINENO_VAR
2278 if (strcmp(name, "LINENO") == 0)
2279 return utoa(G.execute_lineno);
2280#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002281#if BASH_EPOCH_VARS
2282 {
2283 const char *fmt = NULL;
2284 if (strcmp(name, "EPOCHSECONDS") == 0)
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002285 fmt = "%llu";
Ron Yorstona81700b2019-04-15 10:48:29 +01002286 else if (strcmp(name, "EPOCHREALTIME") == 0)
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002287 fmt = "%llu.%06u";
Ron Yorstona81700b2019-04-15 10:48:29 +01002288 if (fmt) {
2289 struct timeval tv;
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002290 xgettimeofday(&tv);
2291 sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
Ron Yorstona81700b2019-04-15 10:48:29 +01002292 (unsigned)tv.tv_usec);
2293 return G.epoch_buf;
2294 }
2295 }
2296#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002297 return NULL;
2298}
2299
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002300#if ENABLE_HUSH_GETOPTS
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002301static void handle_changed_special_names(const char *name, unsigned name_len)
2302{
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002303 if (name_len == 6) {
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002304 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002305 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002306 return;
2307 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002308 }
2309}
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002310#else
2311/* Do not even bother evaluating arguments */
2312# define handle_changed_special_names(...) ((void)0)
2313#endif
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002314
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002316 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002317 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002318#define SETFLAG_EXPORT (1 << 0)
2319#define SETFLAG_UNEXPORT (1 << 1)
2320#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002321#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002322static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002323{
Denys Vlasenko61407802018-04-04 21:14:28 +02002324 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002325 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002326 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002327 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002328 int name_len;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002329 int retval;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002330 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002331
Denis Vlasenko950bd722009-04-21 11:23:56 +00002332 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002333 if (HUSH_DEBUG && !eq_sign)
James Byrne69374872019-07-02 11:35:03 +02002334 bb_simple_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002335
Denis Vlasenko950bd722009-04-21 11:23:56 +00002336 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002337 cur_pp = &G.top_var;
2338 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002339 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002340 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002341 continue;
2342 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002343
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002344 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002345 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002346 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002347 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002348//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2349//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002350 return -1;
2351 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002352 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002353 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2354 *eq_sign = '\0';
2355 unsetenv(str);
2356 *eq_sign = '=';
2357 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002358 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002359 /* bash 3.2.33(1) and exported vars:
2360 * # export z=z
2361 * # f() { local z=a; env | grep ^z; }
2362 * # f
2363 * z=a
2364 * # env | grep ^z
2365 * z=z
2366 */
2367 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002368 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002369 /* New variable is local ("local VAR=VAL" or
2370 * "VAR=VAL cmd")
2371 * and existing one is global, or local
2372 * on a lower level that new one.
2373 * Remove it from global variable list:
2374 */
2375 *cur_pp = cur->next;
2376 if (G.shadowed_vars_pp) {
2377 /* Save in "shadowed" list */
2378 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2379 cur->flg_export ? "exported " : "",
2380 cur->varstr, cur->var_nest_level, str, local_lvl
2381 );
2382 cur->next = *G.shadowed_vars_pp;
2383 *G.shadowed_vars_pp = cur;
2384 } else {
2385 /* Came from pseudo_exec_argv(), no need to save: delete it */
2386 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2387 cur->flg_export ? "exported " : "",
2388 cur->varstr, cur->var_nest_level, str, local_lvl
2389 );
2390 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2391 free_me = cur->varstr; /* then free it later */
2392 free(cur);
2393 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002394 break;
2395 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002396
Denis Vlasenko950bd722009-04-21 11:23:56 +00002397 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002398 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002399 free_and_exp:
2400 free(str);
2401 goto exp;
2402 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002403
2404 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002405 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002406 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002407 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002408 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002409 strcpy(cur->varstr, str);
2410 goto free_and_exp;
2411 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002412 /* Can't reuse */
2413 cur->max_len = 0;
2414 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002415 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002416 /* max_len == 0 signifies "malloced" var, which we can
2417 * (and have to) free. But we can't free(cur->varstr) here:
2418 * if cur->flg_export is 1, it is in the environment.
2419 * We should either unsetenv+free, or wait until putenv,
2420 * then putenv(new)+free(old).
2421 */
2422 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002423 goto set_str_and_exp;
2424 }
2425
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002426 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002427 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002428 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002429 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002430 cur->next = *cur_pp;
2431 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002432
2433 set_str_and_exp:
2434 cur->varstr = str;
2435 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002436#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002437 if (flags & SETFLAG_MAKE_RO) {
2438 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002439 }
2440#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002441 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002442 cur->flg_export = 1;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002443 retval = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002444 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002445 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002446 cur->flg_export = 0;
2447 /* unsetenv was already done */
2448 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002449 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002450 retval = putenv(cur->varstr);
2451 /* fall through to "free(free_me)" -
2452 * only now we can free old exported malloced string
2453 */
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002454 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002455 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002456 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002457
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002458 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002459
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002460 return retval;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002461}
2462
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002463static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2464{
2465 char *var = xasprintf("%s=%s", name, val);
2466 set_local_var(var, /*flag:*/ 0);
2467}
2468
Denys Vlasenko6db47842009-09-05 20:15:17 +02002469/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002470static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002471{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002472 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002473}
2474
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002475#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002476static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002477{
2478 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002479 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002480
Denys Vlasenko61407802018-04-04 21:14:28 +02002481 cur_pp = &G.top_var;
2482 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002483 if (strncmp(cur->varstr, name, name_len) == 0
2484 && cur->varstr[name_len] == '='
2485 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002486 if (cur->flg_read_only) {
2487 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002488 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002489 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002490
Denys Vlasenko61407802018-04-04 21:14:28 +02002491 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002492 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2493 bb_unsetenv(cur->varstr);
2494 if (!cur->max_len)
2495 free(cur->varstr);
2496 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002497
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002498 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002499 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002500 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002501 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002502
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002503 /* Handle "unset LINENO" et al even if did not find the variable to unset */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002504 handle_changed_special_names(name, name_len);
2505
Mike Frysingerd690f682009-03-30 06:50:54 +00002506 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002507}
2508
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002509static int unset_local_var(const char *name)
2510{
2511 return unset_local_var_len(name, strlen(name));
2512}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002513#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002514
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002515
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002516/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002517 * Helpers for "var1=val1 var2=val2 cmd" feature
2518 */
2519static void add_vars(struct variable *var)
2520{
2521 struct variable *next;
2522
2523 while (var) {
2524 next = var->next;
2525 var->next = G.top_var;
2526 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002527 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002528 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002529 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002530 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002531 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002532 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002533 var = next;
2534 }
2535}
2536
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002537/* We put strings[i] into variable table and possibly putenv them.
2538 * If variable is read only, we can free the strings[i]
2539 * which attempts to overwrite it.
2540 * The strings[] vector itself is freed.
2541 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002542static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002543{
2544 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002545
2546 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002547 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002548
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002549 s = strings;
2550 while (*s) {
2551 struct variable *var_p;
2552 struct variable **var_pp;
2553 char *eq;
2554
2555 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002556 if (HUSH_DEBUG && !eq)
James Byrne69374872019-07-02 11:35:03 +02002557 bb_simple_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002558 var_pp = get_ptr_to_local_var(*s, eq - *s);
2559 if (var_pp) {
2560 var_p = *var_pp;
2561 if (var_p->flg_read_only) {
2562 char **p;
2563 bb_error_msg("%s: readonly variable", *s);
2564 /*
2565 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2566 * If VAR is readonly, leaving it in the list
2567 * after asssignment error (msg above)
2568 * causes doubled error message later, on unset.
2569 */
2570 debug_printf_env("removing/freeing '%s' element\n", *s);
2571 free(*s);
2572 p = s;
2573 do { *p = p[1]; p++; } while (*p);
2574 goto next;
2575 }
2576 /* below, set_local_var() with nest level will
2577 * "shadow" (remove) this variable from
2578 * global linked list.
2579 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002580 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002581 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2582 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002583 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002584 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002585 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002586 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002587}
2588
2589
2590/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002591 * Unicode helper
2592 */
2593static void reinit_unicode_for_hush(void)
2594{
2595 /* Unicode support should be activated even if LANG is set
2596 * _during_ shell execution, not only if it was set when
2597 * shell was started. Therefore, re-check LANG every time:
2598 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002599 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2600 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002601 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002602 const char *s = get_local_var_value("LC_ALL");
2603 if (!s) s = get_local_var_value("LC_CTYPE");
2604 if (!s) s = get_local_var_value("LANG");
2605 reinit_unicode(s);
2606 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002607}
2608
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002609/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002610 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002611 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002612
2613#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002614/* To test correct lineedit/interactive behavior, type from command line:
2615 * echo $P\
2616 * \
2617 * AT\
2618 * H\
2619 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002620 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002621 */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002622static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002623{
2624 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002625
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002626 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002627
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002628# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2629 prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
2630 if (!prompt_str)
2631 prompt_str = "";
2632# else
2633 prompt_str = "> "; /* if PS2, else... */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002634 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002635 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2636 free(G.PS1);
2637 /* bash uses $PWD value, even if it is set by user.
2638 * It uses current dir only if PWD is unset.
2639 * We always use current dir. */
Denys Vlasenko649acb92020-12-23 15:29:13 +01002640 prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002641 }
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002642# endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002643 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002644 return prompt_str;
2645}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002646static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002647{
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002648# if ENABLE_FEATURE_EDITING
2649 /* In EDITING case, this function reads next input line,
2650 * saves it in i->p, then returns 1st char of it.
2651 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002652 int r;
2653 const char *prompt_str;
2654
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002655 prompt_str = setup_prompt_string();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002656 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002657 reinit_unicode_for_hush();
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002658 G.flag_SIGINT = 0;
Denys Vlasenko12566e72022-01-17 03:02:40 +01002659
2660 bb_got_signal = 0;
2661 if (!sigisemptyset(&G.pending_set)) {
2662 /* Whoops, already got a signal, do not call read_line_input */
2663 bb_got_signal = r = -1;
2664 } else {
2665 /* For shell, LI_INTERRUPTIBLE is set:
2666 * read_line_input will abort on either
2667 * getting EINTR in poll(), or if it sees bb_got_signal != 0
2668 * (IOW: if signal arrives before poll() is reached).
2669 * Interactive testcases:
2670 * (while kill -INT $$; do sleep 1; done) &
2671 * #^^^ prints ^C, prints prompt, repeats
2672 * trap 'echo I' int; (while kill -INT $$; do sleep 1; done) &
2673 * #^^^ prints ^C, prints "I", prints prompt, repeats
2674 * trap 'echo T' term; (while kill $$; do sleep 1; done) &
2675 * #^^^ prints "T", prints prompt, repeats
2676 * #(bash 5.0.17 exits after first "T", looks like a bug)
2677 */
2678 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002679 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko12566e72022-01-17 03:02:40 +01002680 );
2681 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2682 if (r == 0)
2683 raise(SIGINT);
2684 }
2685 /* bash prints ^C (before running a trap, if any)
2686 * both on keyboard ^C and on real SIGINT (non-kbd generated).
2687 */
2688 if (sigismember(&G.pending_set, SIGINT)) {
2689 write(STDOUT_FILENO, "^C\n", 3);
2690 G.last_exitcode = 128 | SIGINT;
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002691 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002692 check_and_run_traps();
Denys Vlasenko12566e72022-01-17 03:02:40 +01002693 if (r == 0) /* keyboard ^C? */
2694 continue; /* go back, read another input line */
2695 if (r > 0) /* normal input? (no ^C, no ^D, no signals) */
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002696 break;
Denys Vlasenko12566e72022-01-17 03:02:40 +01002697 if (!bb_got_signal) {
2698 /* r < 0: ^D/EOF/error detected (but not signal) */
2699 /* ^D on interactive input goes to next line before exiting: */
2700 write(STDOUT_FILENO, "\n", 1);
2701 i->p = NULL;
2702 i->peek_buf[0] = r = EOF;
2703 return r;
2704 }
2705 /* it was a signal: go back, read another input line */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002706 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002707 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002708 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002709# else
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002710 /* In !EDITING case, this function gets called for every char.
2711 * Buffering happens deeper in the call chain, in hfgetc(i->file).
2712 */
2713 int r;
2714
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002715 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002716 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002717 if (i->last_char == '\0' || i->last_char == '\n') {
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002718 const char *prompt_str = setup_prompt_string();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002719 /* Why check_and_run_traps here? Try this interactively:
2720 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2721 * $ <[enter], repeatedly...>
2722 * Without check_and_run_traps, handler never runs.
2723 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002724 check_and_run_traps();
Ron Yorstoncad3fc72021-02-03 20:47:14 +01002725 fputs_stdout(prompt_str);
Denys Vlasenko521220e2020-12-23 23:44:55 +01002726 fflush_all();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002727 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002728 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002729 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2730 * no ^C masking happens during fgetc, no special code for ^C:
2731 * it generates SIGINT as usual.
2732 */
2733 check_and_run_traps();
Denys Vlasenko521220e2020-12-23 23:44:55 +01002734 if (r != '\0' && !G.flag_SIGINT)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002735 break;
Denys Vlasenko521220e2020-12-23 23:44:55 +01002736 if (G.flag_SIGINT) {
2737 /* ^C or SIGINT: repeat */
2738 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2739 /* kernel prints "^C" itself, just print newline: */
2740 write(STDOUT_FILENO, "\n", 1);
2741 G.last_exitcode = 128 | SIGINT;
2742 }
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002743 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002744 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002745# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002746}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002747/* This is the magic location that prints prompts
2748 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002749static int fgetc_interactive(struct in_str *i)
2750{
2751 int ch;
2752 /* If it's interactive stdin, get new line. */
Denys Vlasenko21806562019-11-01 14:16:07 +01002753 if (G_interactive_fd && i->file == G.HFILE_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002754 /* Returns first char (or EOF), the rest is in i->p[] */
2755 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002756 G.promptmode = 1; /* PS2 */
2757 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002758 } else {
2759 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002760 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002761 }
2762 return ch;
2763}
Denys Vlasenko649acb92020-12-23 15:29:13 +01002764#else /* !INTERACTIVE */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002765static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002766{
2767 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002768 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002769 return ch;
2770}
Denys Vlasenko649acb92020-12-23 15:29:13 +01002771#endif /* !INTERACTIVE */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002772
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002773static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002774{
2775 int ch;
2776
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002777 if (!i->file) {
2778 /* string-based in_str */
2779 ch = (unsigned char)*i->p;
2780 if (ch != '\0') {
2781 i->p++;
2782 i->last_char = ch;
Denys Vlasenko574b9c42021-09-07 21:44:44 +02002783#if ENABLE_HUSH_LINENO_VAR
2784 if (ch == '\n') {
2785 G.parse_lineno++;
2786 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
2787 }
2788#endif
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002789 return ch;
2790 }
2791 return EOF;
2792 }
2793
2794 /* FILE-based in_str */
2795
Denys Vlasenko4074d492016-09-30 01:49:53 +02002796#if ENABLE_FEATURE_EDITING
2797 /* This can be stdin, check line editing char[] buffer */
2798 if (i->p && *i->p != '\0') {
2799 ch = (unsigned char)*i->p++;
2800 goto out;
2801 }
2802#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002803 /* peek_buf[] is an int array, not char. Can contain EOF. */
2804 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002805 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002806 int ch2 = i->peek_buf[1];
2807 i->peek_buf[0] = ch2;
2808 if (ch2 == 0) /* very likely, avoid redundant write */
2809 goto out;
2810 i->peek_buf[1] = 0;
2811 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002812 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002813
Denys Vlasenko4074d492016-09-30 01:49:53 +02002814 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002815 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002816 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002817 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002818#if ENABLE_HUSH_LINENO_VAR
2819 if (ch == '\n') {
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002820 G.parse_lineno++;
2821 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
Denys Vlasenko5807e182018-02-08 19:19:04 +01002822 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002823#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002824 return ch;
2825}
2826
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002827static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002828{
2829 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002830
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002831 if (!i->file) {
2832 /* string-based in_str */
2833 /* Doesn't report EOF on NUL. None of the callers care. */
2834 return (unsigned char)*i->p;
2835 }
2836
2837 /* FILE-based in_str */
2838
Denys Vlasenko4074d492016-09-30 01:49:53 +02002839#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002840 /* This can be stdin, check line editing char[] buffer */
2841 if (i->p && *i->p != '\0')
2842 return (unsigned char)*i->p;
2843#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002844 /* peek_buf[] is an int array, not char. Can contain EOF. */
2845 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002846 if (ch != 0)
2847 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002848
Denys Vlasenko4074d492016-09-30 01:49:53 +02002849 /* Need to get a new char */
2850 ch = fgetc_interactive(i);
2851 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2852
2853 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2854#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2855 if (i->p) {
2856 i->p -= 1;
2857 return ch;
2858 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002859#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002860 i->peek_buf[0] = ch;
2861 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002862 return ch;
2863}
2864
Denys Vlasenko4074d492016-09-30 01:49:53 +02002865/* Only ever called if i_peek() was called, and did not return EOF.
2866 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2867 * not end-of-line. Therefore we never need to read a new editing line here.
2868 */
2869static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002870{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002871 int ch;
2872
2873 /* There are two cases when i->p[] buffer exists.
2874 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002875 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002876 * In both cases, we know that i->p[0] exists and not NUL, and
2877 * the peek2 result is in i->p[1].
2878 */
2879 if (i->p)
2880 return (unsigned char)i->p[1];
2881
2882 /* Now we know it is a file-based in_str. */
2883
2884 /* peek_buf[] is an int array, not char. Can contain EOF. */
2885 /* Is there 2nd char? */
2886 ch = i->peek_buf[1];
2887 if (ch == 0) {
2888 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002889 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002890 i->peek_buf[1] = ch;
2891 }
2892
2893 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2894 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002895}
2896
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002897static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2898{
2899 for (;;) {
2900 int ch, ch2;
2901
2902 ch = i_getch(input);
2903 if (ch != '\\')
2904 return ch;
2905 ch2 = i_peek(input);
2906 if (ch2 != '\n')
2907 return ch;
2908 /* backslash+newline, skip it */
2909 i_getch(input);
2910 }
2911}
2912
2913/* Note: this function _eats_ \<newline> pairs, safe to use plain
2914 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2915 */
2916static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2917{
2918 for (;;) {
2919 int ch, ch2;
2920
2921 ch = i_peek(input);
2922 if (ch != '\\')
2923 return ch;
2924 ch2 = i_peek2(input);
2925 if (ch2 != '\n')
2926 return ch;
2927 /* backslash+newline, skip it */
2928 i_getch(input);
2929 i_getch(input);
2930 }
2931}
2932
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002933static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002934{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002935 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002936 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002937 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002938}
2939
2940static void setup_string_in_str(struct in_str *i, const char *s)
2941{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002942 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002943 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002944 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002945}
2946
2947
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002948/*
2949 * o_string support
2950 */
2951#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002952
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002953static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002954{
2955 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002956 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002957 if (o->data)
2958 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002959}
2960
Denys Vlasenko18567402018-07-20 17:51:31 +02002961static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002962{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002963 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002964 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002965}
2966
Denys Vlasenko18567402018-07-20 17:51:31 +02002967static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002968{
2969 free(o->data);
2970}
2971
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002972static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002973{
2974 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002975 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002976 o->data = xrealloc(o->data, 1 + o->maxlen);
2977 }
2978}
2979
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002980static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002981{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002982 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002983 if (o->length < o->maxlen) {
2984 /* likely. avoid o_grow_by() call */
2985 add:
2986 o->data[o->length] = ch;
2987 o->length++;
2988 o->data[o->length] = '\0';
2989 return;
2990 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002991 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002992 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002993}
2994
Denys Vlasenko657086a2016-09-29 18:07:42 +02002995#if 0
2996/* Valid only if we know o_string is not empty */
2997static void o_delchr(o_string *o)
2998{
2999 o->length--;
3000 o->data[o->length] = '\0';
3001}
3002#endif
3003
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003004static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003005{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003006 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02003007 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003008 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003009}
3010
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003011static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00003012{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003013 o_addblock(o, str, strlen(str));
3014}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003015
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003016static void o_addstr_with_NUL(o_string *o, const char *str)
3017{
3018 o_addblock(o, str, strlen(str) + 1);
3019}
3020
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003021#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003022static void nommu_addchr(o_string *o, int ch)
3023{
3024 if (o)
3025 o_addchr(o, ch);
3026}
3027#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003028# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003029#endif
3030
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003031#if ENABLE_HUSH_MODE_X
3032static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003033{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003034 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00003035}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003036static void x_mode_addstr(const char *str)
3037{
3038 o_addstr(&G.x_mode_buf, str);
3039}
3040static void x_mode_addblock(const char *str, int len)
3041{
3042 o_addblock(&G.x_mode_buf, str, len);
3043}
3044static void x_mode_prefix(void)
3045{
3046 int n = G.x_mode_depth;
3047 do x_mode_addchr('+'); while (--n >= 0);
3048}
3049static void x_mode_flush(void)
3050{
3051 int len = G.x_mode_buf.length;
3052 if (len <= 0)
3053 return;
3054 if (G.x_mode_fd > 0) {
3055 G.x_mode_buf.data[len] = '\n';
3056 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
3057 }
3058 G.x_mode_buf.length = 0;
3059}
3060#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00003061
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003062/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02003063 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003064 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
3065 * Apparently, on unquoted $v bash still does globbing
3066 * ("v='*.txt'; echo $v" prints all .txt files),
3067 * but NOT brace expansion! Thus, there should be TWO independent
3068 * quoting mechanisms on $v expansion side: one protects
3069 * $v from brace expansion, and other additionally protects "$v" against globbing.
3070 * We have only second one.
3071 */
3072
Denys Vlasenko9e800222010-10-03 14:28:04 +02003073#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003074# define MAYBE_BRACES "{}"
3075#else
3076# define MAYBE_BRACES ""
3077#endif
3078
Eric Andersen25f27032001-04-26 23:22:31 +00003079/* My analysis of quoting semantics tells me that state information
3080 * is associated with a destination, not a source.
3081 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003082static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00003083{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003084 int sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003085 /* '-' is included because of this case:
3086 * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
3087 */
3088 char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003089 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003090 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003091 o_grow_by(o, sz);
3092 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003093 o->data[o->length] = '\\';
3094 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003095 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003096 o->data[o->length] = ch;
3097 o->length++;
3098 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003099}
3100
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003101static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003102{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003103 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003104 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003105 && strchr("*?[-\\" MAYBE_BRACES, ch)
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003106 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003107 sz++;
3108 o->data[o->length] = '\\';
3109 o->length++;
3110 }
3111 o_grow_by(o, sz);
3112 o->data[o->length] = ch;
3113 o->length++;
3114 o->data[o->length] = '\0';
3115}
3116
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003117static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003118{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003119 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003120 char ch;
3121 int sz;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003122 int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003123 if (ordinary_cnt > len) /* paranoia */
3124 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003125 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003126 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003127 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003128 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003129 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003130
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003131 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003132 sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003133 if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003134 sz++;
3135 o->data[o->length] = '\\';
3136 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003137 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003138 o_grow_by(o, sz);
3139 o->data[o->length] = ch;
3140 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003141 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003142 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003143}
3144
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003145static void o_addQblock(o_string *o, const char *str, int len)
3146{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003147 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003148 o_addblock(o, str, len);
3149 return;
3150 }
3151 o_addqblock(o, str, len);
3152}
3153
Denys Vlasenko38292b62010-09-05 14:49:40 +02003154static void o_addQstr(o_string *o, const char *str)
3155{
3156 o_addQblock(o, str, strlen(str));
3157}
3158
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003159/* A special kind of o_string for $VAR and `cmd` expansion.
3160 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003161 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003162 * list[i] contains an INDEX (int!) into this string data.
3163 * It means that if list[] needs to grow, data needs to be moved higher up
3164 * but list[i]'s need not be modified.
3165 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003166 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003167 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3168 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003169#if DEBUG_EXPAND || DEBUG_GLOB
3170static void debug_print_list(const char *prefix, o_string *o, int n)
3171{
3172 char **list = (char**)o->data;
3173 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3174 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003175
3176 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003177 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 +02003178 prefix, list, n, string_start, o->length, o->maxlen,
3179 !!(o->o_expflags & EXP_FLAG_GLOB),
3180 o->has_quoted_part,
3181 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003182 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003183 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003184 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3185 o->data + (int)(uintptr_t)list[i] + string_start,
3186 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003187 i++;
3188 }
3189 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003190 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003191 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003192 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003193 }
3194}
3195#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003196# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003197#endif
3198
3199/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3200 * in list[n] so that it points past last stored byte so far.
3201 * It returns n+1. */
3202static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003203{
3204 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003205 int string_start;
3206 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003207
3208 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003209 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3210 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003211 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003212 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003213 /* list[n] points to string_start, make space for 16 more pointers */
3214 o->maxlen += 0x10 * sizeof(list[0]);
3215 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003216 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003217 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003218 /*
3219 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3220 * check. (grep for -prev-ifs-check-).
3221 * Ensure that argv[-1][last] is not garbage
3222 * but zero bytes, to save index check there.
3223 */
3224 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003225 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003226 } else {
3227 debug_printf_list("list[%d]=%d string_start=%d\n",
3228 n, string_len, string_start);
3229 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003230 } else {
3231 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003232 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3233 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003234 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3235 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003236 o->has_empty_slot = 0;
3237 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003238 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003239 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003240 return n + 1;
3241}
3242
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003243/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003244static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003245{
3246 char **list = (char**)o->data;
3247 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3248
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003249 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003250}
3251
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003252/*
3253 * Globbing routines.
3254 *
3255 * Most words in commands need to be globbed, even ones which are
3256 * (single or double) quoted. This stems from the possiblity of
3257 * constructs like "abc"* and 'abc'* - these should be globbed.
3258 * Having a different code path for fully-quoted strings ("abc",
3259 * 'abc') would only help performance-wise, but we still need
3260 * code for partially-quoted strings.
3261 *
3262 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003263 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003264 * to a string, then globbed, and if globbing does not match anything,
3265 * it is used verbatim". Here are two examples where it fails:
3266 *
3267 * echo 'b\*'?
3268 *
3269 * The globbing can't be avoided (because of '?' at the end).
3270 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3271 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003272 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003273 * Now, look at this:
3274 *
3275 * v='\\\*'; echo b$v?
3276 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003277 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003278 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003279 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003280 *
3281 * ash implements this by having an encoded representation of the word
3282 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3283 * Glob pattern is derived from it. If glob fails, the decision what result
3284 * should be is made using that encoded representation. Not glob pattern.
3285 */
3286
Denys Vlasenko9e800222010-10-03 14:28:04 +02003287#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003288/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3289 * first, it processes even {a} (no commas), second,
3290 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003291 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003292 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003293
3294/* Helper */
3295static int glob_needed(const char *s)
3296{
3297 while (*s) {
3298 if (*s == '\\') {
3299 if (!s[1])
3300 return 0;
3301 s += 2;
3302 continue;
3303 }
3304 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3305 return 1;
3306 s++;
3307 }
3308 return 0;
3309}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003310/* Return pointer to next closing brace or to comma */
3311static const char *next_brace_sub(const char *cp)
3312{
3313 unsigned depth = 0;
3314 cp++;
3315 while (*cp != '\0') {
3316 if (*cp == '\\') {
3317 if (*++cp == '\0')
3318 break;
3319 cp++;
3320 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003321 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003322 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003323 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003324 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003325 depth++;
3326 }
3327
3328 return *cp != '\0' ? cp : NULL;
3329}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003330/* Recursive brace globber. Note: may garble pattern[]. */
3331static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003332{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003333 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003334 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003335 const char *next;
3336 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003337 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003338 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003339
3340 debug_printf_glob("glob_brace('%s')\n", pattern);
3341
3342 begin = pattern;
3343 while (1) {
3344 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003345 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003346 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003347 /* Find the first sub-pattern and at the same time
3348 * find the rest after the closing brace */
3349 next = next_brace_sub(begin);
3350 if (next == NULL) {
3351 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003352 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003353 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003354 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003355 /* "{abc}" with no commas - illegal
3356 * brace expr, disregard and skip it */
3357 begin = next + 1;
3358 continue;
3359 }
3360 break;
3361 }
3362 if (*begin == '\\' && begin[1] != '\0')
3363 begin++;
3364 begin++;
3365 }
3366 debug_printf_glob("begin:%s\n", begin);
3367 debug_printf_glob("next:%s\n", next);
3368
3369 /* Now find the end of the whole brace expression */
3370 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003371 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003372 rest = next_brace_sub(rest);
3373 if (rest == NULL) {
3374 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003375 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003376 }
3377 debug_printf_glob("rest:%s\n", rest);
3378 }
3379 rest_len = strlen(++rest) + 1;
3380
3381 /* We are sure the brace expression is well-formed */
3382
3383 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003384 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003385
3386 /* We have a brace expression. BEGIN points to the opening {,
3387 * NEXT points past the terminator of the first element, and REST
3388 * points past the final }. We will accumulate result names from
3389 * recursive runs for each brace alternative in the buffer using
Denys Vlasenko62f1eed2021-10-12 22:39:11 +02003390 * GLOB_APPEND. */
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003391
3392 p = begin + 1;
3393 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003394 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003395 memcpy(
3396 mempcpy(
3397 mempcpy(new_pattern_buf,
3398 /* We know the prefix for all sub-patterns */
3399 pattern, begin - pattern),
3400 p, next - p),
3401 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003402
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003403 /* Note: glob_brace() may garble new_pattern_buf[].
3404 * That's why we re-copy prefix every time (1st memcpy above).
3405 */
3406 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003407 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003408 /* We saw the last entry */
3409 break;
3410 }
3411 p = next + 1;
3412 next = next_brace_sub(next);
3413 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003414 free(new_pattern_buf);
3415 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003416
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003417 simple_glob:
3418 {
3419 int gr;
3420 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003421
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003422 memset(&globdata, 0, sizeof(globdata));
3423 gr = glob(pattern, 0, NULL, &globdata);
3424 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3425 if (gr != 0) {
3426 if (gr == GLOB_NOMATCH) {
3427 globfree(&globdata);
3428 /* NB: garbles parameter */
3429 unbackslash(pattern);
3430 o_addstr_with_NUL(o, pattern);
3431 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3432 return o_save_ptr_helper(o, n);
3433 }
3434 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003435 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003436 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3437 * but we didn't specify it. Paranoia again. */
3438 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3439 }
3440 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3441 char **argv = globdata.gl_pathv;
3442 while (1) {
3443 o_addstr_with_NUL(o, *argv);
3444 n = o_save_ptr_helper(o, n);
3445 argv++;
3446 if (!*argv)
3447 break;
3448 }
3449 }
3450 globfree(&globdata);
3451 }
3452 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003453}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003454/* Performs globbing on last list[],
3455 * saving each result as a new list[].
3456 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003457static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003458{
3459 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003460
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003461 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003462 if (!o->data)
3463 return o_save_ptr_helper(o, n);
3464 pattern = o->data + o_get_last_ptr(o, n);
3465 debug_printf_glob("glob pattern '%s'\n", pattern);
3466 if (!glob_needed(pattern)) {
3467 /* unbackslash last string in o in place, fix length */
3468 o->length = unbackslash(pattern) - o->data;
3469 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3470 return o_save_ptr_helper(o, n);
3471 }
3472
3473 copy = xstrdup(pattern);
3474 /* "forget" pattern in o */
3475 o->length = pattern - o->data;
3476 n = glob_brace(copy, o, n);
3477 free(copy);
3478 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003479 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003480 return n;
3481}
3482
Denys Vlasenko238081f2010-10-03 14:26:26 +02003483#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003484
3485/* Helper */
3486static int glob_needed(const char *s)
3487{
3488 while (*s) {
3489 if (*s == '\\') {
3490 if (!s[1])
3491 return 0;
3492 s += 2;
3493 continue;
3494 }
3495 if (*s == '*' || *s == '[' || *s == '?')
3496 return 1;
3497 s++;
3498 }
3499 return 0;
3500}
3501/* Performs globbing on last list[],
3502 * saving each result as a new list[].
3503 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003504static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003505{
3506 glob_t globdata;
3507 int gr;
3508 char *pattern;
3509
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003510 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003511 if (!o->data)
3512 return o_save_ptr_helper(o, n);
3513 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003514 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003515 if (!glob_needed(pattern)) {
3516 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003517 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003518 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003519 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003520 return o_save_ptr_helper(o, n);
3521 }
3522
3523 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003524 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3525 * If we glob "*.\*" and don't find anything, we need
3526 * to fall back to using literal "*.*", but GLOB_NOCHECK
3527 * will return "*.\*"!
3528 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003529 gr = glob(pattern, 0, NULL, &globdata);
3530 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003531 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003532 if (gr == GLOB_NOMATCH) {
3533 globfree(&globdata);
3534 goto literal;
3535 }
3536 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003537 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003538 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3539 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003540 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003541 }
3542 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3543 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003544 /* "forget" pattern in o */
3545 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003546 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003547 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003548 n = o_save_ptr_helper(o, n);
3549 argv++;
3550 if (!*argv)
3551 break;
3552 }
3553 }
3554 globfree(&globdata);
3555 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003556 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003557 return n;
3558}
3559
Denys Vlasenko238081f2010-10-03 14:26:26 +02003560#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003561
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003562/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003563 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003564static int o_save_ptr(o_string *o, int n)
3565{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003566 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003567 /* If o->has_empty_slot, list[n] was already globbed
3568 * (if it was requested back then when it was filled)
3569 * so don't do that again! */
3570 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003571 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003572 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003573 return o_save_ptr_helper(o, n);
3574}
3575
3576/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003577static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003578{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003579 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003580 int string_start;
3581
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003582 if (DEBUG_EXPAND)
3583 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003584 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003585 list = (char**)o->data;
3586 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3587 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003588 while (n) {
3589 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003590 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003591 }
3592 return list;
3593}
3594
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003595static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003596
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003597/* Returns pi->next - next pipe in the list */
3598static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003599{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003600 struct pipe *next;
3601 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003602
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003603 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003604 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003605 struct command *command;
3606 struct redir_struct *r, *rnext;
3607
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003608 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003609 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003610 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003611 if (DEBUG_CLEAN) {
3612 int a;
3613 char **p;
3614 for (a = 0, p = command->argv; *p; a++, p++) {
3615 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3616 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003617 }
3618 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003619 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003620 }
3621 /* not "else if": on syntax error, we may have both! */
3622 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003623 debug_printf_clean(" begin group (cmd_type:%d)\n",
3624 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003625 free_pipe_list(command->group);
3626 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003627 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003628 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003629 /* else is crucial here.
3630 * If group != NULL, child_func is meaningless */
3631#if ENABLE_HUSH_FUNCTIONS
3632 else if (command->child_func) {
3633 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3634 command->child_func->parent_cmd = NULL;
3635 }
3636#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003637#if !BB_MMU
3638 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003639 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003640#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003641 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003642 debug_printf_clean(" redirect %d%s",
3643 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003644 /* guard against the case >$FOO, where foo is unset or blank */
3645 if (r->rd_filename) {
3646 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3647 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003648 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003649 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003650 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003651 rnext = r->next;
3652 free(r);
3653 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003654 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003655 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003656 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003657 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003658#if ENABLE_HUSH_JOB
3659 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003660 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003661#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003662
3663 next = pi->next;
3664 free(pi);
3665 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003666}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003667
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003668static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003669{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003670 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003671#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003672 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003673#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003674 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003675 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003676 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003677}
3678
3679
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003680/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003681
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003682#ifndef debug_print_tree
3683static void debug_print_tree(struct pipe *pi, int lvl)
3684{
Denys Vlasenko987be932022-02-06 20:07:12 +01003685 static const char *const PIPE[] ALIGN_PTR = {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003686 [PIPE_SEQ] = "SEQ",
3687 [PIPE_AND] = "AND",
3688 [PIPE_OR ] = "OR" ,
3689 [PIPE_BG ] = "BG" ,
3690 };
3691 static const char *RES[] = {
3692 [RES_NONE ] = "NONE" ,
3693# if ENABLE_HUSH_IF
3694 [RES_IF ] = "IF" ,
3695 [RES_THEN ] = "THEN" ,
3696 [RES_ELIF ] = "ELIF" ,
3697 [RES_ELSE ] = "ELSE" ,
3698 [RES_FI ] = "FI" ,
3699# endif
3700# if ENABLE_HUSH_LOOPS
3701 [RES_FOR ] = "FOR" ,
3702 [RES_WHILE] = "WHILE",
3703 [RES_UNTIL] = "UNTIL",
3704 [RES_DO ] = "DO" ,
3705 [RES_DONE ] = "DONE" ,
3706# endif
3707# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3708 [RES_IN ] = "IN" ,
3709# endif
3710# if ENABLE_HUSH_CASE
3711 [RES_CASE ] = "CASE" ,
3712 [RES_CASE_IN ] = "CASE_IN" ,
3713 [RES_MATCH] = "MATCH",
3714 [RES_CASE_BODY] = "CASE_BODY",
3715 [RES_ESAC ] = "ESAC" ,
3716# endif
3717 [RES_XXXX ] = "XXXX" ,
3718 [RES_SNTX ] = "SNTX" ,
3719 };
Denys Vlasenko987be932022-02-06 20:07:12 +01003720 static const char *const CMDTYPE[] ALIGN_PTR = {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003721 "{}",
3722 "()",
3723 "[noglob]",
3724# if ENABLE_HUSH_FUNCTIONS
3725 "func()",
3726# endif
3727 };
3728
3729 int pin, prn;
3730
3731 pin = 0;
3732 while (pi) {
Denys Vlasenko83a49672021-06-15 18:12:13 +02003733 fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
Denys Vlasenko5807e182018-02-08 19:19:04 +01003734 lvl*2, "",
3735 pin,
Denys Vlasenko83a49672021-06-15 18:12:13 +02003736 pi->num_cmds,
Denys Vlasenko5807e182018-02-08 19:19:04 +01003737 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3738 RES[pi->res_word],
3739 pi->followup, PIPE[pi->followup]
3740 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003741 prn = 0;
3742 while (prn < pi->num_cmds) {
3743 struct command *command = &pi->cmds[prn];
3744 char **argv = command->argv;
3745
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003746 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003747 lvl*2, "", prn,
3748 command->assignment_cnt);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003749# if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko5807e182018-02-08 19:19:04 +01003750 fdprintf(2, " LINENO:%u", command->lineno);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003751# endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003752 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003753 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003754 CMDTYPE[command->cmd_type],
3755 argv
3756# if !BB_MMU
3757 , " group_as_string:", command->group_as_string
3758# else
3759 , "", ""
3760# endif
3761 );
3762 debug_print_tree(command->group, lvl+1);
3763 prn++;
3764 continue;
3765 }
3766 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003767 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003768 argv++;
3769 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003770 if (command->redirects)
3771 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003772 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003773 prn++;
3774 }
3775 pi = pi->next;
3776 pin++;
3777 }
3778}
3779#endif /* debug_print_tree */
3780
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003781static struct pipe *new_pipe(void)
3782{
Eric Andersen25f27032001-04-26 23:22:31 +00003783 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003784 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003785 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003786 return pi;
3787}
3788
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003789/* Command (member of a pipe) is complete, or we start a new pipe
3790 * if ctx->command is NULL.
3791 * No errors possible here.
3792 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003793static int done_command(struct parse_context *ctx)
3794{
3795 /* The command is really already in the pipe structure, so
3796 * advance the pipe counter and make a new, null command. */
3797 struct pipe *pi = ctx->pipe;
3798 struct command *command = ctx->command;
3799
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003800#if 0 /* Instead we emit error message at run time */
3801 if (ctx->pending_redirect) {
3802 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003803 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003804 ctx->pending_redirect = NULL;
3805 }
3806#endif
3807
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003808 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003809 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003810 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003811 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003812 }
3813 pi->num_cmds++;
3814 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003815 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003816 } else {
3817 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3818 }
3819
3820 /* Only real trickiness here is that the uncommitted
3821 * command structure is not counted in pi->num_cmds. */
3822 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003823 ctx->command = command = &pi->cmds[pi->num_cmds];
3824 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003825 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003826#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02003827 command->lineno = G.parse_lineno;
3828 debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003829#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003830 return pi->num_cmds; /* used only for 0/nonzero check */
3831}
3832
3833static void done_pipe(struct parse_context *ctx, pipe_style type)
3834{
3835 int not_null;
3836
3837 debug_printf_parse("done_pipe entered, followup %d\n", type);
3838 /* Close previous command */
3839 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003840#if HAS_KEYWORDS
3841 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3842 ctx->ctx_inverted = 0;
3843 ctx->pipe->res_word = ctx->ctx_res_w;
3844#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003845 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3846 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003847 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3848 * in a backgrounded subshell.
3849 */
3850 struct pipe *pi;
3851 struct command *command;
3852
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003853 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003854 pi = ctx->list_head;
3855 while (pi != ctx->pipe) {
3856 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3857 goto no_conv;
3858 pi = pi->next;
3859 }
3860
3861 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3862 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3863 pi = xzalloc(sizeof(*pi));
3864 pi->followup = PIPE_BG;
3865 pi->num_cmds = 1;
3866 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3867 command = &pi->cmds[0];
3868 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3869 command->cmd_type = CMD_NORMAL;
3870 command->group = ctx->list_head;
3871#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003872 command->group_as_string = xstrndup(
3873 ctx->as_string.data,
3874 ctx->as_string.length - 1 /* do not copy last char, "&" */
3875 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003876#endif
3877 /* Replace all pipes in ctx with one newly created */
3878 ctx->list_head = ctx->pipe = pi;
Denys Vlasenko83a49672021-06-15 18:12:13 +02003879 /* for cases like "cmd && &", do not be tricked by last command
3880 * being null - the entire {...} & is NOT null! */
3881 not_null = 1;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003882 } else {
3883 no_conv:
3884 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003885 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003886
3887 /* Without this check, even just <enter> on command line generates
3888 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003889 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003890 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003891#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003892 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003893#endif
3894#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003895 || ctx->ctx_res_w == RES_DONE
3896 || ctx->ctx_res_w == RES_FOR
3897 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003898#endif
3899#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003900 || ctx->ctx_res_w == RES_ESAC
3901#endif
3902 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003903 struct pipe *new_p;
3904 debug_printf_parse("done_pipe: adding new pipe: "
3905 "not_null:%d ctx->ctx_res_w:%d\n",
3906 not_null, ctx->ctx_res_w);
3907 new_p = new_pipe();
3908 ctx->pipe->next = new_p;
3909 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003910 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003911 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003912 * This is used to control execution.
3913 * RES_FOR and RES_IN are NOT sticky (needed to support
3914 * cases where variable or value happens to match a keyword):
3915 */
3916#if ENABLE_HUSH_LOOPS
3917 if (ctx->ctx_res_w == RES_FOR
3918 || ctx->ctx_res_w == RES_IN)
3919 ctx->ctx_res_w = RES_NONE;
3920#endif
3921#if ENABLE_HUSH_CASE
3922 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003923 ctx->ctx_res_w = RES_CASE_BODY;
3924 if (ctx->ctx_res_w == RES_CASE)
3925 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003926#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003927 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003928 /* Create the memory for command, roughly:
3929 * ctx->pipe->cmds = new struct command;
3930 * ctx->command = &ctx->pipe->cmds[0];
3931 */
3932 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003933 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003934 }
3935 debug_printf_parse("done_pipe return\n");
3936}
3937
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003938static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003939{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003940 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003941 if (MAYBE_ASSIGNMENT != 0)
3942 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003943 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003944 /* Create the memory for command, roughly:
3945 * ctx->pipe->cmds = new struct command;
3946 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003947 */
3948 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003949}
3950
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003951/* If a reserved word is found and processed, parse context is modified
3952 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003953 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003954#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003955struct reserved_combo {
3956 char literal[6];
3957 unsigned char res;
3958 unsigned char assignment_flag;
Denys Vlasenko965b7952020-11-30 13:03:03 +01003959 uint32_t flag;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003960};
3961enum {
3962 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003963# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003964 FLAG_IF = (1 << RES_IF ),
3965 FLAG_THEN = (1 << RES_THEN ),
3966 FLAG_ELIF = (1 << RES_ELIF ),
3967 FLAG_ELSE = (1 << RES_ELSE ),
3968 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003969# endif
3970# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003971 FLAG_FOR = (1 << RES_FOR ),
3972 FLAG_WHILE = (1 << RES_WHILE),
3973 FLAG_UNTIL = (1 << RES_UNTIL),
3974 FLAG_DO = (1 << RES_DO ),
3975 FLAG_DONE = (1 << RES_DONE ),
3976 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003977# endif
3978# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003979 FLAG_MATCH = (1 << RES_MATCH),
3980 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003981# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003982 FLAG_START = (1 << RES_XXXX ),
3983};
3984
3985static const struct reserved_combo* match_reserved_word(o_string *word)
3986{
Eric Andersen25f27032001-04-26 23:22:31 +00003987 /* Mostly a list of accepted follow-up reserved words.
3988 * FLAG_END means we are done with the sequence, and are ready
3989 * to turn the compound list into a command.
3990 * FLAG_START means the word must start a new compound list.
3991 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01003992 static const struct reserved_combo reserved_list[] ALIGN4 = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003993# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003994 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3995 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3996 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3997 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3998 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3999 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004000# endif
4001# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004002 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4003 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
4004 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
4005 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4006 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
4007 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004008# endif
4009# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004010 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4011 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004012# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004013 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004014 const struct reserved_combo *r;
4015
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02004016 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004017 if (strcmp(word->data, r->literal) == 0)
4018 return r;
4019 }
4020 return NULL;
4021}
Denys Vlasenko5807e182018-02-08 19:19:04 +01004022/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00004023 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004024static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004025{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004026# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004027 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004028 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004029 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004030# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004031 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004032
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004033 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004034 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004035 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004036 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01004037 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004038
4039 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004040# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004041 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4042 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004043 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004044 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004045# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004046 if (r->flag == 0) { /* '!' */
4047 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004048 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004049 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004050 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004051 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01004052 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004053 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004054 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004055 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004056
Denys Vlasenko9e55a152017-07-10 10:01:12 +02004057 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004058 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004059 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004060 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004061 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004062 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004063 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01004064 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004065 } else {
4066 /* "{...} fi" is ok. "{...} if" is not
4067 * Example:
4068 * if { echo foo; } then { echo bar; } fi */
4069 if (ctx->command->group)
4070 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004071 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004072
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004073 ctx->ctx_res_w = r->res;
4074 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004075 ctx->is_assignment = r->assignment_flag;
4076 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004077
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004078 if (ctx->old_flag & FLAG_END) {
4079 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004080
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004081 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004082 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004083 old = ctx->stack;
4084 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004085 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004086# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004087 /* At this point, the compound command's string is in
4088 * ctx->as_string... except for the leading keyword!
4089 * Consider this example: "echo a | if true; then echo a; fi"
4090 * ctx->as_string will contain "true; then echo a; fi",
4091 * with "if " remaining in old->as_string!
4092 */
4093 {
4094 char *str;
4095 int len = old->as_string.length;
4096 /* Concatenate halves */
4097 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004098 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004099 /* Find where leading keyword starts in first half */
4100 str = old->as_string.data + len;
4101 if (str > old->as_string.data)
4102 str--; /* skip whitespace after keyword */
4103 while (str > old->as_string.data && isalpha(str[-1]))
4104 str--;
4105 /* Ugh, we're done with this horrid hack */
4106 old->command->group_as_string = xstrdup(str);
4107 debug_printf_parse("pop, remembering as:'%s'\n",
4108 old->command->group_as_string);
4109 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004110# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004111 *ctx = *old; /* physical copy */
4112 free(old);
4113 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004114 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004115}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004116#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004117
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004118/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004119 * Normal return is 0. Syntax errors return 1.
4120 * Note: on return, word is reset, but not o_free'd!
4121 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004122static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004123{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004124 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004125
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004126 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4127 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004128 debug_printf_parse("done_word return 0: true null, ignored\n");
4129 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004130 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004131
Eric Andersen25f27032001-04-26 23:22:31 +00004132 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004133 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4134 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004135 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004136 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004137 * If the redirection operator is "<<" or "<<-", the word
4138 * that follows the redirection operator shall be
4139 * subjected to quote removal; it is unspecified whether
4140 * any of the other expansions occur. For the other
4141 * redirection operators, the word that follows the
4142 * redirection operator shall be subjected to tilde
4143 * expansion, parameter expansion, command substitution,
4144 * arithmetic expansion, and quote removal.
4145 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004146 * on the word by a non-interactive shell; an interactive
4147 * shell may perform it, but shall do so only when
4148 * the expansion would result in one word."
4149 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004150//bash does not do parameter/command substitution or arithmetic expansion
4151//for _heredoc_ redirection word: these constructs look for exact eof marker
4152// as written:
4153// <<EOF$t
4154// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004155// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4156
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004157 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004158 /* Cater for >\file case:
4159 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4160 * Same with heredocs:
4161 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4162 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004163 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4164 unbackslash(ctx->pending_redirect->rd_filename);
4165 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004166 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004167 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4168 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004169 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004170 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004171 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004172 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004173#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004174# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004175 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004176 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004177 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004178 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004179 /* ctx->ctx_res_w = RES_MATCH; */
4180 ctx->ctx_dsemicolon = 0;
4181 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004182# endif
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004183# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4184 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
4185 && strcmp(ctx->word.data, "]]") == 0
4186 ) {
4187 /* allow "[[ ]] >file" etc */
4188 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4189 } else
4190# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004191 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004192# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004193 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4194 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004195# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004196# if ENABLE_HUSH_CASE
4197 && ctx->ctx_res_w != RES_CASE
4198# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004199 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004200 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004201 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004202 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004203 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004204# if ENABLE_HUSH_LINENO_VAR
4205/* Case:
4206 * "while ...; do
4207 * cmd ..."
4208 * If we don't close the pipe _now_, immediately after "do", lineno logic
4209 * sees "cmd" as starting at "do" - i.e., at the previous line.
4210 */
4211 if (0
4212 IF_HUSH_IF(|| reserved->res == RES_THEN)
4213 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4214 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4215 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4216 ) {
4217 done_pipe(ctx, PIPE_SEQ);
4218 }
4219# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004220 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004221 debug_printf_parse("done_word return %d\n",
4222 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004223 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004224 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004225# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4226 if (strcmp(ctx->word.data, "[[") == 0) {
4227 command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
4228 } else
4229# endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02004230# if defined(CMD_SINGLEWORD_NOGLOB)
4231 if (0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004232 /* In bash, local/export/readonly are special, args
4233 * are assignments and therefore expansion of them
4234 * should be "one-word" expansion:
4235 * $ export i=`echo 'a b'` # one arg: "i=a b"
4236 * compare with:
4237 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4238 * ls: cannot access i=a: No such file or directory
4239 * ls: cannot access b: No such file or directory
4240 * Note: bash 3.2.33(1) does this only if export word
4241 * itself is not quoted:
4242 * $ export i=`echo 'aaa bbb'`; echo "$i"
4243 * aaa bbb
4244 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4245 * aaa
4246 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004247 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4248 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4249 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004250 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004251 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4252 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004253# else
4254 { /* empty block to pair "if ... else" */ }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004255# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004256 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004257#endif /* HAS_KEYWORDS */
4258
Denis Vlasenkobb929512009-04-16 10:59:40 +00004259 if (command->group) {
4260 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004261 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004262 debug_printf_parse("done_word return 1: syntax error, "
4263 "groups and arglists don't mix\n");
4264 return 1;
4265 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004266
4267 /* If this word wasn't an assignment, next ones definitely
4268 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004269 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4270 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004271 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004272 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004273 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004274 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004275 command->assignment_cnt++;
4276 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4277 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004278 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4279 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004280 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004281 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4282 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004283 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004284 }
Eric Andersen25f27032001-04-26 23:22:31 +00004285
Denis Vlasenko06810332007-05-21 23:30:54 +00004286#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004287 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004288 if (ctx->word.has_quoted_part
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02004289 || endofname(command->argv[0])[0] != '\0'
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004290 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004291 /* bash says just "not a valid identifier" */
Denys Vlasenko457825f2021-06-06 12:07:11 +02004292 syntax_error("bad variable name in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004293 return 1;
4294 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004295 /* Force FOR to have just one word (variable name) */
4296 /* NB: basically, this makes hush see "for v in ..."
4297 * syntax as if it is "for v; in ...". FOR and IN become
4298 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004299 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004300 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004301#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004302#if ENABLE_HUSH_CASE
4303 /* Force CASE to have just one word */
4304 if (ctx->ctx_res_w == RES_CASE) {
4305 done_pipe(ctx, PIPE_SEQ);
4306 }
4307#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004308
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004309 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004310
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004311 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004312 return 0;
4313}
4314
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004315
4316/* Peek ahead in the input to find out if we have a "&n" construct,
4317 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004318 * Return:
4319 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4320 * REDIRFD_SYNTAX_ERR if syntax error,
4321 * REDIRFD_TO_FILE if no & was seen,
4322 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004323 */
4324#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004325#define parse_redir_right_fd(as_string, input) \
4326 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004327#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004328static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004329{
4330 int ch, d, ok;
4331
4332 ch = i_peek(input);
4333 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004334 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004335
4336 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004337 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004338 ch = i_peek(input);
4339 if (ch == '-') {
4340 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004341 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004342 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004343 }
4344 d = 0;
4345 ok = 0;
4346 while (ch != EOF && isdigit(ch)) {
4347 d = d*10 + (ch-'0');
4348 ok = 1;
4349 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004350 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004351 ch = i_peek(input);
4352 }
4353 if (ok) return d;
4354
4355//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4356
James Byrne69374872019-07-02 11:35:03 +02004357 bb_simple_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004358 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004359}
4360
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004361/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004362 */
4363static int parse_redirect(struct parse_context *ctx,
4364 int fd,
4365 redir_type style,
4366 struct in_str *input)
4367{
4368 struct command *command = ctx->command;
4369 struct redir_struct *redir;
4370 struct redir_struct **redirp;
4371 int dup_num;
4372
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004373 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004374 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004375 /* Check for a '>&1' type redirect */
4376 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4377 if (dup_num == REDIRFD_SYNTAX_ERR)
4378 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004379 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004380 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004381 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004382 if (dup_num) { /* <<-... */
4383 ch = i_getch(input);
4384 nommu_addchr(&ctx->as_string, ch);
4385 ch = i_peek(input);
4386 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004387 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004388
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004389 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004390 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004391 if (ch == '|') {
4392 /* >|FILE redirect ("clobbering" >).
4393 * Since we do not support "set -o noclobber" yet,
4394 * >| and > are the same for now. Just eat |.
4395 */
4396 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004397 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004398 }
4399 }
4400
4401 /* Create a new redir_struct and append it to the linked list */
4402 redirp = &command->redirects;
4403 while ((redir = *redirp) != NULL) {
4404 redirp = &(redir->next);
4405 }
4406 *redirp = redir = xzalloc(sizeof(*redir));
4407 /* redir->next = NULL; */
4408 /* redir->rd_filename = NULL; */
4409 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004410 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004411
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004412 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4413 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004414
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004415 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004416 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004417 /* Erik had a check here that the file descriptor in question
4418 * is legit; I postpone that to "run time"
4419 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004420 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4421 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004422 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004423#if 0 /* Instead we emit error message at run time */
4424 if (ctx->pending_redirect) {
4425 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004426 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004427 }
4428#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004429 /* Set ctx->pending_redirect, so we know what to do at the
4430 * end of the next parsed word. */
4431 ctx->pending_redirect = redir;
4432 }
4433 return 0;
4434}
4435
Eric Andersen25f27032001-04-26 23:22:31 +00004436/* If a redirect is immediately preceded by a number, that number is
4437 * supposed to tell which file descriptor to redirect. This routine
4438 * looks for such preceding numbers. In an ideal world this routine
4439 * needs to handle all the following classes of redirects...
4440 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4441 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4442 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4443 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004444 *
4445 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4446 * "2.7 Redirection
4447 * ... If n is quoted, the number shall not be recognized as part of
4448 * the redirection expression. For example:
4449 * echo \2>a
4450 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004451 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004452 *
4453 * A -1 return means no valid number was found,
4454 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004455 */
4456static int redirect_opt_num(o_string *o)
4457{
4458 int num;
4459
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004460 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004461 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004462 num = bb_strtou(o->data, NULL, 10);
4463 if (errno || num < 0)
4464 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004465 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004466 return num;
4467}
4468
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004469#if BB_MMU
4470#define fetch_till_str(as_string, input, word, skip_tabs) \
4471 fetch_till_str(input, word, skip_tabs)
4472#endif
4473static char *fetch_till_str(o_string *as_string,
4474 struct in_str *input,
4475 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004476 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004477{
4478 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004479 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004480 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004481 int ch;
4482
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004483 /* Starting with "" is necessary for this case:
4484 * cat <<EOF
4485 *
4486 * xxx
4487 * EOF
4488 */
4489 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4490
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004491 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004492
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004493 while (1) {
4494 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004495 if (ch != EOF)
4496 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004497 if (ch == '\n' || ch == EOF) {
4498 check_heredoc_end:
4499 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004500 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004501 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4502 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004503 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004504 return heredoc.data;
4505 }
4506 if (ch == '\n') {
4507 /* This is a new line.
4508 * Remember position and backslash-escaping status.
4509 */
4510 o_addchr(&heredoc, ch);
4511 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004512 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004513 past_EOL = heredoc.length;
4514 /* Get 1st char of next line, possibly skipping leading tabs */
4515 do {
4516 ch = i_getch(input);
4517 if (ch != EOF)
4518 nommu_addchr(as_string, ch);
4519 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4520 /* If this immediately ended the line,
4521 * go back to end-of-line checks.
4522 */
4523 if (ch == '\n')
4524 goto check_heredoc_end;
4525 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004526 } else {
4527 /* Backslash-line continuation in an unquoted
4528 * heredoc. This does not need special handling
4529 * for heredoc body (unquoted heredocs are
4530 * expanded on "execution" and that would take
4531 * care of this case too), but not the case
4532 * of line continuation *in terminator*:
4533 * cat <<EOF
4534 * Ok1
4535 * EO\
4536 * F
4537 */
4538 heredoc.data[--heredoc.length] = '\0';
4539 prev = 0; /* not '\' */
4540 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004541 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004542 }
4543 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004544 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004545 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004546 }
4547 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004548 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004549 if (prev == '\\' && ch == '\\')
4550 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004551 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004552 else
4553 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004554 }
4555}
4556
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004557/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4558 * and load them all. There should be exactly heredoc_cnt of them.
4559 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004560#if BB_MMU
4561#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4562 fetch_heredocs(pi, heredoc_cnt, input)
4563#endif
4564static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004565{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004566 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004567 int i;
4568 struct command *cmd = pi->cmds;
4569
Denys Vlasenko3675c372018-07-23 16:31:21 +02004570 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004571 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004572 cmd->argv ? cmd->argv[0] : "NONE"
4573 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004574 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004575 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004576
Denys Vlasenko3675c372018-07-23 16:31:21 +02004577 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004578 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004579 while (redir) {
4580 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004581 char *p;
4582
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004583 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004584 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004585 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004586 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004587 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004588 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004589 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004590 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004591 free(redir->rd_filename);
4592 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004593 heredoc_cnt--;
4594 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004595 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004596 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004597 if (cmd->group) {
4598 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4599 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4600 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4601 if (heredoc_cnt < 0)
4602 return heredoc_cnt; /* error */
4603 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004604 cmd++;
4605 }
4606 pi = pi->next;
4607 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004608 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004609}
4610
4611
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004612static int run_list(struct pipe *pi);
4613#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004614#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4615 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004616#endif
4617static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004618 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004619 struct in_str *input,
4620 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004621
Denys Vlasenko474cb202018-07-24 13:03:03 +02004622/* Returns number of heredocs not yet consumed,
4623 * or -1 on error.
4624 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004625static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004626 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004627{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004628 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004629 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004630 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004631#if BB_MMU
4632# define as_string NULL
4633#else
4634 char *as_string = NULL;
4635#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004636 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004637 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004638 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004639 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004640
4641 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004642#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004643 if (ch == '(' && !ctx->word.has_quoted_part) {
4644 if (ctx->word.length)
4645 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004646 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004647 if (!command->argv)
4648 goto skip; /* (... */
4649 if (command->argv[1]) { /* word word ... (... */
4650 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004651 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004652 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004653 /* it is "word(..." or "word (..." */
4654 do
4655 ch = i_getch(input);
4656 while (ch == ' ' || ch == '\t');
4657 if (ch != ')') {
4658 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004659 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004660 }
4661 nommu_addchr(&ctx->as_string, ch);
4662 do
4663 ch = i_getch(input);
4664 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004665 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004666 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004667 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004668 }
4669 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004670 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004671 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004672 }
4673#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004674
4675#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004676 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004677 || ctx->word.length /* word{... */
4678 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004679 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004680 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004681 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004682 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004683 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004684 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004685#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004686
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004687 IF_HUSH_FUNCTIONS(skip:)
4688
Denis Vlasenko240c2552009-04-03 03:45:05 +00004689 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004690 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004691 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004692 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4693 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004694 } else {
4695 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004696 ch = i_peek(input);
4697 if (ch != ' ' && ch != '\t' && ch != '\n'
4698 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4699 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004700 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004701 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004702 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004703 if (ch != '(') {
4704 ch = i_getch(input);
4705 nommu_addchr(&ctx->as_string, ch);
4706 }
Eric Andersen25f27032001-04-26 23:22:31 +00004707 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004708
Denys Vlasenko474cb202018-07-24 13:03:03 +02004709 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4710 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4711 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004712#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004713 if (as_string)
4714 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004715#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004716
4717 /* empty ()/{} or parse error? */
4718 if (!pipe_list || pipe_list == ERR_PTR) {
4719 /* parse_stream already emitted error msg */
4720 if (!BB_MMU)
4721 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004722 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004723 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004724 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004725 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004726#if !BB_MMU
4727 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4728 command->group_as_string = as_string;
4729 debug_printf_parse("end of group, remembering as:'%s'\n",
4730 command->group_as_string);
4731#endif
4732
4733#if ENABLE_HUSH_FUNCTIONS
4734 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4735 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4736 struct command *cmd2;
4737
4738 cmd2 = xzalloc(sizeof(*cmd2));
4739 cmd2->cmd_type = CMD_SUBSHELL;
4740 cmd2->group = pipe_list;
4741# if !BB_MMU
4742//UNTESTED!
4743 cmd2->group_as_string = command->group_as_string;
4744 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4745# endif
4746
4747 pipe_list = new_pipe();
4748 pipe_list->cmds = cmd2;
4749 pipe_list->num_cmds = 1;
4750 }
4751#endif
4752
4753 command->group = pipe_list;
4754
Denys Vlasenko474cb202018-07-24 13:03:03 +02004755 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4756 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004757 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004758#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004759}
4760
Denys Vlasenko0b883582016-12-23 16:49:07 +01004761#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004762/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004763/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004764static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004765{
4766 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004767 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004768 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004769 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004770 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004771 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004772 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004773 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004774 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004775 }
4776}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004777static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4778{
4779 while (1) {
4780 int ch = i_getch(input);
4781 if (ch == EOF) {
4782 syntax_error_unterm_ch('\'');
4783 return 0;
4784 }
4785 if (ch == '\'')
4786 return 1;
4787 o_addqchr(dest, ch);
4788 }
4789}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004790/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004791static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004792static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004793{
4794 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004795 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004796 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004797 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004798 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004799 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004800 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004801 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004802 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004803 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004804 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004805 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004806 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004807 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004808 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4809 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004810 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004811 continue;
4812 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004813 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004814 }
4815}
4816/* Process `cmd` - copy contents until "`" is seen. Complicated by
4817 * \` quoting.
4818 * "Within the backquoted style of command substitution, backslash
4819 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4820 * The search for the matching backquote shall be satisfied by the first
4821 * backquote found without a preceding backslash; during this search,
4822 * if a non-escaped backquote is encountered within a shell comment,
4823 * a here-document, an embedded command substitution of the $(command)
4824 * form, or a quoted string, undefined results occur. A single-quoted
4825 * or double-quoted string that begins, but does not end, within the
4826 * "`...`" sequence produces undefined results."
4827 * Example Output
4828 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4829 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004830static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004831{
4832 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004833 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004834 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004835 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004836 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004837 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4838 ch = i_getch(input);
4839 if (ch != '`'
4840 && ch != '$'
4841 && ch != '\\'
4842 && (!in_dquote || ch != '"')
4843 ) {
4844 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004845 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004846 }
4847 if (ch == EOF) {
4848 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004849 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004850 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004851 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004852 }
4853}
4854/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4855 * quoting and nested ()s.
4856 * "With the $(command) style of command substitution, all characters
4857 * following the open parenthesis to the matching closing parenthesis
4858 * constitute the command. Any valid shell script can be used for command,
4859 * except a script consisting solely of redirections which produces
4860 * unspecified results."
4861 * Example Output
4862 * echo $(echo '(TEST)' BEST) (TEST) BEST
4863 * echo $(echo 'TEST)' BEST) TEST) BEST
4864 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004865 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004866 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004867 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004868 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4869 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004870 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004871#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004872static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004873{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004874 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004875 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004876# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004877 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004878# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004879 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4880
Denys Vlasenko259747c2019-11-28 10:28:14 +01004881# if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004882 G.promptmode = 1; /* PS2 */
Denys Vlasenko259747c2019-11-28 10:28:14 +01004883# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004884 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4885
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004886 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004887 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004888 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004889 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004890 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004891 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004892 if (ch == end_ch
4893# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004894 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004895# endif
4896 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004897 if (!dbl)
4898 break;
4899 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004900 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004901 i_getch(input); /* eat second ')' */
4902 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004903 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004904 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004905 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004906 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004907 if (ch == '(' || ch == '{') {
4908 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004909 if (!add_till_closing_bracket(dest, input, ch))
4910 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004911 o_addchr(dest, ch);
4912 continue;
4913 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004914 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004915 if (!add_till_single_quote(dest, input))
4916 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004917 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004918 continue;
4919 }
4920 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004921 if (!add_till_double_quote(dest, input))
4922 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004923 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004924 continue;
4925 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004926 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004927 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4928 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004929 o_addchr(dest, ch);
4930 continue;
4931 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004932 if (ch == '\\') {
4933 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004934 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004935 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004936 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004937 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004938 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004939# if 0
Denys Vlasenko657086a2016-09-29 18:07:42 +02004940 if (ch == '\n') {
4941 /* "backslash+newline", ignore both */
4942 o_delchr(dest); /* undo insertion of '\' */
4943 continue;
4944 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004945# endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004946 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004947 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004948 continue;
4949 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004950 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004951 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004952 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004953}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004954#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004955
Denys Vlasenkob278d822021-07-26 15:29:13 +02004956#if BASH_DOLLAR_SQUOTE
4957/* Return code: 1 for "found and parsed", 0 for "seen something else" */
Denys Vlasenko8dd676c2021-07-27 04:09:45 +02004958# if BB_MMU
Denys Vlasenkob278d822021-07-26 15:29:13 +02004959#define parse_dollar_squote(as_string, dest, input) \
4960 parse_dollar_squote(dest, input)
4961#define as_string NULL
Denys Vlasenko8dd676c2021-07-27 04:09:45 +02004962# endif
Denys Vlasenkob278d822021-07-26 15:29:13 +02004963static int parse_dollar_squote(o_string *as_string, o_string *dest, struct in_str *input)
4964{
4965 int start;
4966 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4967 debug_printf_parse("parse_dollar_squote entered: ch='%c'\n", ch);
4968 if (ch != '\'')
4969 return 0;
4970
4971 dest->has_quoted_part = 1;
4972 start = dest->length;
4973
4974 ch = i_getch(input); /* eat ' */
4975 nommu_addchr(as_string, ch);
4976 while (1) {
4977 ch = i_getch(input);
4978 nommu_addchr(as_string, ch);
4979 if (ch == EOF) {
4980 syntax_error_unterm_ch('\'');
4981 return 0;
4982 }
4983 if (ch == '\'')
4984 break;
4985 if (ch == SPECIAL_VAR_SYMBOL) {
4986 /* Convert raw ^C to corresponding special variable reference */
4987 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4988 o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
4989 /* will addchr() another SPECIAL_VAR_SYMBOL (see after the if() block) */
4990 } else if (ch == '\\') {
4991 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
4992
4993 ch = i_getch(input);
4994 nommu_addchr(as_string, ch);
4995 if (strchr(C_escapes, ch)) {
4996 char buf[4];
4997 char *p = buf;
4998 int cnt = 2;
4999
5000 buf[0] = ch;
5001 if ((unsigned char)(ch - '0') <= 7) { /* \ooo */
5002 do {
5003 ch = i_peek(input);
5004 if ((unsigned char)(ch - '0') > 7)
5005 break;
5006 *++p = ch = i_getch(input);
5007 nommu_addchr(as_string, ch);
5008 } while (--cnt != 0);
5009 } else if (ch == 'x') { /* \xHH */
5010 do {
5011 ch = i_peek(input);
5012 if (!isxdigit(ch))
5013 break;
5014 *++p = ch = i_getch(input);
5015 nommu_addchr(as_string, ch);
5016 } while (--cnt != 0);
5017 if (cnt == 2) { /* \x but next char is "bad" */
5018 ch = 'x';
5019 goto unrecognized;
5020 }
5021 } /* else simple seq like \\ or \t */
5022 *++p = '\0';
5023 p = buf;
5024 ch = bb_process_escape_sequence((void*)&p);
5025 //bb_error_msg("buf:'%s' ch:%x", buf, ch);
5026 if (ch == '\0')
5027 continue; /* bash compat: $'...\0...' emits nothing */
5028 } else { /* unrecognized "\z": encode both chars unless ' or " */
5029 if (ch != '\'' && ch != '"') {
5030 unrecognized:
5031 o_addqchr(dest, '\\');
5032 }
5033 }
5034 } /* if (\...) */
5035 o_addqchr(dest, ch);
5036 }
5037
5038 if (dest->length == start) {
5039 /* $'', $'\0', $'\000\x00' and the like */
5040 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5041 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5042 }
5043
5044 return 1;
Denys Vlasenko8dd676c2021-07-27 04:09:45 +02005045# undef as_string
Denys Vlasenkob278d822021-07-26 15:29:13 +02005046}
5047#else
Denys Vlasenko21afdde2021-08-15 20:08:53 +02005048# define parse_dollar_squote(as_string, dest, input) 0
Denys Vlasenkob278d822021-07-26 15:29:13 +02005049#endif /* BASH_DOLLAR_SQUOTE */
5050
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005051/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005052#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005053#define parse_dollar(as_string, dest, input, quote_mask) \
5054 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005055#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005056#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005057static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005058 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005059 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00005060{
Denys Vlasenko657086a2016-09-29 18:07:42 +02005061 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005062
Denys Vlasenkob278d822021-07-26 15:29:13 +02005063 debug_printf_parse("parse_dollar entered: ch='%c' quote_mask:0x%x\n", ch, quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005064 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005065 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005066 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005067 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005068 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005069 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005070 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005071 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005072 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005073 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02005074 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02005075 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02005076 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005077 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02005078 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005079 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005080 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005081 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005082 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005083 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005084 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005085 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005086 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005087 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005088 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005089 o_addchr(dest, ch | quote_mask);
5090 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005091 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005092 case '$': /* pid */
5093 case '!': /* last bg pid */
5094 case '?': /* last exit code */
5095 case '#': /* number of args */
5096 case '*': /* args */
5097 case '@': /* args */
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005098 case '-': /* $- option flags set by set builtin or shell options (-i etc) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005099 goto make_one_char_var;
5100 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005101 char len_single_ch;
5102
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005103 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5104
Denys Vlasenko74369502010-05-21 19:52:01 +02005105 ch = i_getch(input); /* eat '{' */
5106 nommu_addchr(as_string, ch);
5107
Denys Vlasenko46e64982016-09-29 19:50:55 +02005108 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02005109 /* It should be ${?}, or ${#var},
5110 * or even ${?+subst} - operator acting on a special variable,
5111 * or the beginning of variable name.
5112 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005113 if (ch == EOF
5114 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
5115 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02005116 bad_dollar_syntax:
5117 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005118 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
5119 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02005120 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005121 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005122 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02005123 ch |= quote_mask;
5124
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005125 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02005126 * However, this regresses some of our testsuite cases
5127 * which check invalid constructs like ${%}.
5128 * Oh well... let's check that the var name part is fine... */
5129
Denys Vlasenko97c3b5e2021-06-19 15:28:10 +02005130 if (isdigit(len_single_ch)
5131 || (len_single_ch == '#' && isdigit(i_peek_and_eat_bkslash_nl(input)))
5132 ) {
5133 /* Execution engine uses plain xatoi_positive()
5134 * to interpret ${NNN} and {#NNN},
5135 * check syntax here in the parser.
5136 * (bash does not support expressions in ${#NN},
5137 * e.g. ${#$var} and {#1:+WORD} are not supported).
5138 */
5139 unsigned cnt = 9; /* max 9 digits for ${NN} and 8 for {#NN} */
5140 while (1) {
5141 o_addchr(dest, ch);
5142 debug_printf_parse(": '%c'\n", ch);
5143 ch = i_getch_and_eat_bkslash_nl(input);
5144 nommu_addchr(as_string, ch);
5145 if (ch == '}')
5146 break;
5147 if (--cnt == 0)
5148 goto bad_dollar_syntax;
5149 if (len_single_ch != '#' && strchr(VAR_SUBST_OPS, ch))
5150 /* ${NN<op>...} is valid */
5151 goto eat_until_closing;
5152 if (!isdigit(ch))
5153 goto bad_dollar_syntax;
5154 }
5155 } else
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005156 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005157 unsigned pos;
5158
Denys Vlasenko74369502010-05-21 19:52:01 +02005159 o_addchr(dest, ch);
5160 debug_printf_parse(": '%c'\n", ch);
5161
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005162 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005163 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02005164 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00005165 break;
Denys Vlasenko74369502010-05-21 19:52:01 +02005166 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005167 unsigned end_ch;
5168 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005169 /* handle parameter expansions
5170 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5171 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005172 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
5173 if (len_single_ch != '#'
5174 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
5175 || i_peek(input) != '}'
5176 ) {
5177 goto bad_dollar_syntax;
5178 }
5179 /* else: it's "length of C" ${#C} op,
5180 * where C is a single char
5181 * special var name, e.g. ${#!}.
5182 */
5183 }
Denys Vlasenko97c3b5e2021-06-19 15:28:10 +02005184 eat_until_closing:
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005185 /* Eat everything until closing '}' (or ':') */
5186 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005187 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005188 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005189 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005190 ) {
5191 /* It's ${var:N[:M]} thing */
5192 end_ch = '}' * 0x100 + ':';
5193 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005194 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005195 && ch == '/'
5196 ) {
5197 /* It's ${var/[/]pattern[/repl]} thing */
5198 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
5199 i_getch(input);
5200 nommu_addchr(as_string, '/');
5201 ch = '\\';
5202 }
5203 end_ch = '}' * 0x100 + '/';
5204 }
5205 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02005206 /* The pattern can't be empty.
5207 * IOW: if the first char after "${v//" is a slash,
5208 * it does not terminate the pattern - it's the first char of the pattern:
5209 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
5210 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
5211 */
5212 if (i_peek(input) == '/') {
5213 o_addchr(dest, i_getch(input));
5214 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005215 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005216 if (!BB_MMU)
5217 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005218#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005219 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005220 if (last_ch == 0) /* error? */
5221 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005222#else
Denys Vlasenko259747c2019-11-28 10:28:14 +01005223# error Simple code to only allow ${var} is not implemented
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005224#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005225 if (as_string) {
5226 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005227 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005228 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005229
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005230 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5231 && (end_ch & 0xff00)
5232 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005233 /* close the first block: */
5234 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005235 /* while parsing N from ${var:N[:M]}
5236 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005237 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005238 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005239 end_ch = '}';
5240 goto again;
5241 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005242 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005243 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005244 /* it's ${var:N} - emulate :999999999 */
5245 o_addstr(dest, "999999999");
5246 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005247 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005248 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005249 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005250 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005251 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005252 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5253 break;
5254 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005255#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005256 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005257 unsigned pos;
5258
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005259 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005260 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005261# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005262 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005263 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005264 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005265 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01005266 o_addchr(dest, quote_mask | '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005267 if (!BB_MMU)
5268 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005269 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5270 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005271 if (as_string) {
5272 o_addstr(as_string, dest->data + pos);
5273 o_addchr(as_string, ')');
5274 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005275 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005276 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005277 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005278 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005279# endif
5280# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005281 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5282 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005283 if (!BB_MMU)
5284 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005285 if (!add_till_closing_bracket(dest, input, ')'))
5286 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005287 if (as_string) {
5288 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005289 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005290 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005291 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005292# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005293 break;
5294 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005295#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005296 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005297 goto make_var;
5298#if 0
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005299 /* TODO: $_: */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005300 /* $_ Shell or shell script name; or last argument of last command
5301 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5302 * but in command's env, set to full pathname used to invoke it */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005303 ch = i_getch(input);
5304 nommu_addchr(as_string, ch);
5305 ch = i_peek_and_eat_bkslash_nl(input);
5306 if (isalnum(ch)) { /* it's $_name or $_123 */
5307 ch = '_';
5308 goto make_var1;
5309 }
5310 /* else: it's $_ */
5311#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005312 default:
5313 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005314 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005315 debug_printf_parse("parse_dollar return 1 (ok)\n");
5316 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005317#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005318}
5319
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005320#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005321#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005322 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005323#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005324#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005325static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005326 o_string *dest,
5327 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005328 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005329{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005330 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005331 int next;
5332
5333 again:
5334 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005335 if (ch != EOF)
5336 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005337 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005338 debug_printf_parse("encode_string return 1 (ok)\n");
5339 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005340 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005341 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005342 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005343 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005344 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005345 }
5346 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005347 if (ch != '\n') {
5348 next = i_peek(input);
5349 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005350 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005351 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005352 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005353 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005354 /* Testcase: in interactive shell a file with
5355 * echo "unterminated string\<eof>
5356 * is sourced.
5357 */
5358 syntax_error_unterm_ch('"');
5359 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005360 }
5361 /* bash:
5362 * "The backslash retains its special meaning [in "..."]
5363 * only when followed by one of the following characters:
5364 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005365 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005366 * NB: in (unquoted) heredoc, above does not apply to ",
5367 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005368 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005369 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005370 ch = i_getch(input); /* eat next */
5371 if (ch == '\n')
5372 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005373 } /* else: ch remains == '\\', and we double it below: */
5374 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005375 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005376 goto again;
5377 }
5378 if (ch == '$') {
Denys Vlasenkob278d822021-07-26 15:29:13 +02005379 //if (parse_dollar_squote(as_string, dest, input))
5380 // goto again;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005381 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5382 debug_printf_parse("encode_string return 0: "
5383 "parse_dollar returned 0 (error)\n");
5384 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005385 }
5386 goto again;
5387 }
5388#if ENABLE_HUSH_TICK
5389 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005390 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005391 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5392 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005393 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5394 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005395 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5396 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005397 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005398 }
5399#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005400 o_addQchr(dest, ch);
Denys Vlasenko1b7a9b62021-06-15 16:05:57 +02005401 if (ch == SPECIAL_VAR_SYMBOL) {
5402 /* Convert "^C" to corresponding special variable reference */
5403 o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
5404 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5405 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005406 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005407#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005408}
5409
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005410/*
5411 * Scan input until EOF or end_trigger char.
5412 * Return a list of pipes to execute, or NULL on EOF
5413 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005414 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005415 * reset parsing machinery and start parsing anew,
5416 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005417 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005418static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005419 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005420 struct in_str *input,
5421 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005422{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005423 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005424 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005425
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005426 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005427 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005428 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005429 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005430 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005431 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005432
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005433 initialize_context(&ctx);
5434
5435 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5436 * Preventing this:
5437 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005438 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005439
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005440 /* We used to separate words on $IFS here. This was wrong.
5441 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005442 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005443 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005444
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005445 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005446 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005447 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005448 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005449 int ch;
5450 int next;
5451 int redir_fd;
5452 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005453
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005454 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005455 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005456 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005457 if (ch == EOF) {
5458 struct pipe *pi;
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01005459
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005460 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005461 syntax_error_unterm_str("here document");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005462 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005463 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005464 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005465 syntax_error_unterm_ch('(');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005466 goto parse_error_exitcode1;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005467 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005468 if (end_trigger == '}') {
5469 syntax_error_unterm_ch('{');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005470 goto parse_error_exitcode1;
Denys Vlasenko42246472016-11-07 16:22:35 +01005471 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005472
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005473 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005474 goto parse_error_exitcode1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005475 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005476 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005477 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005478 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005479 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005480 /* (this makes bare "&" cmd a no-op.
5481 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005482 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005483 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005484 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005485 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005486 pi = NULL;
5487 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005488#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005489 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005490 if (pstring)
5491 *pstring = ctx.as_string.data;
5492 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005493 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005494#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005495 // heredoc_cnt must be 0 here anyway
5496 //if (heredoc_cnt_ptr)
5497 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005498 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005499 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005500 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005501 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005502 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005503
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005504 /* Handle "'" and "\" first, as they won't play nice with
5505 * i_peek_and_eat_bkslash_nl() anyway:
5506 * echo z\\
5507 * and
5508 * echo '\
5509 * '
5510 * would break.
5511 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005512 if (ch == '\\') {
5513 ch = i_getch(input);
5514 if (ch == '\n')
5515 continue; /* drop \<newline>, get next char */
5516 nommu_addchr(&ctx.as_string, '\\');
Denys Vlasenko1b7a9b62021-06-15 16:05:57 +02005517 if (ch == SPECIAL_VAR_SYMBOL) {
5518 nommu_addchr(&ctx.as_string, ch);
5519 /* Convert \^C to corresponding special variable reference */
5520 goto case_SPECIAL_VAR_SYMBOL;
5521 }
Denys Vlasenkof693b602018-04-11 20:00:43 +02005522 o_addchr(&ctx.word, '\\');
5523 if (ch == EOF) {
5524 /* Testcase: eval 'echo Ok\' */
5525 /* bash-4.3.43 was removing backslash,
5526 * but 4.4.19 retains it, most other shells too
5527 */
5528 continue; /* get next char */
5529 }
5530 /* Example: echo Hello \2>file
5531 * we need to know that word 2 is quoted
5532 */
5533 ctx.word.has_quoted_part = 1;
5534 nommu_addchr(&ctx.as_string, ch);
5535 o_addchr(&ctx.word, ch);
5536 continue; /* get next char */
5537 }
5538 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005539 if (ch == '\'') {
5540 ctx.word.has_quoted_part = 1;
5541 next = i_getch(input);
5542 if (next == '\'' && !ctx.pending_redirect)
5543 goto insert_empty_quoted_str_marker;
5544
5545 ch = next;
5546 while (1) {
5547 if (ch == EOF) {
5548 syntax_error_unterm_ch('\'');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005549 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005550 }
5551 nommu_addchr(&ctx.as_string, ch);
5552 if (ch == '\'')
5553 break;
5554 if (ch == SPECIAL_VAR_SYMBOL) {
5555 /* Convert raw ^C to corresponding special variable reference */
5556 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5557 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5558 }
5559 o_addqchr(&ctx.word, ch);
5560 ch = i_getch(input);
5561 }
5562 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005563 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005564
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005565 next = '\0';
5566 if (ch != '\n')
5567 next = i_peek_and_eat_bkslash_nl(input);
5568
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005569 is_special = "{}<>&|();#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005570 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005571 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005572#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
5573 if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
5574 /* In [[ ]], {}<>&|() are not special */
5575 is_special += 8;
5576 } else
5577#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005578 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005579 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005580 || ctx.word.length /* word{... - non-special */
5581 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005582 || (next != ';' /* }; - special */
5583 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005584 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005585 && next != '&' /* }& and }&& ... - special */
5586 && next != '|' /* }|| ... - special */
5587 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005588 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005589 ) {
5590 /* They are not special, skip "{}" */
5591 is_special += 2;
5592 }
5593 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005594 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005595
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005596 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005597 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005598 o_addQchr(&ctx.word, ch);
5599 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5600 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005601 && ch == '='
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02005602 && endofname(ctx.word.data)[0] == '='
Denis Vlasenko55789c62008-06-18 16:30:42 +00005603 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005604 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5605 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005606 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005607 continue;
5608 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005609
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005610 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005611#if ENABLE_HUSH_LINENO_VAR
5612/* Case:
5613 * "while ...; do<whitespace><newline>
5614 * cmd ..."
5615 * would think that "cmd" starts in <whitespace> -
5616 * i.e., at the previous line.
5617 * We need to skip all whitespace before newlines.
5618 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005619 while (ch != '\n') {
5620 next = i_peek(input);
5621 if (next != ' ' && next != '\t' && next != '\n')
5622 break; /* next char is not ws */
5623 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005624 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005625 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005626#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005627 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005628 goto parse_error_exitcode1;
Eric Andersenaac75e52001-04-30 18:18:45 +00005629 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005630 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005631 /* Is this a case when newline is simply ignored?
5632 * Some examples:
5633 * "cmd | <newline> cmd ..."
5634 * "case ... in <newline> word) ..."
5635 */
5636 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005637 && ctx.word.length == 0
5638 && !ctx.word.has_quoted_part
5639 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005640 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005641 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005642 * Without check #1, interactive shell
5643 * ignores even bare <newline>,
5644 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005645 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005646 * ps2> _ <=== wrong, should be ps1
5647 * Without check #2, "cmd & <newline>"
5648 * is similarly mistreated.
5649 * (BTW, this makes "cmd & cmd"
5650 * and "cmd && cmd" non-orthogonal.
5651 * Really, ask yourself, why
5652 * "cmd && <newline>" doesn't start
5653 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005654 * The only reason is that it might be
5655 * a "cmd1 && <nl> cmd2 &" construct,
5656 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005657 */
5658 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005659 if (pi->num_cmds != 0 /* check #1 */
5660 && pi->followup != PIPE_BG /* check #2 */
5661 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005662 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005663 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005664 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005665 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005666 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005667 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005668 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005669 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5670 if (heredoc_cnt != 0)
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005671 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005672 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005673 ctx.is_assignment = MAYBE_ASSIGNMENT;
5674 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005675 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005676 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005677 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005678 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005679 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005680
5681 /* "cmd}" or "cmd }..." without semicolon or &:
5682 * } is an ordinary char in this case, even inside { cmd; }
5683 * Pathological example: { ""}; } should exec "}" cmd
5684 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005685 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005686 if (ctx.word.length != 0 /* word} */
5687 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005688 ) {
5689 goto ordinary_char;
5690 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005691 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5692 /* Generally, there should be semicolon: "cmd; }"
5693 * However, bash allows to omit it if "cmd" is
5694 * a group. Examples:
5695 * { { echo 1; } }
5696 * {(echo 1)}
5697 * { echo 0 >&2 | { echo 1; } }
5698 * { while false; do :; done }
5699 * { case a in b) ;; esac }
5700 */
5701 if (ctx.command->group)
5702 goto term_group;
5703 goto ordinary_char;
5704 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005705 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005706 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005707 goto skip_end_trigger;
5708 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005709 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005710 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005711 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005712 && (ch != ';' || heredoc_cnt == 0)
5713#if ENABLE_HUSH_CASE
5714 && (ch != ')'
5715 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005716 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005717 )
5718#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005719 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005720 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005721 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005722 }
5723 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005724 ctx.is_assignment = MAYBE_ASSIGNMENT;
5725 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005726 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005727 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005728 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005729 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005730 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005731#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005732 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005733 if (pstring)
5734 *pstring = ctx.as_string.data;
5735 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005736 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005737#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005738 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5739 /* Example: bare "{ }", "()" */
5740 G.last_exitcode = 2; /* bash compat */
5741 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005742 goto parse_error;
Denys Vlasenko39701202017-08-02 19:44:05 +02005743 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005744 if (heredoc_cnt_ptr)
5745 *heredoc_cnt_ptr = heredoc_cnt;
5746 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005747 debug_printf_parse("parse_stream return %p: "
5748 "end_trigger char found\n",
5749 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005750 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005751 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005752 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005753 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005754
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005755 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005756 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005757
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005758 /* Catch <, > before deciding whether this word is
5759 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5760 switch (ch) {
5761 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005762 redir_fd = redirect_opt_num(&ctx.word);
5763 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005764 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005765 }
5766 redir_style = REDIRECT_OVERWRITE;
5767 if (next == '>') {
5768 redir_style = REDIRECT_APPEND;
5769 ch = i_getch(input);
5770 nommu_addchr(&ctx.as_string, ch);
5771 }
5772#if 0
5773 else if (next == '(') {
5774 syntax_error(">(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005775 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005776 }
5777#endif
5778 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005779 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005780 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005781 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005782 redir_fd = redirect_opt_num(&ctx.word);
5783 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005784 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005785 }
5786 redir_style = REDIRECT_INPUT;
5787 if (next == '<') {
5788 redir_style = REDIRECT_HEREDOC;
5789 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005790 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005791 ch = i_getch(input);
5792 nommu_addchr(&ctx.as_string, ch);
5793 } else if (next == '>') {
5794 redir_style = REDIRECT_IO;
5795 ch = i_getch(input);
5796 nommu_addchr(&ctx.as_string, ch);
5797 }
5798#if 0
5799 else if (next == '(') {
5800 syntax_error("<(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005801 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005802 }
5803#endif
5804 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005805 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005806 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005807 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005808 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005809 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005810 /* note: we do not add it to &ctx.as_string */
5811/* TODO: in bash:
5812 * comment inside $() goes to the next \n, even inside quoted string (!):
5813 * cmd "$(cmd2 #comment)" - syntax error
5814 * cmd "`cmd2 #comment`" - ok
5815 * We accept both (comment ends where command subst ends, in both cases).
5816 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005817 while (1) {
5818 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005819 if (ch == '\n') {
5820 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005821 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005822 }
5823 ch = i_getch(input);
5824 if (ch == EOF)
5825 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005826 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005827 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005828 }
5829 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005830 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005831 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005832
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005833 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005834 /* check that we are not in word in "a=1 2>word b=1": */
5835 && !ctx.pending_redirect
5836 ) {
5837 /* ch is a special char and thus this word
5838 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005839 ctx.is_assignment = NOT_ASSIGNMENT;
5840 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005841 }
5842
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005843 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5844
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005845 switch (ch) {
Denys Vlasenko1b7a9b62021-06-15 16:05:57 +02005846 case_SPECIAL_VAR_SYMBOL:
Denys Vlasenko932b9972018-01-11 12:39:48 +01005847 case SPECIAL_VAR_SYMBOL:
5848 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005849 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5850 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005851 /* fall through */
5852 case '#':
5853 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005854 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005855 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005856 case '$':
Denys Vlasenkob278d822021-07-26 15:29:13 +02005857 if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
5858 continue; /* get next char */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005859 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005860 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005861 "parse_dollar returned 0 (error)\n");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005862 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005863 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005864 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005865 case '"':
5866 ctx.word.has_quoted_part = 1;
5867 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005868 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005869 insert_empty_quoted_str_marker:
5870 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005871 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5872 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005873 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005874 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005875 if (ctx.is_assignment == NOT_ASSIGNMENT)
5876 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005877 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005878 goto parse_error_exitcode1;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005879 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005880 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005881#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005882 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005883 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005884
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005885 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5886 o_addchr(&ctx.word, '`');
5887 USE_FOR_NOMMU(pos = ctx.word.length;)
5888 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005889 goto parse_error_exitcode1;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005890# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005891 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005892 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005893# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005894 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5895 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005896 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005897 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005898#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005899 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005900#if ENABLE_HUSH_CASE
5901 case_semi:
5902#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005903 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005904 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005905 }
5906 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005907#if ENABLE_HUSH_CASE
5908 /* Eat multiple semicolons, detect
5909 * whether it means something special */
5910 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005911 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005912 if (ch != ';')
5913 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005914 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005915 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005916 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005917 ctx.ctx_dsemicolon = 1;
5918 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005919 break;
5920 }
5921 }
5922#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005923 new_cmd:
5924 /* We just finished a cmd. New one may start
5925 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005926 ctx.is_assignment = MAYBE_ASSIGNMENT;
5927 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005928 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005929 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005930 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005931 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005932 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005933 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005934 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005935 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005936 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005937 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005938 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005939 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005940 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005941 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005942 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005943 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005944 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005945#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005946 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005947 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005948#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005949 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005950 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005951 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005952 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005953 } else {
5954 /* we could pick up a file descriptor choice here
5955 * with redirect_opt_num(), but bash doesn't do it.
5956 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005957 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005958 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005959 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005960 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005961#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005962 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005963 if (ctx.ctx_res_w == RES_MATCH
5964 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005965 && ctx.word.length == 0 /* not word(... */
5966 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005967 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005968 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005969 }
5970#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005971 /* fall through */
5972 case '{': {
5973 int n = parse_group(&ctx, input, ch);
5974 if (n < 0) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005975 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005976 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005977 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5978 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005979 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005980 }
Eric Andersen25f27032001-04-26 23:22:31 +00005981 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005982#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005983 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005984 goto case_semi;
5985#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005986 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005987 /* proper use of this character is caught by end_trigger:
5988 * if we see {, we call parse_group(..., end_trigger='}')
5989 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005990 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005991 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005992 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005993 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005994 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005995 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005996 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005997 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005998
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005999 parse_error_exitcode1:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01006000 G.last_exitcode = 1;
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01006001 parse_error:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006002 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006003 struct parse_context *pctx;
6004 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006005
6006 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006007 * Sample for finding leaks on syntax error recovery path.
6008 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006009 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006010 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01006011 * while if (true | { true;}); then echo ok; fi; do break; done
6012 * 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 +00006013 */
6014 pctx = &ctx;
6015 do {
6016 /* Update pipe/command counts,
6017 * otherwise freeing may miss some */
6018 done_pipe(pctx, PIPE_SEQ);
6019 debug_printf_clean("freeing list %p from ctx %p\n",
6020 pctx->list_head, pctx);
6021 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006022 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006023 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006024#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02006025 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006026#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006027 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006028 if (pctx != &ctx) {
6029 free(pctx);
6030 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006031 IF_HAS_KEYWORDS(pctx = p2;)
6032 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006033
Denys Vlasenko474cb202018-07-24 13:03:03 +02006034 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006035#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006036 if (pstring)
6037 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006038#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006039 debug_leave();
6040 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006041 }
Eric Andersen25f27032001-04-26 23:22:31 +00006042}
6043
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006044
6045/*** Execution routines ***/
6046
6047/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02006048#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02006049#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006050 expand_string_to_string(str)
6051#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02006052static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006053#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006054static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006055#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006056static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006057
6058/* expand_strvec_to_strvec() takes a list of strings, expands
6059 * all variable references within and returns a pointer to
6060 * a list of expanded strings, possibly with larger number
6061 * of strings. (Think VAR="a b"; echo $VAR).
6062 * This new list is allocated as a single malloc block.
6063 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006064 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006065 * Caller can deallocate entire list by single free(list). */
6066
Denys Vlasenko238081f2010-10-03 14:26:26 +02006067/* A horde of its helpers come first: */
6068
6069static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
6070{
6071 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02006072 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02006073
Denys Vlasenko9e800222010-10-03 14:28:04 +02006074#if ENABLE_HUSH_BRACE_EXPANSION
6075 if (c == '{' || c == '}') {
6076 /* { -> \{, } -> \} */
6077 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02006078 /* And now we want to add { or } and continue:
6079 * o_addchr(o, c);
6080 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006081 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02006082 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02006083 }
6084#endif
6085 o_addchr(o, c);
6086 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02006087 /* \z -> \\\z; \<eol> -> \\<eol> */
6088 o_addchr(o, '\\');
6089 if (len) {
6090 len--;
6091 o_addchr(o, '\\');
6092 o_addchr(o, *str++);
6093 }
6094 }
6095 }
6096}
6097
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006098/* Store given string, finalizing the word and starting new one whenever
6099 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006100 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02006101 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006102 * 1 - ended with IFS char, else 0 (this includes case of empty str).
6103 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006104static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006105{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006106 int last_is_ifs = 0;
6107
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006108 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006109 int word_len;
6110
6111 if (!*str) /* EOL - do not finalize word */
6112 break;
6113 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006114 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006115 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02006116 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006117 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02006118 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006119 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02006120 * Example: "v='\*'; echo b$v" prints "b\*"
6121 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006122 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006123 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006124 /*/ Why can't we do it easier? */
6125 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
6126 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
6127 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006128 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006129 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006130 if (!*str) /* EOL - do not finalize word */
6131 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006132 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006133
6134 /* We know str here points to at least one IFS char */
6135 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02006136 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006137 if (!*str) /* EOL - do not finalize word */
6138 break;
6139
Denys Vlasenko96786362018-04-11 16:02:58 +02006140 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
6141 && strchr(G.ifs, *str) /* the second check would fail */
6142 ) {
6143 /* This is a non-whitespace $IFS char */
6144 /* Skip it and IFS whitespace chars, start new word */
6145 str++;
6146 str += strspn(str, G.ifs_whitespace);
6147 goto new_word;
6148 }
6149
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006150 /* Start new word... but not always! */
6151 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006152 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02006153 /*
6154 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006155 * here nothing precedes the space in $v expansion,
6156 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006157 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02006158 * It's okay if this accesses the byte before first argv[]:
6159 * past call to o_save_ptr() cleared it to zero byte
6160 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006161 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02006162 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006163 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02006164 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006165 o_addchr(output, '\0');
6166 debug_print_list("expand_on_ifs", output, n);
6167 n = o_save_ptr(output, n);
6168 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006169 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006170
Denys Vlasenko168579a2018-07-19 13:45:54 +02006171 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006172 debug_print_list("expand_on_ifs[1]", output, n);
6173 return n;
6174}
6175
6176/* Helper to expand $((...)) and heredoc body. These act as if
6177 * they are in double quotes, with the exception that they are not :).
6178 * Just the rules are similar: "expand only $var and `cmd`"
6179 *
6180 * Returns malloced string.
6181 * As an optimization, we return NULL if expansion is not needed.
6182 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006183static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006184{
6185 char *exp_str;
6186 struct in_str input;
6187 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006188 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006189
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006190 cp = str;
6191 for (;;) {
6192 if (!*cp) return NULL; /* string has no special chars */
6193 if (*cp == '$') break;
6194 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006195#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006196 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006197#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006198 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006199 }
6200
6201 /* We need to expand. Example:
6202 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
6203 */
6204 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006205 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01006206//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006207 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02006208 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02006209 EXP_FLAG_ESC_GLOB_CHARS,
6210 /*unbackslash:*/ 1
6211 );
6212 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006213 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006214 return exp_str;
6215}
6216
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006217static const char *first_special_char_in_vararg(const char *cp)
6218{
6219 for (;;) {
6220 if (!*cp) return NULL; /* string has no special chars */
6221 if (*cp == '$') return cp;
6222 if (*cp == '\\') return cp;
6223 if (*cp == '\'') return cp;
6224 if (*cp == '"') return cp;
6225#if ENABLE_HUSH_TICK
6226 if (*cp == '`') return cp;
6227#endif
6228 /* dquoted "${x:+ARG}" should not glob, therefore
6229 * '*' et al require some non-literal processing: */
6230 if (*cp == '*') return cp;
6231 if (*cp == '?') return cp;
6232 if (*cp == '[') return cp;
6233 cp++;
6234 }
6235}
6236
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006237/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
6238 * These can contain single- and double-quoted strings,
6239 * and treated as if the ARG string is initially unquoted. IOW:
6240 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
6241 * a dquoted string: "${var#"zz"}"), the difference only comes later
6242 * (word splitting and globbing of the ${var...} result).
6243 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006244#if !BASH_PATTERN_SUBST
6245#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
6246 encode_then_expand_vararg(str, handle_squotes)
6247#endif
6248static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6249{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006250#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006251 const int do_unbackslash = 0;
6252#endif
6253 char *exp_str;
6254 struct in_str input;
6255 o_string dest = NULL_O_STRING;
6256
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006257 if (!first_special_char_in_vararg(str)) {
6258 /* string has no special chars */
6259 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006260 }
6261
Denys Vlasenkob762c782018-07-17 14:21:38 +02006262 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006263 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006264 exp_str = NULL;
6265
6266 for (;;) {
6267 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006268
6269 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006270 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6271 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006272
6273 if (!dest.o_expflags) {
6274 if (ch == EOF)
6275 break;
6276 if (handle_squotes && ch == '\'') {
6277 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006278 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006279 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006280 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006281 }
6282 if (ch == EOF) {
6283 syntax_error_unterm_ch('"');
6284 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006285 }
6286 if (ch == '"') {
6287 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6288 continue;
6289 }
6290 if (ch == '\\') {
6291 ch = i_getch(&input);
6292 if (ch == EOF) {
6293//example? error message? syntax_error_unterm_ch('"');
6294 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6295 goto ret;
6296 }
6297 o_addqchr(&dest, ch);
6298 continue;
6299 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006300 if (ch == '$') {
Denys Vlasenkob278d822021-07-26 15:29:13 +02006301 if (parse_dollar_squote(NULL, &dest, &input))
6302 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006303 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6304 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6305 goto ret;
6306 }
6307 continue;
6308 }
6309#if ENABLE_HUSH_TICK
6310 if (ch == '`') {
6311 //unsigned pos = dest->length;
6312 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6313 o_addchr(&dest, 0x80 | '`');
6314 if (!add_till_backquote(&dest, &input,
6315 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6316 )
6317 ) {
6318 goto ret; /* error */
6319 }
6320 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6321 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6322 continue;
6323 }
6324#endif
6325 o_addQchr(&dest, ch);
6326 } /* for (;;) */
6327
6328 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6329 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006330 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6331 do_unbackslash
6332 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006333 ret:
6334 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006335 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006336 return exp_str;
6337}
6338
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006339/* Expanding ARG in ${var+ARG}, ${var-ARG}
6340 */
Denys Vlasenko53b2fdc2021-10-10 13:50:53 +02006341static NOINLINE int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006342 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006343{
6344 struct in_str input;
6345 o_string dest = NULL_O_STRING;
6346
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006347 if (!first_special_char_in_vararg(str)
6348 && '\0' == str[strcspn(str, G.ifs)]
6349 ) {
6350 /* string has no special chars
6351 * && string has no $IFS chars
6352 */
Denys Vlasenko9e0adb92019-05-15 13:39:19 +02006353 if (dquoted) {
6354 /* Prints 1 (quoted expansion is a "" word, not nothing):
6355 * set -- "${notexist-}"; echo $#
6356 */
6357 output->has_quoted_part = 1;
6358 }
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006359 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006360 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006361
Denys Vlasenko294eb462018-07-20 16:18:59 +02006362 setup_string_in_str(&input, str);
6363
6364 for (;;) {
6365 int ch;
6366
6367 ch = i_getch(&input);
6368 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6369 __func__, ch, ch, dest.o_expflags);
6370
6371 if (!dest.o_expflags) {
6372 if (ch == EOF)
6373 break;
6374 if (!dquoted && strchr(G.ifs, ch)) {
6375 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6376 * do not assume we are at the start of the word (PREFIX above).
6377 */
6378 if (dest.data) {
6379 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006380 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006381 o_addchr(output, '\0');
6382 n = o_save_ptr(output, n); /* create next word */
6383 } else
6384 if (output->length != o_get_last_ptr(output, n)
6385 || output->has_quoted_part
6386 ) {
6387 /* For these cases:
6388 * f() { for i; do echo "|$i|"; done; }; x=x
6389 * f a${x:+ }b # 1st condition
6390 * |a|
6391 * |b|
6392 * f ""${x:+ }b # 2nd condition
6393 * ||
6394 * |b|
6395 */
6396 o_addchr(output, '\0');
6397 n = o_save_ptr(output, n); /* create next word */
6398 }
6399 continue;
6400 }
6401 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006402 if (!add_till_single_quote_dquoted(&dest, &input))
6403 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006404 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6405 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006406 continue;
6407 }
6408 }
6409 if (ch == EOF) {
6410 syntax_error_unterm_ch('"');
6411 goto ret; /* error */
6412 }
6413 if (ch == '"') {
6414 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006415 if (dest.o_expflags) {
6416 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6417 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6418 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006419 continue;
6420 }
6421 if (ch == '\\') {
6422 ch = i_getch(&input);
6423 if (ch == EOF) {
6424//example? error message? syntax_error_unterm_ch('"');
6425 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6426 goto ret;
6427 }
6428 o_addqchr(&dest, ch);
6429 continue;
6430 }
6431 if (ch == '$') {
6432 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6433 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6434 goto ret;
6435 }
6436 continue;
6437 }
6438#if ENABLE_HUSH_TICK
6439 if (ch == '`') {
6440 //unsigned pos = dest->length;
6441 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6442 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6443 if (!add_till_backquote(&dest, &input,
6444 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6445 )
6446 ) {
6447 goto ret; /* error */
6448 }
6449 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6450 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6451 continue;
6452 }
6453#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006454 if (dquoted) {
6455 /* Always glob-protect if in dquotes:
6456 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6457 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6458 */
6459 o_addqchr(&dest, ch);
6460 } else {
6461 /* Glob-protect only if char is quoted:
6462 * x=x; echo ${x:+/bin/c*} - prints many filenames
6463 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6464 */
6465 o_addQchr(&dest, ch);
6466 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006467 } /* for (;;) */
6468
6469 if (dest.data) {
6470 n = expand_vars_to_list(output, n, dest.data);
6471 }
6472 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006473 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006474 return n;
6475}
6476
Denys Vlasenko0b883582016-12-23 16:49:07 +01006477#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006478static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006479{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006480 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006481 arith_t res;
6482 char *exp_str;
6483
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006484 math_state.lookupvar = get_local_var_value;
6485 math_state.setvar = set_local_var_from_halves;
6486 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006487 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006488 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006489 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006490 if (errmsg_p)
6491 *errmsg_p = math_state.errmsg;
6492 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006493 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006494 return res;
6495}
6496#endif
6497
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006498#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006499/* ${var/[/]pattern[/repl]} helpers */
6500static char *strstr_pattern(char *val, const char *pattern, int *size)
6501{
Denys Vlasenko49bcf9f2021-10-09 03:52:04 +02006502 int first_escaped = (pattern[0] == '\\' && pattern[1]);
6503 /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
6504 * as literal too (as it is semi-common, and easy to accomodate
6505 * by just using str + 1).
6506 */
6507 int sz = strcspn(pattern + first_escaped * 2, "*?[\\");
6508 if ((pattern + first_escaped * 2)[sz] == '\0') {
Denys Vlasenko49cc3ca2021-07-27 17:53:55 +02006509 /* Optimization for trivial patterns.
6510 * Testcase for very slow replace (performs about 22k replaces):
6511 * x=::::::::::::::::::::::
6512 * x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;echo ${#x}
6513 * echo "${x//:/|}"
6514 */
Denys Vlasenko49bcf9f2021-10-09 03:52:04 +02006515 *size = sz + first_escaped;
6516 return strstr(val, pattern + first_escaped);
Denys Vlasenko49cc3ca2021-07-27 17:53:55 +02006517 }
6518
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006519 while (1) {
6520 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6521 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6522 if (end) {
6523 *size = end - val;
6524 return val;
6525 }
6526 if (*val == '\0')
6527 return NULL;
6528 /* Optimization: if "*pat" did not match the start of "string",
6529 * we know that "tring", "ring" etc will not match too:
6530 */
6531 if (pattern[0] == '*')
6532 return NULL;
6533 val++;
6534 }
6535}
6536static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6537{
6538 char *result = NULL;
6539 unsigned res_len = 0;
6540 unsigned repl_len = strlen(repl);
6541
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006542 /* Null pattern never matches, including if "var" is empty */
6543 if (!pattern[0])
6544 return result; /* NULL, no replaces happened */
6545
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006546 while (1) {
6547 int size;
6548 char *s = strstr_pattern(val, pattern, &size);
6549 if (!s)
6550 break;
6551
6552 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006553 strcpy(mempcpy(result + res_len, val, s - val), repl);
6554 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006555 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6556
6557 val = s + size;
6558 if (exp_op == '/')
6559 break;
6560 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006561 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006562 result = xrealloc(result, res_len + strlen(val) + 1);
6563 strcpy(result + res_len, val);
6564 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6565 }
6566 debug_printf_varexp("result:'%s'\n", result);
6567 return result;
6568}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006569#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006570
Denys Vlasenko168579a2018-07-19 13:45:54 +02006571static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006572 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006573{
6574 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6575 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6576 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6577 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006578 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006579 } else { /* quoted "$VAR" */
6580 output->has_quoted_part = 1;
6581 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6582 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6583 if (val && val[0])
6584 o_addQstr(output, val);
6585 }
6586 return n;
6587}
6588
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006589/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006590 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006591static NOINLINE int expand_one_var(o_string *output, int n,
6592 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006593{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006594 const char *val;
6595 char *to_be_freed;
6596 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006597 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006598 char exp_op;
6599 char exp_save = exp_save; /* for compiler */
6600 char *exp_saveptr; /* points to expansion operator */
6601 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006602 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006603
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006604 val = NULL;
6605 to_be_freed = NULL;
6606 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006607 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006608 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006609 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006610 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006611 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006612 exp_op = 0;
6613
Denys Vlasenkob762c782018-07-17 14:21:38 +02006614 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006615 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6616 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6617 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006618 ) {
6619 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006620 var++;
6621 exp_op = 'L';
6622 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006623 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006624 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006625 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006626 ) {
6627 /* ${?:0}, ${#[:]%0} etc */
6628 exp_saveptr = var + 1;
6629 } else {
6630 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6631 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6632 }
6633 exp_op = exp_save = *exp_saveptr;
6634 if (exp_op) {
6635 exp_word = exp_saveptr + 1;
6636 if (exp_op == ':') {
6637 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006638//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006639 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006640 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006641 ) {
6642 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6643 exp_op = ':';
6644 exp_word--;
6645 }
6646 }
6647 *exp_saveptr = '\0';
6648 } /* else: it's not an expansion op, but bare ${var} */
6649 }
6650
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006651 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006652 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006653 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006654 int nn = xatoi_positive(var);
6655 if (nn < G.global_argc)
6656 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006657 /* else val remains NULL: $N with too big N */
6658 } else {
6659 switch (var[0]) {
6660 case '$': /* pid */
6661 val = utoa(G.root_pid);
6662 break;
6663 case '!': /* bg pid */
6664 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6665 break;
6666 case '?': /* exitcode */
6667 val = utoa(G.last_exitcode);
6668 break;
6669 case '#': /* argc */
6670 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6671 break;
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006672 case '-': { /* active options */
6673 /* Check set_mode() to see what option chars we support */
6674 char *cp;
6675 val = cp = G.optstring_buf;
6676 if (G.o_opt[OPT_O_ERREXIT])
6677 *cp++ = 'e';
6678 if (G_interactive_fd)
6679 *cp++ = 'i';
6680 if (G_x_mode)
6681 *cp++ = 'x';
6682 /* If G.o_opt[OPT_O_NOEXEC] is true,
6683 * commands read but are not executed,
6684 * so $- can not execute too, 'n' is never seen in $-.
6685 */
Denys Vlasenkof3634582019-06-03 12:21:04 +02006686 if (G.opt_c)
6687 *cp++ = 'c';
Denys Vlasenkod8740b22019-05-19 19:11:21 +02006688 if (G.opt_s)
6689 *cp++ = 's';
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006690 *cp = '\0';
6691 break;
6692 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006693 default:
6694 val = get_local_var_value(var);
6695 }
6696 }
6697
6698 /* Handle any expansions */
6699 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006700 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006701 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006702 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006703 debug_printf_expand("%s\n", val);
6704 } else if (exp_op) {
6705 if (exp_op == '%' || exp_op == '#') {
6706 /* Standard-mandated substring removal ops:
6707 * ${parameter%word} - remove smallest suffix pattern
6708 * ${parameter%%word} - remove largest suffix pattern
6709 * ${parameter#word} - remove smallest prefix pattern
6710 * ${parameter##word} - remove largest prefix pattern
6711 *
6712 * Word is expanded to produce a glob pattern.
6713 * Then var's value is matched to it and matching part removed.
6714 */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006715 /* bash compat: if x is "" and no shrinking of it is possible,
6716 * inner ${...} is not evaluated. Example:
6717 * unset b; : ${a%${b=B}}; echo $b
6718 * assignment b=B only happens if $a is not "".
6719 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006720 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006721 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006722 char *exp_exp_word;
6723 char *loc;
6724 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006725 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006726 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006727 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006728 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006729 if (exp_exp_word)
6730 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006731 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6732 /*
6733 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006734 * G.global_argv and results of utoa and get_local_var_value
6735 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006736 * scan_and_match momentarily stores NULs there.
6737 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006738 t = (char*)val;
6739 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006740 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 +02006741 free(exp_exp_word);
6742 if (loc) { /* match was found */
6743 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006744 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006745 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006746 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006747 }
6748 }
6749 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006750#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006751 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006752 /* It's ${var/[/]pattern[/repl]} thing.
6753 * Note that in encoded form it has TWO parts:
6754 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006755 * and if // is used, it is encoded as \:
6756 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006757 */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006758 /* bash compat: if var is "", both pattern and repl
6759 * are still evaluated, if it is unset, then not:
6760 * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
6761 * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
6762 */
6763 if (val /*&& val[0]*/) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006764 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006765 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006766 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006767 * >az >bz
6768 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6769 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6770 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6771 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006772 * (note that a*z _pattern_ is never globbed!)
6773 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006774 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006775 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006776 if (!pattern)
6777 pattern = xstrdup(exp_word);
6778 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6779 *p++ = SPECIAL_VAR_SYMBOL;
6780 exp_word = p;
6781 p = strchr(p, SPECIAL_VAR_SYMBOL);
6782 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006783 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006784 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6785 /* HACK ALERT. We depend here on the fact that
6786 * G.global_argv and results of utoa and get_local_var_value
6787 * are actually in writable memory:
6788 * replace_pattern momentarily stores NULs there. */
6789 t = (char*)val;
6790 to_be_freed = replace_pattern(t,
6791 pattern,
6792 (repl ? repl : exp_word),
6793 exp_op);
6794 if (to_be_freed) /* at least one replace happened */
6795 val = to_be_freed;
6796 free(pattern);
6797 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006798 } else {
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006799 /* Unset variable always gives nothing */
6800 // a=; echo ${a/*/w} # "w"
6801 // unset a; echo ${a/*/w} # ""
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006802 /* Just skip "replace" part */
6803 *p++ = SPECIAL_VAR_SYMBOL;
6804 p = strchr(p, SPECIAL_VAR_SYMBOL);
6805 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006806 }
6807 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006808#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006809 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006810#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006811 /* It's ${var:N[:M]} bashism.
6812 * Note that in encoded form it has TWO parts:
6813 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6814 */
6815 arith_t beg, len;
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006816 unsigned vallen;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006817 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006818
Denys Vlasenko063847d2010-09-15 13:33:02 +02006819 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6820 if (errmsg)
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006821 goto empty_result;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006822 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6823 *p++ = SPECIAL_VAR_SYMBOL;
6824 exp_word = p;
6825 p = strchr(p, SPECIAL_VAR_SYMBOL);
6826 *p = '\0';
Denys Vlasenkoa7b52d22020-12-23 12:38:03 +01006827 vallen = val ? strlen(val) : 0;
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006828 if (beg < 0) {
6829 /* negative beg counts from the end */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006830 beg = (arith_t)vallen + beg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006831 }
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006832 /* If expansion will be empty, do not even evaluate len */
6833 if (!val || beg < 0 || beg > vallen) {
6834 /* Why > vallen, not >=? bash:
6835 * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
6836 * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
6837 */
6838 goto empty_result;
6839 }
6840 len = expand_and_evaluate_arith(exp_word, &errmsg);
6841 if (errmsg)
6842 goto empty_result;
6843 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006844 debug_printf_varexp("from val:'%s'\n", val);
6845 if (len < 0) {
6846 /* in bash, len=-n means strlen()-n */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006847 len = (arith_t)vallen - beg + len;
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006848 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006849 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006850 }
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006851 if (len <= 0 || !val /*|| beg >= vallen*/) {
6852 empty_result:
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006853 val = NULL;
6854 } else {
6855 /* Paranoia. What if user entered 9999999999999
6856 * which fits in arith_t but not int? */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006857 if (len > INT_MAX)
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006858 len = INT_MAX;
6859 val = to_be_freed = xstrndup(val + beg, len);
6860 }
6861 debug_printf_varexp("val:'%s'\n", val);
6862#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006863 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006864 val = NULL;
6865#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006866 } else { /* one of "-=+?" */
6867 /* Standard-mandated substitution ops:
6868 * ${var?word} - indicate error if unset
6869 * If var is unset, word (or a message indicating it is unset
6870 * if word is null) is written to standard error
6871 * and the shell exits with a non-zero exit status.
6872 * Otherwise, the value of var is substituted.
6873 * ${var-word} - use default value
6874 * If var is unset, word is substituted.
6875 * ${var=word} - assign and use default value
6876 * If var is unset, word is assigned to var.
6877 * In all cases, final value of var is substituted.
6878 * ${var+word} - use alternative value
6879 * If var is unset, null is substituted.
6880 * Otherwise, word is substituted.
6881 *
6882 * Word is subjected to tilde expansion, parameter expansion,
6883 * command substitution, and arithmetic expansion.
6884 * If word is not needed, it is not expanded.
6885 *
6886 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6887 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006888 *
6889 * Word-splitting and single quote behavior:
6890 *
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006891 * $ f() { for i; do echo "|$i|"; done; }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006892 *
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006893 * $ x=; f ${x:?'x y' z}; echo $?
6894 * bash: x: x y z # neither f nor "echo $?" executes
6895 * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006896 * $ x=; f "${x:?'x y' z}"
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006897 * bash: x: x y z # dash prints: dash: x: 'x y' z
Denys Vlasenko294eb462018-07-20 16:18:59 +02006898 *
6899 * $ x=; f ${x:='x y' z}
6900 * |x|
6901 * |y|
6902 * |z|
6903 * $ x=; f "${x:='x y' z}"
6904 * |'x y' z|
6905 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006906 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006907 * |x y|
6908 * |z|
6909 * $ x=x; f "${x:+'x y' z}"
6910 * |'x y' z|
6911 *
6912 * $ x=; f ${x:-'x y' z}
6913 * |x y|
6914 * |z|
6915 * $ x=; f "${x:-'x y' z}"
6916 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006917 */
6918 int use_word = (!val || ((exp_save == ':') && !val[0]));
6919 if (exp_op == '+')
6920 use_word = !use_word;
6921 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6922 (exp_save == ':') ? "true" : "false", use_word);
6923 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006924 if (exp_op == '+' || exp_op == '-') {
6925 /* ${var+word} - use alternative value */
6926 /* ${var-word} - use default value */
6927 n = encode_then_append_var_plusminus(output, n, exp_word,
6928 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006929 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006930 val = NULL;
6931 } else {
6932 /* ${var?word} - indicate error if unset */
6933 /* ${var=word} - assign and use default value */
6934 to_be_freed = encode_then_expand_vararg(exp_word,
6935 /*handle_squotes:*/ !(arg0 & 0x80),
6936 /*unbackslash:*/ 0
6937 );
6938 if (to_be_freed)
6939 exp_word = to_be_freed;
6940 if (exp_op == '?') {
6941 /* mimic bash message */
6942 msg_and_die_if_script("%s: %s",
6943 var,
6944 exp_word[0]
6945 ? exp_word
6946 : "parameter null or not set"
6947 /* ash has more specific messages, a-la: */
6948 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6949 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006950//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006951//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006952// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6953// bash: x: x y z
6954// $
6955// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006956 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006957 val = exp_word;
6958 }
6959 if (exp_op == '=') {
6960 /* ${var=[word]} or ${var:=[word]} */
6961 if (isdigit(var[0]) || var[0] == '#') {
6962 /* mimic bash message */
6963 msg_and_die_if_script("$%s: cannot assign in this way", var);
6964 val = NULL;
6965 } else {
6966 char *new_var = xasprintf("%s=%s", var, val);
6967 set_local_var(new_var, /*flag:*/ 0);
6968 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006969 }
6970 }
6971 }
6972 } /* one of "-=+?" */
6973
6974 *exp_saveptr = exp_save;
6975 } /* if (exp_op) */
6976
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006977 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006978 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006979
Denys Vlasenko168579a2018-07-19 13:45:54 +02006980 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006981
6982 free(to_be_freed);
6983 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006984}
6985
6986/* Expand all variable references in given string, adding words to list[]
6987 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6988 * to be filled). This routine is extremely tricky: has to deal with
6989 * variables/parameters with whitespace, $* and $@, and constructs like
6990 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006991static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006992{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006993 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006994 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006995 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006996 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006997 char *p;
6998
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006999 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
7000 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007001 debug_print_list("expand_vars_to_list[0]", output, n);
7002
7003 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
7004 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01007005#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007006 char arith_buf[sizeof(arith_t)*3 + 2];
7007#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02007008
Denys Vlasenko168579a2018-07-19 13:45:54 +02007009 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02007010 o_addchr(output, '\0');
7011 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02007012 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02007013 }
7014
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007015 o_addblock(output, arg, p - arg);
7016 debug_print_list("expand_vars_to_list[1]", output, n);
7017 arg = ++p;
7018 p = strchr(p, SPECIAL_VAR_SYMBOL);
7019
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007020 /* Fetch special var name (if it is indeed one of them)
7021 * and quote bit, force the bit on if singleword expansion -
7022 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007023 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007024
7025 /* Is this variable quoted and thus expansion can't be null?
7026 * "$@" is special. Even if quoted, it can still
7027 * expand to nothing (not even an empty string),
7028 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007029 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007030 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007031
7032 switch (first_ch & 0x7f) {
7033 /* Highest bit in first_ch indicates that var is double-quoted */
7034 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02007035 case '@': {
7036 int i;
7037 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007038 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02007039 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007040 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007041 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007042 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02007043 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007044 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
7045 if (G.global_argv[i++][0] && G.global_argv[i]) {
7046 /* this argv[] is not empty and not last:
7047 * put terminating NUL, start new word */
7048 o_addchr(output, '\0');
7049 debug_print_list("expand_vars_to_list[2]", output, n);
7050 n = o_save_ptr(output, n);
7051 debug_print_list("expand_vars_to_list[3]", output, n);
7052 }
7053 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007054 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007055 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007056 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02007057 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007058 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007059 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007060 while (1) {
7061 o_addQstr(output, G.global_argv[i]);
7062 if (++i >= G.global_argc)
7063 break;
7064 o_addchr(output, '\0');
7065 debug_print_list("expand_vars_to_list[4]", output, n);
7066 n = o_save_ptr(output, n);
7067 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007068 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007069 while (1) {
7070 o_addQstr(output, G.global_argv[i]);
7071 if (!G.global_argv[++i])
7072 break;
7073 if (G.ifs[0])
7074 o_addchr(output, G.ifs[0]);
7075 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02007076 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007077 }
7078 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02007079 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007080 case SPECIAL_VAR_SYMBOL: {
7081 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007082 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02007083 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007084 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007085 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007086 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007087 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01007088 case SPECIAL_VAR_QUOTED_SVS:
7089 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007090 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02007091 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01007092 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01007093 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007094#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007095 case '`': {
7096 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02007097 o_string subst_result = NULL_O_STRING;
7098
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007099 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007100 arg++;
7101 /* Can't just stuff it into output o_string,
7102 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02007103 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007104 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
7105 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02007106 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007107 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02007108 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02007109 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007110 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02007111 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007112#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01007113#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007114 case '+': {
7115 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007116 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007117
7118 arg++; /* skip '+' */
7119 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
7120 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02007121 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02007122 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
7123 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01007124 if (res < 0
7125 && first_ch == (char)('+'|0x80)
7126 /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
7127 ) {
7128 /* Quoted negative ariths, like filename[0"$((-9))"],
7129 * should not be interpreted as glob ranges.
7130 * Convert leading '-' to '\-':
7131 */
7132 o_grow_by(output, 1);
7133 output->data[output->length++] = '\\';
7134 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007135 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007136 break;
7137 }
7138#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02007139 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007140 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02007141 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007142 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007143 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
7144
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007145 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
7146 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007147 if (*p != SPECIAL_VAR_SYMBOL)
7148 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007149 arg = ++p;
7150 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
7151
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02007152 if (*arg) {
7153 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02007154 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02007155 o_addchr(output, '\0');
7156 n = o_save_ptr(output, n);
7157 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007158 debug_print_list("expand_vars_to_list[a]", output, n);
7159 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02007160 * if needed (much earlier), do not use o_addQstr here!
7161 */
7162 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007163 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02007164 } else
7165 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02007166 && !(cant_be_null & 0x80) /* and all vars were not quoted */
7167 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007168 ) {
7169 n--;
7170 /* allow to reuse list[n] later without re-growth */
7171 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007172 }
7173
7174 return n;
7175}
7176
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007177static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007178{
7179 int n;
7180 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007181 o_string output = NULL_O_STRING;
7182
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007183 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007184
7185 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02007186 for (;;) {
7187 /* go to next list[n] */
7188 output.ended_in_ifs = 0;
7189 n = o_save_ptr(&output, n);
7190
7191 if (!*argv)
7192 break;
7193
7194 /* expand argv[i] */
7195 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02007196 /* if (!output->has_empty_slot) -- need this?? */
7197 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007198 }
7199 debug_print_list("expand_variables", &output, n);
7200
7201 /* output.data (malloced in one block) gets returned in "list" */
7202 list = o_finalize_list(&output, n);
7203 debug_print_strings("expand_variables[1]", list);
7204 return list;
7205}
7206
7207static char **expand_strvec_to_strvec(char **argv)
7208{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007209 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007210}
7211
Denys Vlasenkod2241f52020-10-31 03:34:07 +01007212#if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007213static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
7214{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007215 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007216}
7217#endif
7218
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007219/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007220 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007221 *
7222 * NB: should NOT do globbing!
7223 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
7224 */
Denys Vlasenko34179952018-04-11 13:47:59 +02007225static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007226{
Denys Vlasenko637982f2017-07-06 01:52:23 +02007227#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007228 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02007229 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007230#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007231 char *argv[2], **list;
7232
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007233 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007234 /* This is generally an optimization, but it also
7235 * handles "", which otherwise trips over !list[0] check below.
7236 * (is this ever happens that we actually get str="" here?)
7237 */
7238 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
7239 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007240 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007241 return xstrdup(str);
7242 }
7243
7244 argv[0] = (char*)str;
7245 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02007246 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02007247 if (!list[0]) {
7248 /* Example where it happens:
7249 * x=; echo ${x:-"$@"}
7250 */
7251 ((char*)list)[0] = '\0';
7252 } else {
7253 if (HUSH_DEBUG)
7254 if (list[1])
James Byrne69374872019-07-02 11:35:03 +02007255 bb_simple_error_msg_and_die("BUG in varexp2");
Denys Vlasenko2e711012018-07-18 16:02:25 +02007256 /* actually, just move string 2*sizeof(char*) bytes back */
7257 overlapping_strcpy((char*)list, list[0]);
7258 if (do_unbackslash)
7259 unbackslash((char*)list);
7260 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007261 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007262 return (char*)list;
7263}
7264
Denys Vlasenkoabf75562018-04-02 17:25:18 +02007265#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007266static char* expand_strvec_to_string(char **argv)
7267{
7268 char **list;
7269
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007270 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007271 /* Convert all NULs to spaces */
7272 if (list[0]) {
7273 int n = 1;
7274 while (list[n]) {
7275 if (HUSH_DEBUG)
7276 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
7277 bb_error_msg_and_die("BUG in varexp3");
7278 /* bash uses ' ' regardless of $IFS contents */
7279 list[n][-1] = ' ';
7280 n++;
7281 }
7282 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02007283 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007284 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
7285 return (char*)list;
7286}
Denys Vlasenko1f191122018-01-11 13:17:30 +01007287#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007288
7289static char **expand_assignments(char **argv, int count)
7290{
7291 int i;
7292 char **p;
7293
7294 G.expanded_assignments = p = NULL;
7295 /* Expand assignments into one string each */
7296 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02007297 p = add_string_to_strings(p,
7298 expand_string_to_string(argv[i],
7299 EXP_FLAG_ESC_GLOB_CHARS,
7300 /*unbackslash:*/ 1
7301 )
7302 );
7303 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007304 }
7305 G.expanded_assignments = NULL;
7306 return p;
7307}
7308
7309
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007310static void switch_off_special_sigs(unsigned mask)
7311{
7312 unsigned sig = 0;
7313 while ((mask >>= 1) != 0) {
7314 sig++;
7315 if (!(mask & 1))
7316 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007317#if ENABLE_HUSH_TRAP
7318 if (G_traps) {
7319 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007320 /* trap is '', has to remain SIG_IGN */
7321 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007322 free(G_traps[sig]);
7323 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007324 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007325#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007326 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007327 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007328 }
7329}
7330
Denys Vlasenkob347df92011-08-09 22:49:15 +02007331#if BB_MMU
7332/* never called */
7333void re_execute_shell(char ***to_free, const char *s,
7334 char *g_argv0, char **g_argv,
7335 char **builtin_argv) NORETURN;
7336
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007337static void reset_traps_to_defaults(void)
7338{
7339 /* This function is always called in a child shell
7340 * after fork (not vfork, NOMMU doesn't use this function).
7341 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007342 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007343 unsigned mask;
7344
7345 /* Child shells are not interactive.
7346 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7347 * Testcase: (while :; do :; done) + ^Z should background.
7348 * Same goes for SIGTERM, SIGHUP, SIGINT.
7349 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007350 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007351 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007352 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007353
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007354 /* Switch off special sigs */
7355 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007356# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007357 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007358# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007359 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007360 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7361 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007362
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007363# if ENABLE_HUSH_TRAP
7364 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007365 return;
7366
7367 /* Reset all sigs to default except ones with empty traps */
7368 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007369 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007370 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007371 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007372 continue; /* empty trap: has to remain SIG_IGN */
7373 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007374 free(G_traps[sig]);
7375 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007376 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007377 if (sig == 0)
7378 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007379 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007380 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007381# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007382}
7383
7384#else /* !BB_MMU */
7385
7386static void re_execute_shell(char ***to_free, const char *s,
7387 char *g_argv0, char **g_argv,
7388 char **builtin_argv) NORETURN;
7389static void re_execute_shell(char ***to_free, const char *s,
7390 char *g_argv0, char **g_argv,
7391 char **builtin_argv)
7392{
7393# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7394 /* delims + 2 * (number of bytes in printed hex numbers) */
7395 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7396 char *heredoc_argv[4];
7397 struct variable *cur;
7398# if ENABLE_HUSH_FUNCTIONS
7399 struct function *funcp;
7400# endif
7401 char **argv, **pp;
7402 unsigned cnt;
7403 unsigned long long empty_trap_mask;
7404
7405 if (!g_argv0) { /* heredoc */
7406 argv = heredoc_argv;
7407 argv[0] = (char *) G.argv0_for_re_execing;
7408 argv[1] = (char *) "-<";
7409 argv[2] = (char *) s;
7410 argv[3] = NULL;
7411 pp = &argv[3]; /* used as pointer to empty environment */
7412 goto do_exec;
7413 }
7414
7415 cnt = 0;
7416 pp = builtin_argv;
7417 if (pp) while (*pp++)
7418 cnt++;
7419
7420 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007421 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007422 int sig;
7423 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007424 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007425 empty_trap_mask |= 1LL << sig;
7426 }
7427 }
7428
7429 sprintf(param_buf, NOMMU_HACK_FMT
7430 , (unsigned) G.root_pid
7431 , (unsigned) G.root_ppid
7432 , (unsigned) G.last_bg_pid
7433 , (unsigned) G.last_exitcode
7434 , cnt
7435 , empty_trap_mask
7436 IF_HUSH_LOOPS(, G.depth_of_loop)
7437 );
7438# undef NOMMU_HACK_FMT
7439 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7440 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7441 */
7442 cnt += 6;
7443 for (cur = G.top_var; cur; cur = cur->next) {
7444 if (!cur->flg_export || cur->flg_read_only)
7445 cnt += 2;
7446 }
7447# if ENABLE_HUSH_FUNCTIONS
7448 for (funcp = G.top_func; funcp; funcp = funcp->next)
7449 cnt += 3;
7450# endif
7451 pp = g_argv;
7452 while (*pp++)
7453 cnt++;
7454 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7455 *pp++ = (char *) G.argv0_for_re_execing;
7456 *pp++ = param_buf;
7457 for (cur = G.top_var; cur; cur = cur->next) {
7458 if (strcmp(cur->varstr, hush_version_str) == 0)
7459 continue;
7460 if (cur->flg_read_only) {
7461 *pp++ = (char *) "-R";
7462 *pp++ = cur->varstr;
7463 } else if (!cur->flg_export) {
7464 *pp++ = (char *) "-V";
7465 *pp++ = cur->varstr;
7466 }
7467 }
7468# if ENABLE_HUSH_FUNCTIONS
7469 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7470 *pp++ = (char *) "-F";
7471 *pp++ = funcp->name;
7472 *pp++ = funcp->body_as_string;
7473 }
7474# endif
7475 /* We can pass activated traps here. Say, -Tnn:trap_string
7476 *
7477 * However, POSIX says that subshells reset signals with traps
7478 * to SIG_DFL.
7479 * I tested bash-3.2 and it not only does that with true subshells
7480 * of the form ( list ), but with any forked children shells.
7481 * I set trap "echo W" WINCH; and then tried:
7482 *
7483 * { echo 1; sleep 20; echo 2; } &
7484 * while true; do echo 1; sleep 20; echo 2; break; done &
7485 * true | { echo 1; sleep 20; echo 2; } | cat
7486 *
7487 * In all these cases sending SIGWINCH to the child shell
7488 * did not run the trap. If I add trap "echo V" WINCH;
7489 * _inside_ group (just before echo 1), it works.
7490 *
7491 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007492 */
7493 *pp++ = (char *) "-c";
7494 *pp++ = (char *) s;
7495 if (builtin_argv) {
7496 while (*++builtin_argv)
7497 *pp++ = *builtin_argv;
7498 *pp++ = (char *) "";
7499 }
7500 *pp++ = g_argv0;
7501 while (*g_argv)
7502 *pp++ = *g_argv++;
7503 /* *pp = NULL; - is already there */
7504 pp = environ;
7505
7506 do_exec:
7507 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007508 /* Don't propagate SIG_IGN to the child */
7509 if (SPECIAL_JOBSTOP_SIGS != 0)
7510 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007511 execve(bb_busybox_exec_path, argv, pp);
7512 /* Fallback. Useful for init=/bin/hush usage etc */
7513 if (argv[0][0] == '/')
7514 execve(argv[0], argv, pp);
7515 xfunc_error_retval = 127;
James Byrne69374872019-07-02 11:35:03 +02007516 bb_simple_error_msg_and_die("can't re-execute the shell");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007517}
7518#endif /* !BB_MMU */
7519
7520
7521static int run_and_free_list(struct pipe *pi);
7522
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007523/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007524 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7525 * end_trigger controls how often we stop parsing
7526 * NUL: parse all, execute, return
7527 * ';': parse till ';' or newline, execute, repeat till EOF
7528 */
7529static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007530{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007531 /* Why we need empty flag?
7532 * An obscure corner case "false; ``; echo $?":
7533 * empty command in `` should still set $? to 0.
7534 * But we can't just set $? to 0 at the start,
7535 * this breaks "false; echo `echo $?`" case.
7536 */
7537 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007538 while (1) {
7539 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007540
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007541#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007542 if (end_trigger == ';') {
7543 G.promptmode = 0; /* PS1 */
7544 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7545 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007546#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007547 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007548 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7549 /* If we are in "big" script
7550 * (not in `cmd` or something similar)...
7551 */
7552 if (pipe_list == ERR_PTR && end_trigger == ';') {
7553 /* Discard cached input (rest of line) */
7554 int ch = inp->last_char;
7555 while (ch != EOF && ch != '\n') {
7556 //bb_error_msg("Discarded:'%c'", ch);
7557 ch = i_getch(inp);
7558 }
7559 /* Force prompt */
7560 inp->p = NULL;
7561 /* This stream isn't empty */
7562 empty = 0;
7563 continue;
7564 }
7565 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007566 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007567 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007568 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007569 debug_print_tree(pipe_list, 0);
7570 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7571 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007572 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007573 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007574 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007575 }
Eric Andersen25f27032001-04-26 23:22:31 +00007576}
7577
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007578static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007579{
7580 struct in_str input;
Denys Vlasenko574b9c42021-09-07 21:44:44 +02007581 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007582
Eric Andersen25f27032001-04-26 23:22:31 +00007583 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007584 parse_and_run_stream(&input, '\0');
Denys Vlasenko574b9c42021-09-07 21:44:44 +02007585 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007586}
7587
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007588static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007589{
Eric Andersen25f27032001-04-26 23:22:31 +00007590 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007591 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007592
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007593 IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007594 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007595 parse_and_run_stream(&input, ';');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007596 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007597}
7598
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007599#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007600static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007601{
7602 pid_t pid;
7603 int channel[2];
7604# if !BB_MMU
7605 char **to_free = NULL;
7606# endif
7607
7608 xpipe(channel);
7609 pid = BB_MMU ? xfork() : xvfork();
7610 if (pid == 0) { /* child */
7611 disable_restore_tty_pgrp_on_exit();
7612 /* Process substitution is not considered to be usual
7613 * 'command execution'.
7614 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7615 */
7616 bb_signals(0
7617 + (1 << SIGTSTP)
7618 + (1 << SIGTTIN)
7619 + (1 << SIGTTOU)
7620 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007621 close(channel[0]); /* NB: close _first_, then move fd! */
7622 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007623# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007624 /* Awful hack for `trap` or $(trap).
7625 *
7626 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7627 * contains an example where "trap" is executed in a subshell:
7628 *
7629 * save_traps=$(trap)
7630 * ...
7631 * eval "$save_traps"
7632 *
7633 * Standard does not say that "trap" in subshell shall print
7634 * parent shell's traps. It only says that its output
7635 * must have suitable form, but then, in the above example
7636 * (which is not supposed to be normative), it implies that.
7637 *
7638 * bash (and probably other shell) does implement it
7639 * (traps are reset to defaults, but "trap" still shows them),
7640 * but as a result, "trap" logic is hopelessly messed up:
7641 *
7642 * # trap
7643 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7644 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7645 * # true | trap <--- trap is in subshell - no output (ditto)
7646 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7647 * trap -- 'echo Ho' SIGWINCH
7648 * # echo `(trap)` <--- in subshell in subshell - output
7649 * trap -- 'echo Ho' SIGWINCH
7650 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7651 * trap -- 'echo Ho' SIGWINCH
7652 *
7653 * The rules when to forget and when to not forget traps
7654 * get really complex and nonsensical.
7655 *
7656 * Our solution: ONLY bare $(trap) or `trap` is special.
7657 */
7658 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007659 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007660 && skip_whitespace(s + 4)[0] == '\0'
7661 ) {
Denys Vlasenko987be932022-02-06 20:07:12 +01007662 static const char *const argv[] ALIGN_PTR = { NULL, NULL };
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007663 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007664 fflush_all(); /* important */
7665 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007666 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007667# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007668# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007669 /* Prevent it from trying to handle ctrl-z etc */
7670 IF_HUSH_JOB(G.run_list_level = 1;)
7671 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007672 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007673 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007674 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007675 parse_and_run_string(s);
7676 _exit(G.last_exitcode);
7677# else
7678 /* We re-execute after vfork on NOMMU. This makes this script safe:
7679 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7680 * huge=`cat BIG` # was blocking here forever
7681 * echo OK
7682 */
7683 re_execute_shell(&to_free,
7684 s,
7685 G.global_argv[0],
7686 G.global_argv + 1,
7687 NULL);
7688# endif
7689 }
7690
7691 /* parent */
7692 *pid_p = pid;
7693# if ENABLE_HUSH_FAST
7694 G.count_SIGCHLD++;
7695//bb_error_msg("[%d] fork in generate_stream_from_string:"
7696// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7697// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7698# endif
7699 enable_restore_tty_pgrp_on_exit();
7700# if !BB_MMU
7701 free(to_free);
7702# endif
7703 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007704 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007705}
7706
7707/* Return code is exit status of the process that is run. */
7708static int process_command_subs(o_string *dest, const char *s)
7709{
7710 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007711 pid_t pid;
7712 int status, ch, eol_cnt;
7713
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007714 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007715
7716 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007717 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007718 while ((ch = getc(fp)) != EOF) {
7719 if (ch == '\0')
7720 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007721 if (ch == '\n') {
7722 eol_cnt++;
7723 continue;
7724 }
7725 while (eol_cnt) {
7726 o_addchr(dest, '\n');
7727 eol_cnt--;
7728 }
7729 o_addQchr(dest, ch);
7730 }
7731
7732 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007733 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007734 /* We need to extract exitcode. Test case
7735 * "true; echo `sleep 1; false` $?"
7736 * should print 1 */
7737 safe_waitpid(pid, &status, 0);
7738 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7739 return WEXITSTATUS(status);
7740}
7741#endif /* ENABLE_HUSH_TICK */
7742
7743
7744static void setup_heredoc(struct redir_struct *redir)
7745{
7746 struct fd_pair pair;
7747 pid_t pid;
7748 int len, written;
7749 /* the _body_ of heredoc (misleading field name) */
7750 const char *heredoc = redir->rd_filename;
7751 char *expanded;
7752#if !BB_MMU
7753 char **to_free;
7754#endif
7755
7756 expanded = NULL;
7757 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007758 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007759 if (expanded)
7760 heredoc = expanded;
7761 }
7762 len = strlen(heredoc);
7763
7764 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7765 xpiped_pair(pair);
7766 xmove_fd(pair.rd, redir->rd_fd);
7767
7768 /* Try writing without forking. Newer kernels have
7769 * dynamically growing pipes. Must use non-blocking write! */
7770 ndelay_on(pair.wr);
7771 while (1) {
7772 written = write(pair.wr, heredoc, len);
7773 if (written <= 0)
7774 break;
7775 len -= written;
7776 if (len == 0) {
7777 close(pair.wr);
7778 free(expanded);
7779 return;
7780 }
7781 heredoc += written;
7782 }
7783 ndelay_off(pair.wr);
7784
7785 /* Okay, pipe buffer was not big enough */
7786 /* Note: we must not create a stray child (bastard? :)
7787 * for the unsuspecting parent process. Child creates a grandchild
7788 * and exits before parent execs the process which consumes heredoc
7789 * (that exec happens after we return from this function) */
7790#if !BB_MMU
7791 to_free = NULL;
7792#endif
7793 pid = xvfork();
7794 if (pid == 0) {
7795 /* child */
7796 disable_restore_tty_pgrp_on_exit();
7797 pid = BB_MMU ? xfork() : xvfork();
7798 if (pid != 0)
7799 _exit(0);
7800 /* grandchild */
7801 close(redir->rd_fd); /* read side of the pipe */
7802#if BB_MMU
7803 full_write(pair.wr, heredoc, len); /* may loop or block */
7804 _exit(0);
7805#else
7806 /* Delegate blocking writes to another process */
7807 xmove_fd(pair.wr, STDOUT_FILENO);
7808 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7809#endif
7810 }
7811 /* parent */
7812#if ENABLE_HUSH_FAST
7813 G.count_SIGCHLD++;
7814//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7815#endif
7816 enable_restore_tty_pgrp_on_exit();
7817#if !BB_MMU
7818 free(to_free);
7819#endif
7820 close(pair.wr);
7821 free(expanded);
7822 wait(NULL); /* wait till child has died */
7823}
7824
Denys Vlasenko2db74612017-07-07 22:07:28 +02007825struct squirrel {
7826 int orig_fd;
7827 int moved_to;
7828 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7829 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7830};
7831
Denys Vlasenko621fc502017-07-24 12:42:17 +02007832static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7833{
7834 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7835 sq[i].orig_fd = orig;
7836 sq[i].moved_to = moved;
7837 sq[i+1].orig_fd = -1; /* end marker */
7838 return sq;
7839}
7840
Denys Vlasenko2db74612017-07-07 22:07:28 +02007841static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7842{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007843 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007844 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007845
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007846 i = 0;
7847 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007848 /* If we collide with an already moved fd... */
7849 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007850 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007851 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7852 if (sq[i].moved_to < 0) /* what? */
7853 xfunc_die();
7854 return sq;
7855 }
7856 if (fd == sq[i].orig_fd) {
7857 /* Example: echo Hello >/dev/null 1>&2 */
7858 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7859 return sq;
7860 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007861 }
7862
Denys Vlasenko2db74612017-07-07 22:07:28 +02007863 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007864 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007865 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7866 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007867 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007868 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007869}
7870
Denys Vlasenko657e9002017-07-30 23:34:04 +02007871static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7872{
7873 int i;
7874
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007875 i = 0;
7876 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007877 /* If we collide with an already moved fd... */
7878 if (fd == sq[i].orig_fd) {
7879 /* Examples:
7880 * "echo 3>FILE 3>&- 3>FILE"
7881 * "echo 3>&- 3>FILE"
7882 * No need for last redirect to insert
7883 * another "need to close 3" indicator.
7884 */
7885 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7886 return sq;
7887 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007888 }
7889
7890 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7891 return append_squirrel(sq, i, fd, -1);
7892}
7893
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007894/* fd: redirect wants this fd to be used (e.g. 3>file).
7895 * Move all conflicting internally used fds,
7896 * and remember them so that we can restore them later.
7897 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007898static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007899{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007900 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7901 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007902
7903#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko21806562019-11-01 14:16:07 +01007904 if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
7905 && fd == G_interactive_fd
7906 ) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007907 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007908 G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
7909 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007910 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007911 }
7912#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007913 /* Are we called from setup_redirects(squirrel==NULL)
7914 * in redirect in a [v]forked child?
7915 */
7916 if (sqp == NULL) {
7917 /* No need to move script fds.
7918 * For NOMMU case, it's actively wrong: we'd change ->fd
7919 * fields in memory for the parent, but parent's fds
Denys Vlasenko21806562019-11-01 14:16:07 +01007920 * aren't moved, it would use wrong fd!
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007921 * Reproducer: "cmd 3>FILE" in script.
7922 * If we would call move_HFILEs_on_redirect(), child would:
7923 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7924 * close(3) = 0
7925 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7926 */
7927 //bb_error_msg("sqp == NULL: [v]forked child");
7928 return 0;
7929 }
7930
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007931 /* If this one of script's fds? */
7932 if (move_HFILEs_on_redirect(fd, avoid_fd))
7933 return 1; /* yes. "we closed fd" (actually moved it) */
7934
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007935 /* Are we called for "exec 3>FILE"? Came through
7936 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7937 * This case used to fail for this script:
7938 * exec 3>FILE
7939 * echo Ok
7940 * ...100000 more lines...
7941 * echo Ok
7942 * as follows:
7943 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7944 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7945 * dup2(4, 3) = 3
7946 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7947 * close(4) = 0
7948 * write(1, "Ok\n", 3) = 3
7949 * ... = 3
7950 * write(1, "Ok\n", 3) = 3
7951 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7952 * ^^^^^^^^ oops, wrong fd!!!
7953 * With this case separate from sqp == NULL and *after* move_HFILEs,
7954 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007955 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007956 if (sqp == ERR_PTR) {
7957 /* Don't preserve redirected fds: exec is _meant_ to change these */
7958 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007959 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007960 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007961
Denys Vlasenko2db74612017-07-07 22:07:28 +02007962 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7963 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7964 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007965}
7966
Denys Vlasenko2db74612017-07-07 22:07:28 +02007967static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007968{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007969 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007970 int i;
7971 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007972 if (sq[i].moved_to >= 0) {
7973 /* We simply die on error */
7974 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7975 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7976 } else {
7977 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7978 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7979 close(sq[i].orig_fd);
7980 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007981 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007982 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007983 }
Denys Vlasenko21806562019-11-01 14:16:07 +01007984 if (G.HFILE_stdin
Denys Vlasenko1237d622020-12-25 19:01:49 +01007985 && G.HFILE_stdin->fd > STDIN_FILENO
7986 /* we compare > STDIN, not == STDIN, since hfgetc()
7987 * closes fd and sets ->fd to -1 if EOF is reached.
7988 * Testcase: echo 'pwd' | hush
7989 */
Denys Vlasenko21806562019-11-01 14:16:07 +01007990 ) {
7991 /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
7992 * Redirect moves ->fd to e.g. 10,
7993 * and it is not restored above (we do not restore script fds
7994 * after redirects, we just use new, "moved" fds).
7995 * However for stdin, get_user_input() -> read_line_input(),
7996 * and read builtin, depend on fd == STDIN_FILENO.
7997 */
7998 debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
7999 xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
8000 G.HFILE_stdin->fd = STDIN_FILENO;
8001 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02008002
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02008003 /* If moved, G_interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02008004}
8005
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008006#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008007static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008008{
8009 if (G_interactive_fd)
8010 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008011 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008012}
8013#endif
8014
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02008015static int internally_opened_fd(int fd, struct squirrel *sq)
8016{
8017 int i;
8018
8019#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02008020 if (fd == G_interactive_fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02008021 return 1;
8022#endif
8023 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008024 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02008025 return 1;
8026
8027 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
8028 if (fd == sq[i].moved_to)
8029 return 1;
8030 }
8031 return 0;
8032}
8033
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008034/* squirrel != NULL means we squirrel away copies of stdin, stdout,
8035 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008036static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008037{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008038 struct redir_struct *redir;
8039
8040 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02008041 int newfd;
8042 int closed;
8043
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008044 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02008045 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02008046 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008047 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
8048 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008049 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008050 redir->rd_filename);
8051 setup_heredoc(redir);
8052 continue;
8053 }
8054
8055 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02008056 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008057 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02008058 int mode;
8059
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008060 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008061 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02008062 * "cmd >" (no filename)
8063 * "cmd > <file" (2nd redirect starts too early)
8064 */
Denys Vlasenko39701202017-08-02 19:44:05 +02008065 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008066 continue;
8067 }
8068 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02008069 p = expand_string_to_string(redir->rd_filename,
8070 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02008071 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008072 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02008073 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02008074 /* Error message from open_or_warn can be lost
8075 * if stderr has been redirected, but bash
8076 * and ash both lose it as well
8077 * (though zsh doesn't!)
8078 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008079 return 1;
8080 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02008081 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02008082 /* open() gave us precisely the fd we wanted.
8083 * This means that this fd was not busy
8084 * (not opened to anywhere).
8085 * Remember to close it on restore:
8086 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02008087 *sqp = add_squirrel_closed(*sqp, newfd);
8088 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02008089 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008090 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02008091 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
8092 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008093 }
8094
Denys Vlasenko657e9002017-07-30 23:34:04 +02008095 if (newfd == redir->rd_fd)
8096 continue;
8097
8098 /* if "N>FILE": move newfd to redir->rd_fd */
8099 /* if "N>&M": dup newfd to redir->rd_fd */
8100 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
8101
8102 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
8103 if (newfd == REDIRFD_CLOSE) {
8104 /* "N>&-" means "close me" */
8105 if (!closed) {
8106 /* ^^^ optimization: saving may already
8107 * have closed it. If not... */
8108 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008109 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02008110 /* Sometimes we do another close on restore, getting EBADF.
8111 * Consider "echo 3>FILE 3>&-"
8112 * first redirect remembers "need to close 3",
8113 * and second redirect closes 3! Restore code then closes 3 again.
8114 */
8115 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02008116 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008117 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02008118 //errno = EBADF;
8119 //bb_perror_msg_and_die("can't duplicate file descriptor");
8120 newfd = -1; /* same effect as code above */
8121 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02008122 xdup2(newfd, redir->rd_fd);
8123 if (redir->rd_dup == REDIRFD_TO_FILE)
8124 /* "rd_fd > FILE" */
8125 close(newfd);
8126 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008127 }
8128 }
8129 return 0;
8130}
8131
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008132static char *find_in_path(const char *arg)
8133{
8134 char *ret = NULL;
8135 const char *PATH = get_local_var_value("PATH");
8136
8137 if (!PATH)
8138 return NULL;
8139
8140 while (1) {
8141 const char *end = strchrnul(PATH, ':');
8142 int sz = end - PATH; /* must be int! */
8143
8144 free(ret);
8145 if (sz != 0) {
8146 ret = xasprintf("%.*s/%s", sz, PATH, arg);
8147 } else {
8148 /* We have xxx::yyyy in $PATH,
8149 * it means "use current dir" */
8150 ret = xstrdup(arg);
8151 }
8152 if (access(ret, F_OK) == 0)
8153 break;
8154
8155 if (*end == '\0') {
8156 free(ret);
8157 return NULL;
8158 }
8159 PATH = end + 1;
8160 }
8161
8162 return ret;
8163}
8164
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008165static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008166 const struct built_in_command *x,
8167 const struct built_in_command *end)
8168{
8169 while (x != end) {
8170 if (strcmp(name, x->b_cmd) != 0) {
8171 x++;
8172 continue;
8173 }
8174 debug_printf_exec("found builtin '%s'\n", name);
8175 return x;
8176 }
8177 return NULL;
8178}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008179static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008180{
8181 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
8182}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008183static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008184{
8185 const struct built_in_command *x = find_builtin1(name);
8186 if (x)
8187 return x;
8188 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
8189}
8190
Ron Yorston7d1c7d82022-03-24 12:17:25 +00008191#if ENABLE_HUSH_JOB && ENABLE_FEATURE_EDITING
Ron Yorston9e2a5662020-01-21 16:01:58 +00008192static const char * FAST_FUNC get_builtin_name(int i)
8193{
8194 if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
8195 return bltins1[i].b_cmd;
8196 }
8197 i -= ARRAY_SIZE(bltins1);
8198 if (i < ARRAY_SIZE(bltins2)) {
8199 return bltins2[i].b_cmd;
8200 }
8201 return NULL;
8202}
8203#endif
8204
Denys Vlasenko99496dc2018-06-26 15:36:58 +02008205static void remove_nested_vars(void)
8206{
8207 struct variable *cur;
8208 struct variable **cur_pp;
8209
8210 cur_pp = &G.top_var;
8211 while ((cur = *cur_pp) != NULL) {
8212 if (cur->var_nest_level <= G.var_nest_level) {
8213 cur_pp = &cur->next;
8214 continue;
8215 }
8216 /* Unexport */
8217 if (cur->flg_export) {
8218 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
8219 bb_unsetenv(cur->varstr);
8220 }
8221 /* Remove from global list */
8222 *cur_pp = cur->next;
8223 /* Free */
8224 if (!cur->max_len) {
8225 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
8226 free(cur->varstr);
8227 }
8228 free(cur);
8229 }
8230}
8231
8232static void enter_var_nest_level(void)
8233{
8234 G.var_nest_level++;
8235 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
8236
8237 /* Try: f() { echo -n .; f; }; f
8238 * struct variable::var_nest_level is uint16_t,
8239 * thus limiting recursion to < 2^16.
8240 * In any case, with 8 Mbyte stack SEGV happens
8241 * not too long after 2^16 recursions anyway.
8242 */
8243 if (G.var_nest_level > 0xff00)
8244 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
8245}
8246
8247static void leave_var_nest_level(void)
8248{
8249 G.var_nest_level--;
8250 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
8251 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
James Byrne69374872019-07-02 11:35:03 +02008252 bb_simple_error_msg_and_die("BUG: nesting underflow");
Denys Vlasenko99496dc2018-06-26 15:36:58 +02008253
8254 remove_nested_vars();
8255}
8256
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008257#if ENABLE_HUSH_FUNCTIONS
8258static struct function **find_function_slot(const char *name)
8259{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008260 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008261 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008262
8263 while ((funcp = *funcpp) != NULL) {
8264 if (strcmp(name, funcp->name) == 0) {
8265 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008266 break;
8267 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008268 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008269 }
8270 return funcpp;
8271}
8272
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008273static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008274{
8275 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008276 return funcp;
8277}
8278
8279/* Note: takes ownership on name ptr */
8280static struct function *new_function(char *name)
8281{
8282 struct function **funcpp = find_function_slot(name);
8283 struct function *funcp = *funcpp;
8284
8285 if (funcp != NULL) {
8286 struct command *cmd = funcp->parent_cmd;
8287 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
8288 if (!cmd) {
8289 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
8290 free(funcp->name);
8291 /* Note: if !funcp->body, do not free body_as_string!
8292 * This is a special case of "-F name body" function:
8293 * body_as_string was not malloced! */
8294 if (funcp->body) {
8295 free_pipe_list(funcp->body);
8296# if !BB_MMU
8297 free(funcp->body_as_string);
8298# endif
8299 }
8300 } else {
8301 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
8302 cmd->argv[0] = funcp->name;
8303 cmd->group = funcp->body;
8304# if !BB_MMU
8305 cmd->group_as_string = funcp->body_as_string;
8306# endif
8307 }
8308 } else {
8309 debug_printf_exec("remembering new function '%s'\n", name);
8310 funcp = *funcpp = xzalloc(sizeof(*funcp));
8311 /*funcp->next = NULL;*/
8312 }
8313
8314 funcp->name = name;
8315 return funcp;
8316}
8317
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008318# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008319static void unset_func(const char *name)
8320{
8321 struct function **funcpp = find_function_slot(name);
8322 struct function *funcp = *funcpp;
8323
8324 if (funcp != NULL) {
8325 debug_printf_exec("freeing function '%s'\n", funcp->name);
8326 *funcpp = funcp->next;
8327 /* funcp is unlinked now, deleting it.
8328 * Note: if !funcp->body, the function was created by
8329 * "-F name body", do not free ->body_as_string
8330 * and ->name as they were not malloced. */
8331 if (funcp->body) {
8332 free_pipe_list(funcp->body);
8333 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008334# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008335 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008336# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008337 }
8338 free(funcp);
8339 }
8340}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008341# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008342
8343# if BB_MMU
8344#define exec_function(to_free, funcp, argv) \
8345 exec_function(funcp, argv)
8346# endif
8347static void exec_function(char ***to_free,
8348 const struct function *funcp,
8349 char **argv) NORETURN;
8350static void exec_function(char ***to_free,
8351 const struct function *funcp,
8352 char **argv)
8353{
8354# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008355 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008356
8357 argv[0] = G.global_argv[0];
8358 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008359 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008360
8361// Example when we are here: "cmd | func"
8362// func will run with saved-redirect fds open.
8363// $ f() { echo /proc/self/fd/*; }
8364// $ true | f
8365// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8366// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8367// Same in script:
8368// $ . ./SCRIPT
8369// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8370// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8371// They are CLOEXEC so external programs won't see them, but
8372// for "more correctness" we might want to close those extra fds here:
8373//? close_saved_fds_and_FILE_fds();
8374
Denys Vlasenko332e4112018-04-04 22:32:59 +02008375 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008376 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008377 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008378 IF_HUSH_LOCAL(G.func_nest_level++;)
8379
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008380 /* On MMU, funcp->body is always non-NULL */
8381 n = run_list(funcp->body);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008382 _exit(n);
8383# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008384//? close_saved_fds_and_FILE_fds();
8385
8386//TODO: check whether "true | func_with_return" works
8387
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008388 re_execute_shell(to_free,
8389 funcp->body_as_string,
8390 G.global_argv[0],
8391 argv + 1,
8392 NULL);
8393# endif
8394}
8395
8396static int run_function(const struct function *funcp, char **argv)
8397{
8398 int rc;
8399 save_arg_t sv;
8400 smallint sv_flg;
8401
8402 save_and_replace_G_args(&sv, argv);
8403
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008404 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008405 sv_flg = G_flag_return_in_progress;
8406 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008407
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008408 /* Make "local" variables properly shadow previous ones */
8409 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008410 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008411
8412 /* On MMU, funcp->body is always non-NULL */
8413# if !BB_MMU
8414 if (!funcp->body) {
8415 /* Function defined by -F */
8416 parse_and_run_string(funcp->body_as_string);
8417 rc = G.last_exitcode;
8418 } else
8419# endif
8420 {
8421 rc = run_list(funcp->body);
8422 }
8423
Denys Vlasenko332e4112018-04-04 22:32:59 +02008424 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008425 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008426
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008427 G_flag_return_in_progress = sv_flg;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01008428# if ENABLE_HUSH_TRAP
8429 debug_printf_exec("G.return_exitcode=-1\n");
8430 G.return_exitcode = -1; /* invalidate stashed return value */
8431# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008432
8433 restore_G_args(&sv, argv);
8434
8435 return rc;
8436}
8437#endif /* ENABLE_HUSH_FUNCTIONS */
8438
8439
8440#if BB_MMU
8441#define exec_builtin(to_free, x, argv) \
8442 exec_builtin(x, argv)
8443#else
8444#define exec_builtin(to_free, x, argv) \
8445 exec_builtin(to_free, argv)
8446#endif
8447static void exec_builtin(char ***to_free,
8448 const struct built_in_command *x,
8449 char **argv) NORETURN;
8450static void exec_builtin(char ***to_free,
8451 const struct built_in_command *x,
8452 char **argv)
8453{
8454#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008455 int rcode;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008456//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008457 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008458 fflush_all();
8459 _exit(rcode);
8460#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008461 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008462 /* On NOMMU, we must never block!
8463 * Example: { sleep 99 | read line; } & echo Ok
8464 */
8465 re_execute_shell(to_free,
8466 argv[0],
8467 G.global_argv[0],
8468 G.global_argv + 1,
8469 argv);
8470#endif
8471}
8472
8473
8474static void execvp_or_die(char **argv) NORETURN;
8475static void execvp_or_die(char **argv)
8476{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008477 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008478 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008479 /* Don't propagate SIG_IGN to the child */
8480 if (SPECIAL_JOBSTOP_SIGS != 0)
8481 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008482 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008483 e = 2;
8484 if (errno == EACCES) e = 126;
8485 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008486 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008487 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008488}
8489
8490#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008491static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008492{
8493 unsigned len;
8494 const char *cp;
8495
8496 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008497
8498 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8499 /* test a char with: bash -c 'set -x; echo "CH"' */
8500 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8501 " " "\001\002\003\004\005\006\007"
8502 "\010\011\012\013\014\015\016\017"
8503 "\020\021\022\023\024\025\026\027"
8504 "\030\031\032\033\034\035\036\037"
8505 )
8506 ] == '\0'
8507 ) {
8508 /* string has no special chars */
8509 x_mode_addstr(str);
8510 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008511 }
8512
8513 cp = str;
8514 for (;;) {
8515 /* print '....' up to EOL or first squote */
8516 len = (int)(strchrnul(cp, '\'') - cp);
8517 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008518 x_mode_addchr('\'');
8519 x_mode_addblock(cp, len);
8520 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008521 cp += len;
8522 }
8523 if (*cp == '\0')
8524 break;
8525 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008526 x_mode_addchr('\\');
8527 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008528 cp++;
8529 }
8530}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008531static void dump_cmd_in_x_mode(char **argv)
8532{
8533 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008534 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008535
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008536 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008537 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008538 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008539 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008540 x_mode_addchr(' ');
8541 if (argv[n][0] == '\0') {
8542 x_mode_addchr('\'');
8543 x_mode_addchr('\'');
8544 } else {
8545 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008546 }
8547 n++;
8548 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008549 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008550 }
8551}
8552#else
8553# define dump_cmd_in_x_mode(argv) ((void)0)
8554#endif
8555
Denys Vlasenko57000292018-01-12 14:41:45 +01008556#if ENABLE_HUSH_COMMAND
8557static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8558{
8559 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008560
Denys Vlasenko57000292018-01-12 14:41:45 +01008561 if (!opt_vV)
8562 return;
8563
8564 to_free = NULL;
8565 if (!explanation) {
8566 char *path = getenv("PATH");
8567 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008568 if (!explanation)
8569 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008570 if (opt_vV != 'V')
8571 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8572 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008573 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008574 free(to_free);
8575 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008576 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008577}
8578#else
8579# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8580#endif
8581
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008582#if BB_MMU
8583#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8584 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8585#define pseudo_exec(nommu_save, command, argv_expanded) \
8586 pseudo_exec(command, argv_expanded)
8587#endif
8588
8589/* Called after [v]fork() in run_pipe, or from builtin_exec.
8590 * Never returns.
8591 * Don't exit() here. If you don't exec, use _exit instead.
8592 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008593 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008594 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008595static void pseudo_exec_argv(nommu_save_t *nommu_save,
8596 char **argv, int assignment_cnt,
8597 char **argv_expanded) NORETURN;
8598static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8599 char **argv, int assignment_cnt,
8600 char **argv_expanded)
8601{
Denys Vlasenko57000292018-01-12 14:41:45 +01008602 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008603 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008604 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008605 IF_HUSH_COMMAND(char opt_vV = 0;)
8606 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008607
8608 new_env = expand_assignments(argv, assignment_cnt);
8609 dump_cmd_in_x_mode(new_env);
8610
8611 if (!argv[assignment_cnt]) {
8612 /* Case when we are here: ... | var=val | ...
8613 * (note that we do not exit early, i.e., do not optimize out
8614 * expand_assignments(): think about ... | var=`sleep 1` | ...
8615 */
8616 free_strings(new_env);
Denys Vlasenkodb5546c2022-01-05 22:16:06 +01008617 _exit_SUCCESS();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008618 }
8619
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008620 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008621#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008622 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008623#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008624 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008625 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008626#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008627 set_vars_and_save_old(new_env);
8628 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008629
8630 if (argv_expanded) {
8631 argv = argv_expanded;
8632 } else {
8633 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8634#if !BB_MMU
8635 nommu_save->argv = argv;
8636#endif
8637 }
8638 dump_cmd_in_x_mode(argv);
8639
8640#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8641 if (strchr(argv[0], '/') != NULL)
8642 goto skip;
8643#endif
8644
Denys Vlasenko75481d32017-07-31 05:27:09 +02008645#if ENABLE_HUSH_FUNCTIONS
8646 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008647 funcp = find_function(argv[0]);
8648 if (funcp)
8649 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008650#endif
8651
Denys Vlasenko57000292018-01-12 14:41:45 +01008652#if ENABLE_HUSH_COMMAND
8653 /* "command BAR": run BAR without looking it up among functions
8654 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8655 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8656 */
8657 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8658 char *p;
8659
8660 argv++;
8661 p = *argv;
8662 if (p[0] != '-' || !p[1])
8663 continue; /* bash allows "command command command [-OPT] BAR" */
8664
8665 for (;;) {
8666 p++;
8667 switch (*p) {
8668 case '\0':
8669 argv++;
8670 p = *argv;
8671 if (p[0] != '-' || !p[1])
8672 goto after_opts;
8673 continue; /* next arg is also -opts, process it too */
8674 case 'v':
8675 case 'V':
8676 opt_vV = *p;
8677 continue;
8678 default:
8679 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8680 }
8681 }
8682 }
8683 after_opts:
8684# if ENABLE_HUSH_FUNCTIONS
8685 if (opt_vV && find_function(argv[0]))
8686 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8687# endif
8688#endif
8689
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008690 /* Check if the command matches any of the builtins.
8691 * Depending on context, this might be redundant. But it's
8692 * easier to waste a few CPU cycles than it is to figure out
8693 * if this is one of those cases.
8694 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008695 /* Why "BB_MMU ? :" difference in logic? -
8696 * On NOMMU, it is more expensive to re-execute shell
8697 * just in order to run echo or test builtin.
8698 * It's better to skip it here and run corresponding
8699 * non-builtin later. */
8700 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8701 if (x) {
8702 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8703 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008704 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008705
8706#if ENABLE_FEATURE_SH_STANDALONE
8707 /* Check if the command matches any busybox applets */
8708 {
8709 int a = find_applet_by_name(argv[0]);
8710 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008711 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008712# if BB_MMU /* see above why on NOMMU it is not allowed */
8713 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008714 /* Do not leak open fds from opened script files etc.
8715 * Testcase: interactive "ls -l /proc/self/fd"
8716 * should not show tty fd open.
8717 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008718 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008719//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008720//This casuses test failures in
8721//redir_children_should_not_see_saved_fd_2.tests
8722//redir_children_should_not_see_saved_fd_3.tests
8723//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008724 /* Without this, "rm -i FILE" can't be ^C'ed: */
8725 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008726 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008727 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008728 }
8729# endif
8730 /* Re-exec ourselves */
8731 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008732 /* Don't propagate SIG_IGN to the child */
8733 if (SPECIAL_JOBSTOP_SIGS != 0)
8734 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008735 execv(bb_busybox_exec_path, argv);
8736 /* If they called chroot or otherwise made the binary no longer
8737 * executable, fall through */
8738 }
8739 }
8740#endif
8741
8742#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8743 skip:
8744#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008745 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008746 execvp_or_die(argv);
8747}
8748
8749/* Called after [v]fork() in run_pipe
8750 */
8751static void pseudo_exec(nommu_save_t *nommu_save,
8752 struct command *command,
8753 char **argv_expanded) NORETURN;
8754static void pseudo_exec(nommu_save_t *nommu_save,
8755 struct command *command,
8756 char **argv_expanded)
8757{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008758#if ENABLE_HUSH_FUNCTIONS
8759 if (command->cmd_type == CMD_FUNCDEF) {
8760 /* Ignore funcdefs in pipes:
8761 * true | f() { cmd }
8762 */
8763 _exit(0);
8764 }
8765#endif
8766
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008767 if (command->argv) {
8768 pseudo_exec_argv(nommu_save, command->argv,
8769 command->assignment_cnt, argv_expanded);
8770 }
8771
8772 if (command->group) {
8773 /* Cases when we are here:
8774 * ( list )
8775 * { list } &
8776 * ... | ( list ) | ...
8777 * ... | { list } | ...
8778 */
8779#if BB_MMU
8780 int rcode;
8781 debug_printf_exec("pseudo_exec: run_list\n");
8782 reset_traps_to_defaults();
8783 rcode = run_list(command->group);
8784 /* OK to leak memory by not calling free_pipe_list,
8785 * since this process is about to exit */
8786 _exit(rcode);
8787#else
8788 re_execute_shell(&nommu_save->argv_from_re_execing,
8789 command->group_as_string,
8790 G.global_argv[0],
8791 G.global_argv + 1,
8792 NULL);
8793#endif
8794 }
8795
8796 /* Case when we are here: ... | >file */
8797 debug_printf_exec("pseudo_exec'ed null command\n");
Denys Vlasenkodb5546c2022-01-05 22:16:06 +01008798 _exit_SUCCESS();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008799}
8800
8801#if ENABLE_HUSH_JOB
8802static const char *get_cmdtext(struct pipe *pi)
8803{
8804 char **argv;
8805 char *p;
8806 int len;
8807
8808 /* This is subtle. ->cmdtext is created only on first backgrounding.
8809 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8810 * On subsequent bg argv is trashed, but we won't use it */
8811 if (pi->cmdtext)
8812 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008813
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008814 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008815 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008816 pi->cmdtext = xzalloc(1);
8817 return pi->cmdtext;
8818 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008819 len = 0;
8820 do {
8821 len += strlen(*argv) + 1;
8822 } while (*++argv);
8823 p = xmalloc(len);
8824 pi->cmdtext = p;
8825 argv = pi->cmds[0].argv;
8826 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008827 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008828 *p++ = ' ';
8829 } while (*++argv);
8830 p[-1] = '\0';
8831 return pi->cmdtext;
8832}
8833
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008834static void remove_job_from_table(struct pipe *pi)
8835{
8836 struct pipe *prev_pipe;
8837
8838 if (pi == G.job_list) {
8839 G.job_list = pi->next;
8840 } else {
8841 prev_pipe = G.job_list;
8842 while (prev_pipe->next != pi)
8843 prev_pipe = prev_pipe->next;
8844 prev_pipe->next = pi->next;
8845 }
8846 G.last_jobid = 0;
8847 if (G.job_list)
8848 G.last_jobid = G.job_list->jobid;
8849}
8850
8851static void delete_finished_job(struct pipe *pi)
8852{
8853 remove_job_from_table(pi);
8854 free_pipe(pi);
8855}
8856
8857static void clean_up_last_dead_job(void)
8858{
8859 if (G.job_list && !G.job_list->alive_cmds)
8860 delete_finished_job(G.job_list);
8861}
8862
Denys Vlasenko16096292017-07-10 10:00:28 +02008863static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008864{
8865 struct pipe *job, **jobp;
8866 int i;
8867
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008868 clean_up_last_dead_job();
8869
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008870 /* Find the end of the list, and find next job ID to use */
8871 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008872 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008873 while ((job = *jobp) != NULL) {
8874 if (job->jobid > i)
8875 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008876 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008877 }
8878 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008879
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008880 /* Create a new job struct at the end */
8881 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008882 job->next = NULL;
8883 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8884 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8885 for (i = 0; i < pi->num_cmds; i++) {
8886 job->cmds[i].pid = pi->cmds[i].pid;
8887 /* all other fields are not used and stay zero */
8888 }
8889 job->cmdtext = xstrdup(get_cmdtext(pi));
8890
8891 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008892 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008893 G.last_jobid = job->jobid;
8894}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008895#endif /* JOB */
8896
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008897static int job_exited_or_stopped(struct pipe *pi)
8898{
8899 int rcode, i;
8900
8901 if (pi->alive_cmds != pi->stopped_cmds)
8902 return -1;
8903
8904 /* All processes in fg pipe have exited or stopped */
8905 rcode = 0;
8906 i = pi->num_cmds;
8907 while (--i >= 0) {
8908 rcode = pi->cmds[i].cmd_exitcode;
8909 /* usually last process gives overall exitstatus,
8910 * but with "set -o pipefail", last *failed* process does */
8911 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8912 break;
8913 }
8914 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8915 return rcode;
8916}
8917
Denys Vlasenko7e675362016-10-28 21:57:31 +02008918static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008919{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008920#if ENABLE_HUSH_JOB
8921 struct pipe *pi;
8922#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008923 int i, dead;
8924
8925 dead = WIFEXITED(status) || WIFSIGNALED(status);
8926
8927#if DEBUG_JOBS
8928 if (WIFSTOPPED(status))
8929 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8930 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8931 if (WIFSIGNALED(status))
8932 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8933 childpid, WTERMSIG(status), WEXITSTATUS(status));
8934 if (WIFEXITED(status))
8935 debug_printf_jobs("pid %d exited, exitcode %d\n",
8936 childpid, WEXITSTATUS(status));
8937#endif
8938 /* Were we asked to wait for a fg pipe? */
8939 if (fg_pipe) {
8940 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008941
Denys Vlasenko7e675362016-10-28 21:57:31 +02008942 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008943 int rcode;
8944
Denys Vlasenko7e675362016-10-28 21:57:31 +02008945 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8946 if (fg_pipe->cmds[i].pid != childpid)
8947 continue;
8948 if (dead) {
8949 int ex;
8950 fg_pipe->cmds[i].pid = 0;
8951 fg_pipe->alive_cmds--;
8952 ex = WEXITSTATUS(status);
8953 /* bash prints killer signal's name for *last*
8954 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8955 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8956 */
8957 if (WIFSIGNALED(status)) {
8958 int sig = WTERMSIG(status);
Denys Vlasenko77a51a22020-12-29 16:53:11 +01008959#if ENABLE_HUSH_JOB
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008960 if (G.run_list_level == 1
8961 /* ^^^^^ Do not print in nested contexts, example:
8962 * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
8963 */
8964 && i == fg_pipe->num_cmds-1
8965 ) {
Denys Vlasenkoe16f7eb2020-10-24 04:26:43 +02008966 /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
8967 puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008968 }
Denys Vlasenko77a51a22020-12-29 16:53:11 +01008969#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008970 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko93e2a222020-12-23 12:23:21 +01008971 /* MIPS has 128 sigs (1..128), if sig==128,
8972 * 128 + sig would result in exitcode 256 -> 0!
8973 */
8974 ex = 128 | sig;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008975 }
8976 fg_pipe->cmds[i].cmd_exitcode = ex;
8977 } else {
8978 fg_pipe->stopped_cmds++;
8979 }
8980 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8981 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008982 rcode = job_exited_or_stopped(fg_pipe);
8983 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008984/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8985 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8986 * and "killall -STOP cat" */
8987 if (G_interactive_fd) {
8988#if ENABLE_HUSH_JOB
8989 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008990 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008991#endif
8992 return rcode;
8993 }
8994 if (fg_pipe->alive_cmds == 0)
8995 return rcode;
8996 }
8997 /* There are still running processes in the fg_pipe */
8998 return -1;
8999 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02009000 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009001 }
9002
9003#if ENABLE_HUSH_JOB
9004 /* We were asked to wait for bg or orphaned children */
9005 /* No need to remember exitcode in this case */
9006 for (pi = G.job_list; pi; pi = pi->next) {
9007 for (i = 0; i < pi->num_cmds; i++) {
9008 if (pi->cmds[i].pid == childpid)
9009 goto found_pi_and_prognum;
9010 }
9011 }
9012 /* Happens when shell is used as init process (init=/bin/sh) */
9013 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
9014 return -1; /* this wasn't a process from fg_pipe */
9015
9016 found_pi_and_prognum:
9017 if (dead) {
9018 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02009019 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009020 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009021 /* NB: not 128 + sig, MIPS has sig 128 */
9022 rcode = 128 | WTERMSIG(status);
Denys Vlasenko840a4352017-07-07 22:56:02 +02009023 pi->cmds[i].cmd_exitcode = rcode;
9024 if (G.last_bg_pid == pi->cmds[i].pid)
9025 G.last_bg_pid_exitcode = rcode;
9026 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02009027 pi->alive_cmds--;
9028 if (!pi->alive_cmds) {
Denys Vlasenko259747c2019-11-28 10:28:14 +01009029# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01009030 G.dead_job_exitcode = job_exited_or_stopped(pi);
Denys Vlasenko259747c2019-11-28 10:28:14 +01009031# endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02009032 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009033 printf(JOB_STATUS_FORMAT, pi->jobid,
9034 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02009035 delete_finished_job(pi);
9036 } else {
9037/*
9038 * bash deletes finished jobs from job table only in interactive mode,
9039 * after "jobs" cmd, or if pid of a new process matches one of the old ones
9040 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
9041 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
9042 * We only retain one "dead" job, if it's the single job on the list.
9043 * This covers most of real-world scenarios where this is useful.
9044 */
9045 if (pi != G.job_list)
9046 delete_finished_job(pi);
9047 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009048 }
9049 } else {
9050 /* child stopped */
9051 pi->stopped_cmds++;
9052 }
9053#endif
9054 return -1; /* this wasn't a process from fg_pipe */
9055}
9056
9057/* Check to see if any processes have exited -- if they have,
9058 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009059 *
9060 * If non-NULL fg_pipe: wait for its completion or stop.
9061 * Return its exitcode or zero if stopped.
9062 *
9063 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
9064 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
9065 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
9066 * or 0 if no children changed status.
9067 *
9068 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
9069 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
9070 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02009071 */
9072static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
9073{
9074 int attributes;
9075 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009076 int rcode = 0;
9077
9078 debug_printf_jobs("checkjobs %p\n", fg_pipe);
9079
9080 attributes = WUNTRACED;
9081 if (fg_pipe == NULL)
9082 attributes |= WNOHANG;
9083
9084 errno = 0;
9085#if ENABLE_HUSH_FAST
9086 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
9087//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
9088//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
9089 /* There was neither fork nor SIGCHLD since last waitpid */
9090 /* Avoid doing waitpid syscall if possible */
9091 if (!G.we_have_children) {
9092 errno = ECHILD;
9093 return -1;
9094 }
9095 if (fg_pipe == NULL) { /* is WNOHANG set? */
9096 /* We have children, but they did not exit
9097 * or stop yet (we saw no SIGCHLD) */
9098 return 0;
9099 }
9100 /* else: !WNOHANG, waitpid will block, can't short-circuit */
9101 }
9102#endif
9103
9104/* Do we do this right?
9105 * bash-3.00# sleep 20 | false
9106 * <ctrl-Z pressed>
9107 * [3]+ Stopped sleep 20 | false
9108 * bash-3.00# echo $?
9109 * 1 <========== bg pipe is not fully done, but exitcode is already known!
9110 * [hush 1.14.0: yes we do it right]
9111 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009112 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009113 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009114#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02009115 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009116 i = G.count_SIGCHLD;
9117#endif
9118 childpid = waitpid(-1, &status, attributes);
9119 if (childpid <= 0) {
9120 if (childpid && errno != ECHILD)
James Byrne69374872019-07-02 11:35:03 +02009121 bb_simple_perror_msg("waitpid");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009122#if ENABLE_HUSH_FAST
9123 else { /* Until next SIGCHLD, waitpid's are useless */
9124 G.we_have_children = (childpid == 0);
9125 G.handled_SIGCHLD = i;
9126//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9127 }
9128#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009129 /* ECHILD (no children), or 0 (no change in children status) */
9130 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009131 break;
9132 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009133 rcode = process_wait_result(fg_pipe, childpid, status);
9134 if (rcode >= 0) {
9135 /* fg_pipe exited or stopped */
9136 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009137 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01009138 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009139 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009140 rcode = WEXITSTATUS(status);
9141 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009142 rcode = 128 | WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009143 if (WIFSTOPPED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009144 /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
9145 rcode = 128 | WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009146 rcode++;
9147 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009148 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01009149#if ENABLE_HUSH_BASH_COMPAT
9150 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
9151 && G.dead_job_exitcode >= 0 /* some job did finish */
9152 ) {
9153 debug_printf_exec("waitfor_pid:-1\n");
9154 rcode = G.dead_job_exitcode + 1;
9155 break;
9156 }
9157#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009158 /* This wasn't one of our processes, or */
9159 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009160 } /* while (waitpid succeeds)... */
9161
9162 return rcode;
9163}
9164
9165#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02009166static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009167{
9168 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02009169 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009170 if (G_saved_tty_pgrp) {
9171 /* Job finished, move the shell to the foreground */
9172 p = getpgrp(); /* our process group id */
9173 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
9174 tcsetpgrp(G_interactive_fd, p);
9175 }
9176 return rcode;
9177}
9178#endif
9179
9180/* Start all the jobs, but don't wait for anything to finish.
9181 * See checkjobs().
9182 *
9183 * Return code is normally -1, when the caller has to wait for children
9184 * to finish to determine the exit status of the pipe. If the pipe
9185 * is a simple builtin command, however, the action is done by the
9186 * time run_pipe returns, and the exit code is provided as the
9187 * return value.
9188 *
9189 * Returns -1 only if started some children. IOW: we have to
9190 * mask out retvals of builtins etc with 0xff!
9191 *
9192 * The only case when we do not need to [v]fork is when the pipe
9193 * is single, non-backgrounded, non-subshell command. Examples:
9194 * cmd ; ... { list } ; ...
9195 * cmd && ... { list } && ...
9196 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01009197 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009198 * or (if SH_STANDALONE) an applet, and we can run the { list }
9199 * with run_list. If it isn't one of these, we fork and exec cmd.
9200 *
9201 * Cases when we must fork:
9202 * non-single: cmd | cmd
9203 * backgrounded: cmd & { list } &
9204 * subshell: ( list ) [&]
9205 */
9206#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009207#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
9208 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009209#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009210static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009211 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02009212 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009213 char **argv_expanded)
9214{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009215 /* Assignments occur before redirects. Try:
9216 * a=`sleep 1` sleep 2 3>/qwe/rty
9217 */
9218
9219 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
9220 dump_cmd_in_x_mode(new_env);
9221 dump_cmd_in_x_mode(argv_expanded);
9222 /* this takes ownership of new_env[i] elements, and frees new_env: */
9223 set_vars_and_save_old(new_env);
9224
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009225 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009226}
9227static NOINLINE int run_pipe(struct pipe *pi)
9228{
9229 static const char *const null_ptr = NULL;
9230
9231 int cmd_no;
9232 int next_infd;
9233 struct command *command;
9234 char **argv_expanded;
9235 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02009236 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009237 int rcode;
9238
9239 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
9240 debug_enter();
9241
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009242 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
9243 * Result should be 3 lines: q w e, qwe, q w e
9244 */
Denys Vlasenko96786362018-04-11 16:02:58 +02009245 if (G.ifs_whitespace != G.ifs)
9246 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009247 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02009248 if (G.ifs) {
9249 char *p;
9250 G.ifs_whitespace = (char*)G.ifs;
9251 p = skip_whitespace(G.ifs);
9252 if (*p) {
9253 /* Not all $IFS is whitespace */
9254 char *d;
9255 int len = p - G.ifs;
9256 p = skip_non_whitespace(p);
9257 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
9258 d = mempcpy(G.ifs_whitespace, G.ifs, len);
9259 while (*p) {
9260 if (isspace(*p))
9261 *d++ = *p;
9262 p++;
9263 }
9264 *d = '\0';
9265 }
9266 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009267 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02009268 G.ifs_whitespace = (char*)G.ifs;
9269 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009270
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009271 IF_HUSH_JOB(pi->pgrp = -1;)
9272 pi->stopped_cmds = 0;
9273 command = &pi->cmds[0];
9274 argv_expanded = NULL;
9275
9276 if (pi->num_cmds != 1
9277 || pi->followup == PIPE_BG
9278 || command->cmd_type == CMD_SUBSHELL
9279 ) {
9280 goto must_fork;
9281 }
9282
9283 pi->alive_cmds = 1;
9284
9285 debug_printf_exec(": group:%p argv:'%s'\n",
9286 command->group, command->argv ? command->argv[0] : "NONE");
9287
9288 if (command->group) {
9289#if ENABLE_HUSH_FUNCTIONS
9290 if (command->cmd_type == CMD_FUNCDEF) {
9291 /* "executing" func () { list } */
9292 struct function *funcp;
9293
9294 funcp = new_function(command->argv[0]);
9295 /* funcp->name is already set to argv[0] */
9296 funcp->body = command->group;
9297# if !BB_MMU
9298 funcp->body_as_string = command->group_as_string;
9299 command->group_as_string = NULL;
9300# endif
9301 command->group = NULL;
9302 command->argv[0] = NULL;
9303 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
9304 funcp->parent_cmd = command;
9305 command->child_func = funcp;
9306
9307 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
9308 debug_leave();
9309 return EXIT_SUCCESS;
9310 }
9311#endif
9312 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009313 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009314 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009315 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009316 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02009317//FIXME: we need to pass squirrel down into run_list()
9318//for SH_STANDALONE case, or else this construct:
9319// { find /proc/self/fd; true; } >FILE; cmd2
9320//has no way of closing saved fd#1 for "find",
9321//and in SH_STANDALONE mode, "find" is not execed,
9322//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009323 rcode = run_list(command->group) & 0xff;
9324 }
9325 restore_redirects(squirrel);
9326 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9327 debug_leave();
9328 debug_printf_exec("run_pipe: return %d\n", rcode);
9329 return rcode;
9330 }
9331
9332 argv = command->argv ? command->argv : (char **) &null_ptr;
9333 {
9334 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009335 IF_HUSH_FUNCTIONS(const struct function *funcp;)
9336 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009337 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009338 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009339
Denys Vlasenko5807e182018-02-08 19:19:04 +01009340#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009341 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009342#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009343
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009344 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009345 /* Assignments, but no command.
9346 * Ensure redirects take effect (that is, create files).
9347 * Try "a=t >file"
9348 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009349 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009350 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009351 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009352 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009353 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009354
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009355 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009356 i = 0;
9357 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009358 char *p = expand_string_to_string(argv[i],
9359 EXP_FLAG_ESC_GLOB_CHARS,
9360 /*unbackslash:*/ 1
9361 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009362#if ENABLE_HUSH_MODE_X
9363 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009364 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009365 if (i == 0)
9366 x_mode_prefix();
9367 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009368 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009369 if (*eq) eq++;
9370 x_mode_addblock(p, (eq - p));
9371 x_mode_print_optionally_squoted(eq);
9372 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009373 }
9374#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009375 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009376 if (set_local_var(p, /*flag:*/ 0)) {
9377 /* assignment to readonly var / putenv error? */
9378 rcode = 1;
9379 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009380 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009381 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009382 /* Redirect error sets $? to 1. Otherwise,
9383 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009384 * Else, clear $?:
9385 * false; q=`exit 2`; echo $? - should print 2
9386 * false; x=1; echo $? - should print 0
9387 * Because of the 2nd case, we can't just use G.last_exitcode.
9388 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009389 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009390 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009391 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9392 debug_leave();
9393 debug_printf_exec("run_pipe: return %d\n", rcode);
9394 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009395 }
9396
9397 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkod2241f52020-10-31 03:34:07 +01009398#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
9399 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
9400 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
9401 else
9402#endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02009403#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009404 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009405 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009406 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009407#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009408 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009409
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009410 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009411 if (!argv_expanded[0]) {
9412 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009413 /* `false` still has to set exitcode 1 */
9414 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009415 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009416 }
9417
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009418 old_vars = NULL;
9419 sv_shadowed = G.shadowed_vars_pp;
9420
Denys Vlasenko75481d32017-07-31 05:27:09 +02009421 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009422 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9423 IF_HUSH_FUNCTIONS(x = NULL;)
9424 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009425 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009426 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009427 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9428 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009429 /*
9430 * Variable assignments are executed, but then "forgotten":
9431 * a=`sleep 1;echo A` exec 3>&-; echo $a
9432 * sleeps, but prints nothing.
9433 */
9434 enter_var_nest_level();
9435 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009436 rcode = redirect_and_varexp_helper(command,
9437 /*squirrel:*/ ERR_PTR,
9438 argv_expanded
9439 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009440 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009441 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009442
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009443 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009444 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009445
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009446 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009447 * a=b true; env | grep ^a=
9448 */
9449 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009450 /* Collect all variables "shadowed" by helper
9451 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9452 * into old_vars list:
9453 */
9454 G.shadowed_vars_pp = &old_vars;
9455 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009456 if (rcode == 0) {
9457 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009458 /* Do not collect *to old_vars list* vars shadowed
9459 * by e.g. "local VAR" builtin (collect them
9460 * in the previously nested list instead):
9461 * don't want them to be restored immediately
9462 * after "local" completes.
9463 */
9464 G.shadowed_vars_pp = sv_shadowed;
9465
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009466 debug_printf_exec(": builtin '%s' '%s'...\n",
9467 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009468 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009469 rcode = x->b_function(argv_expanded) & 0xff;
9470 fflush_all();
9471 }
9472#if ENABLE_HUSH_FUNCTIONS
9473 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009474 debug_printf_exec(": function '%s' '%s'...\n",
9475 funcp->name, argv_expanded[1]);
9476 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009477 /*
9478 * But do collect *to old_vars list* vars shadowed
9479 * within function execution. To that end, restore
9480 * this pointer _after_ function run:
9481 */
9482 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009483 }
9484#endif
9485 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009486 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009487 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009488 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009489 if (n < 0 || !APPLET_IS_NOFORK(n))
9490 goto must_fork;
9491
9492 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009493 /* Collect all variables "shadowed" by helper into old_vars list */
9494 G.shadowed_vars_pp = &old_vars;
9495 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9496 G.shadowed_vars_pp = sv_shadowed;
9497
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009498 if (rcode == 0) {
9499 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9500 argv_expanded[0], argv_expanded[1]);
9501 /*
9502 * Note: signals (^C) can't interrupt here.
9503 * We remember them and they will be acted upon
9504 * after applet returns.
9505 * This makes applets which can run for a long time
9506 * and/or wait for user input ineligible for NOFORK:
9507 * for example, "yes" or "rm" (rm -i waits for input).
9508 */
9509 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009510 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009511 } else
9512 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009513
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009514 restore_redirects(squirrel);
9515 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009516 leave_var_nest_level();
9517 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009518
9519 /*
9520 * Try "usleep 99999999" + ^C + "echo $?"
9521 * with FEATURE_SH_NOFORK=y.
9522 */
9523 if (!funcp) {
9524 /* It was builtin or nofork.
9525 * if this would be a real fork/execed program,
9526 * it should have died if a fatal sig was received.
9527 * But OTOH, there was no separate process,
9528 * the sig was sent to _shell_, not to non-existing
9529 * child.
9530 * Let's just handle ^C only, this one is obvious:
9531 * we aren't ok with exitcode 0 when ^C was pressed
9532 * during builtin/nofork.
9533 */
9534 if (sigismember(&G.pending_set, SIGINT))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009535 rcode = 128 | SIGINT;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009536 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009537 free(argv_expanded);
9538 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9539 debug_leave();
9540 debug_printf_exec("run_pipe return %d\n", rcode);
9541 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009542 }
9543
9544 must_fork:
9545 /* NB: argv_expanded may already be created, and that
9546 * might include `cmd` runs! Do not rerun it! We *must*
9547 * use argv_expanded if it's non-NULL */
9548
9549 /* Going to fork a child per each pipe member */
9550 pi->alive_cmds = 0;
9551 next_infd = 0;
9552
9553 cmd_no = 0;
9554 while (cmd_no < pi->num_cmds) {
9555 struct fd_pair pipefds;
9556#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009557 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009558 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009559 nommu_save.old_vars = NULL;
9560 nommu_save.argv = NULL;
9561 nommu_save.argv_from_re_execing = NULL;
9562#endif
9563 command = &pi->cmds[cmd_no];
9564 cmd_no++;
9565 if (command->argv) {
9566 debug_printf_exec(": pipe member '%s' '%s'...\n",
9567 command->argv[0], command->argv[1]);
9568 } else {
9569 debug_printf_exec(": pipe member with no argv\n");
9570 }
9571
9572 /* pipes are inserted between pairs of commands */
9573 pipefds.rd = 0;
9574 pipefds.wr = 1;
9575 if (cmd_no < pi->num_cmds)
9576 xpiped_pair(pipefds);
9577
Denys Vlasenko5807e182018-02-08 19:19:04 +01009578#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009579 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009580#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009581
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009582 command->pid = BB_MMU ? fork() : vfork();
9583 if (!command->pid) { /* child */
9584#if ENABLE_HUSH_JOB
9585 disable_restore_tty_pgrp_on_exit();
9586 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9587
9588 /* Every child adds itself to new process group
9589 * with pgid == pid_of_first_child_in_pipe */
9590 if (G.run_list_level == 1 && G_interactive_fd) {
9591 pid_t pgrp;
9592 pgrp = pi->pgrp;
9593 if (pgrp < 0) /* true for 1st process only */
9594 pgrp = getpid();
9595 if (setpgid(0, pgrp) == 0
9596 && pi->followup != PIPE_BG
9597 && G_saved_tty_pgrp /* we have ctty */
9598 ) {
9599 /* We do it in *every* child, not just first,
9600 * to avoid races */
9601 tcsetpgrp(G_interactive_fd, pgrp);
9602 }
9603 }
9604#endif
9605 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9606 /* 1st cmd in backgrounded pipe
9607 * should have its stdin /dev/null'ed */
9608 close(0);
9609 if (open(bb_dev_null, O_RDONLY))
9610 xopen("/", O_RDONLY);
9611 } else {
9612 xmove_fd(next_infd, 0);
9613 }
9614 xmove_fd(pipefds.wr, 1);
9615 if (pipefds.rd > 1)
9616 close(pipefds.rd);
9617 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009618 * and the pipe fd (fd#1) is available for dup'ing:
9619 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9620 * of cmd1 goes into pipe.
9621 */
9622 if (setup_redirects(command, NULL)) {
9623 /* Happens when redir file can't be opened:
9624 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9625 * FOO
9626 * hush: can't open '/qwe/rty': No such file or directory
9627 * BAZ
9628 * (echo BAR is not executed, it hits _exit(1) below)
9629 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009630 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009631 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009632
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009633 /* Stores to nommu_save list of env vars putenv'ed
9634 * (NOMMU, on MMU we don't need that) */
9635 /* cast away volatility... */
9636 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9637 /* pseudo_exec() does not return */
9638 }
9639
9640 /* parent or error */
9641#if ENABLE_HUSH_FAST
9642 G.count_SIGCHLD++;
9643//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9644#endif
9645 enable_restore_tty_pgrp_on_exit();
9646#if !BB_MMU
9647 /* Clean up after vforked child */
9648 free(nommu_save.argv);
9649 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009650 G.var_nest_level = sv_var_nest_level;
9651 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009652 add_vars(nommu_save.old_vars);
9653#endif
9654 free(argv_expanded);
9655 argv_expanded = NULL;
9656 if (command->pid < 0) { /* [v]fork failed */
9657 /* Clearly indicate, was it fork or vfork */
James Byrne69374872019-07-02 11:35:03 +02009658 bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009659 } else {
9660 pi->alive_cmds++;
9661#if ENABLE_HUSH_JOB
9662 /* Second and next children need to know pid of first one */
9663 if (pi->pgrp < 0)
9664 pi->pgrp = command->pid;
9665#endif
9666 }
9667
9668 if (cmd_no > 1)
9669 close(next_infd);
9670 if (cmd_no < pi->num_cmds)
9671 close(pipefds.wr);
9672 /* Pass read (output) pipe end to next iteration */
9673 next_infd = pipefds.rd;
9674 }
9675
9676 if (!pi->alive_cmds) {
9677 debug_leave();
9678 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9679 return 1;
9680 }
9681
9682 debug_leave();
9683 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9684 return -1;
9685}
9686
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009687/* NB: called by pseudo_exec, and therefore must not modify any
9688 * global data until exec/_exit (we can be a child after vfork!) */
9689static int run_list(struct pipe *pi)
9690{
9691#if ENABLE_HUSH_CASE
9692 char *case_word = NULL;
9693#endif
9694#if ENABLE_HUSH_LOOPS
9695 struct pipe *loop_top = NULL;
9696 char **for_lcur = NULL;
9697 char **for_list = NULL;
9698#endif
9699 smallint last_followup;
9700 smalluint rcode;
9701#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9702 smalluint cond_code = 0;
9703#else
9704 enum { cond_code = 0 };
9705#endif
9706#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009707 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009708 smallint last_rword; /* ditto */
9709#endif
9710
9711 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9712 debug_enter();
9713
9714#if ENABLE_HUSH_LOOPS
9715 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009716 {
9717 struct pipe *cpipe;
9718 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9719 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9720 continue;
9721 /* current word is FOR or IN (BOLD in comments below) */
9722 if (cpipe->next == NULL) {
9723 syntax_error("malformed for");
9724 debug_leave();
9725 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9726 return 1;
9727 }
9728 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9729 if (cpipe->next->res_word == RES_DO)
9730 continue;
9731 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9732 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9733 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9734 ) {
9735 syntax_error("malformed for");
9736 debug_leave();
9737 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9738 return 1;
9739 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009740 }
9741 }
9742#endif
9743
9744 /* Past this point, all code paths should jump to ret: label
9745 * in order to return, no direct "return" statements please.
9746 * This helps to ensure that no memory is leaked. */
9747
9748#if ENABLE_HUSH_JOB
9749 G.run_list_level++;
9750#endif
9751
9752#if HAS_KEYWORDS
9753 rword = RES_NONE;
9754 last_rword = RES_XXXX;
9755#endif
9756 last_followup = PIPE_SEQ;
9757 rcode = G.last_exitcode;
9758
9759 /* Go through list of pipes, (maybe) executing them. */
9760 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009761 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009762 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009763
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009764 if (G.flag_SIGINT)
9765 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009766 if (G_flag_return_in_progress == 1)
9767 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009768
9769 IF_HAS_KEYWORDS(rword = pi->res_word;)
9770 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9771 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009772
9773 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009774 if (
9775#if ENABLE_HUSH_IF
9776 rword == RES_IF || rword == RES_ELIF ||
9777#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009778 pi->followup != PIPE_SEQ
9779 ) {
9780 G.errexit_depth++;
9781 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009782#if ENABLE_HUSH_LOOPS
9783 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9784 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9785 ) {
9786 /* start of a loop: remember where loop starts */
9787 loop_top = pi;
9788 G.depth_of_loop++;
9789 }
9790#endif
9791 /* Still in the same "if...", "then..." or "do..." branch? */
9792 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9793 if ((rcode == 0 && last_followup == PIPE_OR)
9794 || (rcode != 0 && last_followup == PIPE_AND)
9795 ) {
9796 /* It is "<true> || CMD" or "<false> && CMD"
9797 * and we should not execute CMD */
9798 debug_printf_exec("skipped cmd because of || or &&\n");
9799 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009800 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009801 }
9802 }
9803 last_followup = pi->followup;
9804 IF_HAS_KEYWORDS(last_rword = rword;)
9805#if ENABLE_HUSH_IF
9806 if (cond_code) {
9807 if (rword == RES_THEN) {
9808 /* if false; then ... fi has exitcode 0! */
9809 G.last_exitcode = rcode = EXIT_SUCCESS;
9810 /* "if <false> THEN cmd": skip cmd */
9811 continue;
9812 }
9813 } else {
9814 if (rword == RES_ELSE || rword == RES_ELIF) {
9815 /* "if <true> then ... ELSE/ELIF cmd":
9816 * skip cmd and all following ones */
9817 break;
9818 }
9819 }
9820#endif
9821#if ENABLE_HUSH_LOOPS
9822 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9823 if (!for_lcur) {
9824 /* first loop through for */
9825
9826 static const char encoded_dollar_at[] ALIGN1 = {
9827 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9828 }; /* encoded representation of "$@" */
Denys Vlasenko987be932022-02-06 20:07:12 +01009829 static const char *const encoded_dollar_at_argv[] ALIGN_PTR = {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009830 encoded_dollar_at, NULL
9831 }; /* argv list with one element: "$@" */
9832 char **vals;
9833
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009834 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009835 vals = (char**)encoded_dollar_at_argv;
9836 if (pi->next->res_word == RES_IN) {
9837 /* if no variable values after "in" we skip "for" */
9838 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009839 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9840 break;
9841 }
9842 vals = pi->next->cmds[0].argv;
9843 } /* else: "for var; do..." -> assume "$@" list */
9844 /* create list of variable values */
9845 debug_print_strings("for_list made from", vals);
9846 for_list = expand_strvec_to_strvec(vals);
9847 for_lcur = for_list;
9848 debug_print_strings("for_list", for_list);
9849 }
9850 if (!*for_lcur) {
9851 /* "for" loop is over, clean up */
9852 free(for_list);
9853 for_list = NULL;
9854 for_lcur = NULL;
9855 break;
9856 }
9857 /* Insert next value from for_lcur */
9858 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009859 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009860 continue;
9861 }
9862 if (rword == RES_IN) {
9863 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9864 }
9865 if (rword == RES_DONE) {
9866 continue; /* "done" has no cmds too */
9867 }
9868#endif
9869#if ENABLE_HUSH_CASE
9870 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009871 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009872 case_word = expand_string_to_string(pi->cmds->argv[0],
9873 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009874 debug_printf_exec("CASE word1:'%s'\n", case_word);
9875 //unbackslash(case_word);
9876 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009877 continue;
9878 }
9879 if (rword == RES_MATCH) {
9880 char **argv;
9881
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009882 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009883 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9884 break;
9885 /* all prev words didn't match, does this one match? */
9886 argv = pi->cmds->argv;
9887 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009888 char *pattern;
9889 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9890 pattern = expand_string_to_string(*argv,
9891 EXP_FLAG_ESC_GLOB_CHARS,
9892 /*unbackslash:*/ 0
9893 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009894 /* TODO: which FNM_xxx flags to use? */
9895 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009896 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9897 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009898 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009899 if (cond_code == 0) {
9900 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009901 free(case_word);
9902 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009903 break;
9904 }
9905 argv++;
9906 }
9907 continue;
9908 }
9909 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009910 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009911 if (cond_code != 0)
9912 continue; /* not matched yet, skip this pipe */
9913 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009914 if (rword == RES_ESAC) {
9915 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9916 if (case_word) {
9917 /* "case" did not match anything: still set $? (to 0) */
9918 G.last_exitcode = rcode = EXIT_SUCCESS;
9919 }
9920 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009921#endif
9922 /* Just pressing <enter> in shell should check for jobs.
9923 * OTOH, in non-interactive shell this is useless
9924 * and only leads to extra job checks */
9925 if (pi->num_cmds == 0) {
9926 if (G_interactive_fd)
9927 goto check_jobs_and_continue;
9928 continue;
9929 }
9930
9931 /* After analyzing all keywords and conditions, we decided
9932 * to execute this pipe. NB: have to do checkjobs(NULL)
9933 * after run_pipe to collect any background children,
9934 * even if list execution is to be stopped. */
9935 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009936#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009937 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009938#endif
Denys Vlasenkoe53c7db2021-09-07 02:23:51 +02009939 rcode = r = G.o_opt[OPT_O_NOEXEC] ? 0 : run_pipe(pi);
9940 /* NB: rcode is a smalluint, r is int */
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009941 if (r != -1) {
9942 /* We ran a builtin, function, or group.
9943 * rcode is already known
9944 * and we don't need to wait for anything. */
9945 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9946 G.last_exitcode = rcode;
9947 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009948#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9949 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9950#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009951#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009952 /* Was it "break" or "continue"? */
9953 if (G.flag_break_continue) {
9954 smallint fbc = G.flag_break_continue;
9955 /* We might fall into outer *loop*,
9956 * don't want to break it too */
9957 if (loop_top) {
9958 G.depth_break_continue--;
9959 if (G.depth_break_continue == 0)
9960 G.flag_break_continue = 0;
9961 /* else: e.g. "continue 2" should *break* once, *then* continue */
9962 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9963 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009964 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009965 break;
9966 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009967 /* "continue": simulate end of loop */
9968 rword = RES_DONE;
9969 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009970 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009971#endif
9972 if (G_flag_return_in_progress == 1) {
9973 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9974 break;
9975 }
9976 } else if (pi->followup == PIPE_BG) {
9977 /* What does bash do with attempts to background builtins? */
9978 /* even bash 3.2 doesn't do that well with nested bg:
9979 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9980 * I'm NOT treating inner &'s as jobs */
9981#if ENABLE_HUSH_JOB
9982 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009983 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009984#endif
9985 /* Last command's pid goes to $! */
9986 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009987 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009988 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009989/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009990 rcode = EXIT_SUCCESS;
9991 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009992 } else {
9993#if ENABLE_HUSH_JOB
9994 if (G.run_list_level == 1 && G_interactive_fd) {
9995 /* Waits for completion, then fg's main shell */
9996 rcode = checkjobs_and_fg_shell(pi);
9997 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009998 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009999 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +010010000#endif
10001 /* This one just waits for completion */
10002 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
10003 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
10004 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +010010005 G.last_exitcode = rcode;
10006 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010007#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
10008 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
10009#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010010 }
10011
Denys Vlasenko9fda6092017-07-14 13:36:48 +020010012 /* Handle "set -e" */
10013 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
10014 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
10015 if (G.errexit_depth == 0)
10016 hush_exit(rcode);
10017 }
10018 G.errexit_depth = sv_errexit_depth;
10019
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010020 /* Analyze how result affects subsequent commands */
10021#if ENABLE_HUSH_IF
10022 if (rword == RES_IF || rword == RES_ELIF)
10023 cond_code = rcode;
10024#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +020010025 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010026 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +020010027 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010028#if ENABLE_HUSH_LOOPS
10029 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +020010030 if (pi->next
10031 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +020010032 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +020010033 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010034 if (rword == RES_WHILE) {
10035 if (rcode) {
10036 /* "while false; do...done" - exitcode 0 */
10037 G.last_exitcode = rcode = EXIT_SUCCESS;
10038 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +020010039 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010040 }
10041 }
10042 if (rword == RES_UNTIL) {
10043 if (!rcode) {
10044 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010045 break;
10046 }
10047 }
10048 }
10049#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010050 } /* for (pi) */
10051
10052#if ENABLE_HUSH_JOB
10053 G.run_list_level--;
10054#endif
10055#if ENABLE_HUSH_LOOPS
10056 if (loop_top)
10057 G.depth_of_loop--;
10058 free(for_list);
10059#endif
10060#if ENABLE_HUSH_CASE
10061 free(case_word);
10062#endif
10063 debug_leave();
10064 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
10065 return rcode;
10066}
10067
10068/* Select which version we will use */
10069static int run_and_free_list(struct pipe *pi)
10070{
10071 int rcode = 0;
10072 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -080010073 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010074 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
10075 rcode = run_list(pi);
10076 }
10077 /* free_pipe_list has the side effect of clearing memory.
10078 * In the long run that function can be merged with run_list,
10079 * but doing that now would hobble the debugging effort. */
10080 free_pipe_list(pi);
10081 debug_printf_exec("run_and_free_list return %d\n", rcode);
10082 return rcode;
10083}
10084
10085
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010086static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +000010087{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010088 sighandler_t old_handler;
10089 unsigned sig = 0;
10090 while ((mask >>= 1) != 0) {
10091 sig++;
10092 if (!(mask & 1))
10093 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +020010094 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010095 /* POSIX allows shell to re-enable SIGCHLD
10096 * even if it was SIG_IGN on entry.
10097 * Therefore we skip IGN check for it:
10098 */
10099 if (sig == SIGCHLD)
10100 continue;
Denys Vlasenko23bc5622020-02-18 16:46:01 +010010101 /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
10102 * Try:
10103 * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
10104 * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
Denys Vlasenko49e6bf22017-08-04 14:28:16 +020010105 */
Denys Vlasenko23bc5622020-02-18 16:46:01 +010010106 if (sig == SIGHUP && G_interactive_fd)
10107 continue;
10108 /* Unless one of the above signals, is it SIG_IGN? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010109 if (old_handler == SIG_IGN) {
10110 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010111 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010112#if ENABLE_HUSH_TRAP
10113 if (!G_traps)
10114 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10115 free(G_traps[sig]);
10116 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
10117#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010118 }
10119 }
10120}
10121
10122/* Called a few times only (or even once if "sh -c") */
10123static void install_special_sighandlers(void)
10124{
Denis Vlasenkof9375282009-04-05 19:13:39 +000010125 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010126
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010127 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010128 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010129 if (G_interactive_fd) {
10130 mask |= SPECIAL_INTERACTIVE_SIGS;
10131 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010132 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010133 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010134 /* Careful, do not re-install handlers we already installed */
10135 if (G.special_sig_mask != mask) {
10136 unsigned diff = mask & ~G.special_sig_mask;
10137 G.special_sig_mask = mask;
10138 install_sighandlers(diff);
10139 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010140}
10141
10142#if ENABLE_HUSH_JOB
10143/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010144/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010145static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +000010146{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010147 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010148
10149 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010150 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +010010151 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
10152 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010153 + (1 << SIGBUS ) * HUSH_DEBUG
10154 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +010010155 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010156 + (1 << SIGABRT)
10157 /* bash 3.2 seems to handle these just like 'fatal' ones */
10158 + (1 << SIGPIPE)
10159 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010160 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010161 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010162 * we never want to restore pgrp on exit, and this fn is not called
10163 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010164 /*+ (1 << SIGHUP )*/
10165 /*+ (1 << SIGTERM)*/
10166 /*+ (1 << SIGINT )*/
10167 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010168 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010169
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010170 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010171}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000010172#endif
Eric Andersenada18ff2001-05-21 16:18:22 +000010173
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010174static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +000010175{
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010176 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +000010177 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010178 case 'n':
Denys Vlasenkoe53c7db2021-09-07 02:23:51 +020010179 /* set -n has no effect in interactive shell */
10180 /* Try: while set -n; do echo $-; done */
10181 if (!G_interactive_fd)
10182 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010183 break;
10184 case 'x':
10185 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +020010186 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 +010010187 break;
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010188 case 'e':
10189 G.o_opt[OPT_O_ERREXIT] = state;
10190 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010191 case 'o':
10192 if (!o_opt) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010193 /* "set -o" or "set +o" without parameter.
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010194 * in bash, set -o produces this output:
10195 * pipefail off
10196 * and set +o:
10197 * set +o pipefail
10198 * We always use the second form.
10199 */
10200 const char *p = o_opt_strings;
10201 idx = 0;
10202 while (*p) {
10203 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
10204 idx++;
10205 p += strlen(p) + 1;
10206 }
10207 break;
10208 }
10209 idx = index_in_strings(o_opt_strings, o_opt);
10210 if (idx >= 0) {
10211 G.o_opt[idx] = state;
10212 break;
10213 }
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010214 /* fall through to error */
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010215 default:
10216 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +000010217 }
10218 return EXIT_SUCCESS;
10219}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010220
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000010221int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +000010222int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +000010223{
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010224 pid_t cached_getpid;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010225 enum {
10226 OPT_login = (1 << 0),
10227 };
10228 unsigned flags;
Denys Vlasenko63139b52020-12-13 22:00:56 +010010229#if !BB_MMU
10230 unsigned builtin_argc = 0;
10231#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010232 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010233 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010234 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +000010235
Denis Vlasenko574f2f42008-02-27 18:41:59 +000010236 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +020010237 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010238 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010239#if ENABLE_HUSH_TRAP
10240# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010241 G.return_exitcode = -1;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010242# endif
10243 G.pre_trap_exitcode = -1;
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010244#endif
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010245
Denys Vlasenko10c01312011-05-11 11:49:21 +020010246#if ENABLE_HUSH_FAST
10247 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
10248#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010249#if !BB_MMU
10250 G.argv0_for_re_execing = argv[0];
10251#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010252
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010253 cached_getpid = getpid(); /* for tcsetpgrp() during init */
Denys Vlasenko46a71dc2020-12-25 18:49:29 +010010254 G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
Denys Vlasenko62f1eed2021-10-12 22:39:11 +020010255 G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010256
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010257 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010258 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
10259 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010260 shell_ver = xzalloc(sizeof(*shell_ver));
10261 shell_ver->flg_export = 1;
10262 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +020010263 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +020010264 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010265 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010266
Denys Vlasenko605067b2010-09-06 12:10:51 +020010267 /* Create shell local variables from the values
10268 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010269 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010270 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010271 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010272 if (e) while (*e) {
10273 char *value = strchr(*e, '=');
10274 if (value) { /* paranoia */
10275 cur_var->next = xzalloc(sizeof(*cur_var));
10276 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +000010277 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010278 cur_var->max_len = strlen(*e);
10279 cur_var->flg_export = 1;
10280 }
10281 e++;
10282 }
Denys Vlasenko605067b2010-09-06 12:10:51 +020010283 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010284 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
10285 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +020010286
10287 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010288 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010289
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010290#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010291 /* Set (but not export) HOSTNAME unless already set */
10292 if (!get_local_var_value("HOSTNAME")) {
10293 struct utsname uts;
10294 uname(&uts);
10295 set_local_var_from_halves("HOSTNAME", uts.nodename);
10296 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +020010297#endif
10298 /* IFS is not inherited from the parent environment */
10299 set_local_var_from_halves("IFS", defifs);
10300
Denys Vlasenkoef8985c2019-05-19 16:29:09 +020010301 if (!get_local_var_value("PATH"))
10302 set_local_var_from_halves("PATH", bb_default_root_path);
10303
Denys Vlasenko0c360192019-05-19 15:37:50 +020010304 /* PS1/PS2 are set later, if we determine that we are interactive */
10305
Denys Vlasenko6db47842009-09-05 20:15:17 +020010306 /* bash also exports SHLVL and _,
10307 * and sets (but doesn't export) the following variables:
10308 * BASH=/bin/bash
10309 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
10310 * BASH_VERSION='3.2.0(1)-release'
10311 * HOSTTYPE=i386
10312 * MACHTYPE=i386-pc-linux-gnu
10313 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +020010314 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +020010315 * EUID=<NNNNN>
10316 * UID=<NNNNN>
10317 * GROUPS=()
10318 * LINES=<NNN>
10319 * COLUMNS=<NNN>
10320 * BASH_ARGC=()
10321 * BASH_ARGV=()
10322 * BASH_LINENO=()
10323 * BASH_SOURCE=()
10324 * DIRSTACK=()
10325 * PIPESTATUS=([0]="0")
10326 * HISTFILE=/<xxx>/.bash_history
10327 * HISTFILESIZE=500
10328 * HISTSIZE=500
10329 * MAILCHECK=60
10330 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
10331 * SHELL=/bin/bash
10332 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
10333 * TERM=dumb
10334 * OPTERR=1
10335 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +020010336 * PS4='+ '
10337 */
10338
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010339#if NUM_SCRIPTS > 0
10340 if (argc < 0) {
10341 char *script = get_script_content(-argc - 1);
10342 G.global_argv = argv;
10343 G.global_argc = string_array_len(argv);
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010344 //install_special_sighandlers(); - needed?
10345 parse_and_run_string(script);
10346 goto final_return;
10347 }
10348#endif
10349
Eric Andersen94ac2442001-05-22 19:05:18 +000010350 /* Initialize some more globals to non-zero values */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010351 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +000010352
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010353 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010354 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010355 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010356 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010357 * in order to intercept (more) signals.
10358 */
10359
10360 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010361 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010362 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010363 while (1) {
Denys Vlasenko3b053052021-01-04 03:05:34 +010010364 int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
10365 "cexinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010366#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +000010367 "<:$:R:V:"
10368# if ENABLE_HUSH_FUNCTIONS
10369 "F:"
10370# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010371#endif
10372 );
10373 if (opt <= 0)
10374 break;
Eric Andersen25f27032001-04-26 23:22:31 +000010375 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010376 case 'c':
Denys Vlasenko0ab2dd42020-12-23 02:22:08 +010010377 /* Note: -c is not an option with param!
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010378 * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010379 */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010380 G.opt_c = 1;
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010381 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010382 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010383 /* Well, we cannot just declare interactiveness,
10384 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010385 /* G_interactive_fd++; */
Denys Vlasenko62f1eed2021-10-12 22:39:11 +020010386//There are a few cases where bash -i -c 'SCRIPT'
10387//has visible effect (differs from bash -c 'SCRIPT'):
10388//it ignores TERM:
10389// bash -i -c 'kill $$; echo ALIVE'
10390// ALIVE
Denys Vlasenko931c55f2022-01-13 12:50:48 +010010391//it resets SIG_IGNed HUP to SIG_DFL:
Denys Vlasenko62f1eed2021-10-12 22:39:11 +020010392// trap '' hup; bash -i -c 'kill -hup $$; echo ALIVE'
10393// Hangup [the message is not printed by bash, it's the shell which started it]
10394//is talkative about jobs and exiting:
10395// bash -i -c 'sleep 1 & exit'
10396// [1] 16170
10397// exit
10398//includes $ENV file (only if run as "sh"):
10399// echo last >/tmp/ENV; ENV=/tmp/ENV sh -i -c 'echo HERE'
10400// last: cannot open /var/log/wtmp: No such file or directory
10401// HERE
10402//(under "bash", it's the opposite: it runs $BASH_ENV file only *without* -i).
10403//
10404//ash -i -c 'sleep 3; sleep 3', on ^C, drops into a prompt instead of exiting
10405//(this may be a bug, bash does not do this).
10406//(ash -i -c 'sleep 3' won't show this, the last command gets auto-"exec"ed)
10407//
10408//None of the above feel like useful features people would rely on.
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010409 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010410 case 's':
Denys Vlasenkof3634582019-06-03 12:21:04 +020010411 G.opt_s = 1;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010412 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010413 case 'l':
10414 flags |= OPT_login;
10415 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010416#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010417 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010418 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010419 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010420 case '$': {
10421 unsigned long long empty_trap_mask;
10422
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010423 G.root_pid = bb_strtou(optarg, &optarg, 16);
10424 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010425 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10426 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010427 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10428 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010429 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010430 optarg++;
10431 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010432 optarg++;
10433 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10434 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010435 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010436 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010437# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010438 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010439 for (sig = 1; sig < NSIG; sig++) {
10440 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010441 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010442 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010443 }
10444 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010445# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010446 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010447# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010448 optarg++;
10449 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010450# endif
Denys Vlasenko49142d42020-12-13 18:44:07 +010010451 /* Suppress "killed by signal" message, -$ hack is used
10452 * for subshells: echo `sh -c 'kill -9 $$'`
10453 * should be silent.
10454 */
10455 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010456# if ENABLE_HUSH_FUNCTIONS
10457 /* nommu uses re-exec trick for "... | func | ...",
10458 * should allow "return".
10459 * This accidentally allows returns in subshells.
10460 */
10461 G_flag_return_in_progress = -1;
10462# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010463 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010464 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010465 case 'R':
10466 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010467 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010468 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010469# if ENABLE_HUSH_FUNCTIONS
10470 case 'F': {
10471 struct function *funcp = new_function(optarg);
10472 /* funcp->name is already set to optarg */
10473 /* funcp->body is set to NULL. It's a special case. */
10474 funcp->body_as_string = argv[optind];
10475 optind++;
10476 break;
10477 }
10478# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010479#endif
Denys Vlasenko3b053052021-01-04 03:05:34 +010010480 /*case '?': invalid option encountered (set_mode('?') will fail) */
10481 /*case 'n':*/
10482 /*case 'x':*/
10483 /*case 'e':*/
10484 default:
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010485 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010486 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010487 bb_show_usage();
Eric Andersen25f27032001-04-26 23:22:31 +000010488 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010489 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010490
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010491 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10492 G.global_argc = argc - (optind - 1);
10493 G.global_argv = argv + (optind - 1);
10494 G.global_argv[0] = argv[0];
10495
Denis Vlasenkof9375282009-04-05 19:13:39 +000010496 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010497 if (flags & OPT_login) {
Denys Vlasenko63139b52020-12-13 22:00:56 +010010498 const char *hp = NULL;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010499 HFILE *input;
Denys Vlasenko63139b52020-12-13 22:00:56 +010010500
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010501 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010502 input = hfopen("/etc/profile");
Denys Vlasenko63139b52020-12-13 22:00:56 +010010503 run_profile:
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010504 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010505 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010506 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010507 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010508 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010509 /* bash: after sourcing /etc/profile,
10510 * tries to source (in the given order):
10511 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010512 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010513 * bash also sources ~/.bash_logout on exit.
10514 * If called as sh, skips .bash_XXX files.
10515 */
Denys Vlasenko63139b52020-12-13 22:00:56 +010010516 if (!hp) { /* unless we looped on the "goto" already */
10517 hp = get_local_var_value("HOME");
10518 if (hp && hp[0]) {
10519 debug_printf("sourcing ~/.profile\n");
10520 hp = concat_path_file(hp, ".profile");
10521 input = hfopen(hp);
10522 free((char*)hp);
10523 goto run_profile;
10524 }
10525 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010526 }
10527
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010528 /* -c takes effect *after* -l */
10529 if (G.opt_c) {
10530 /* Possibilities:
10531 * sh ... -c 'script'
10532 * sh ... -c 'script' ARG0 [ARG1...]
10533 * On NOMMU, if builtin_argc != 0,
10534 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
10535 * "" needs to be replaced with NULL
10536 * and BARGV vector fed to builtin function.
10537 * Note: the form without ARG0 never happens:
10538 * sh ... -c 'builtin' BARGV... ""
10539 */
10540 char *script;
10541
10542 install_special_sighandlers();
10543
10544 G.global_argc--;
10545 G.global_argv++;
Denys Vlasenko49142d42020-12-13 18:44:07 +010010546#if !BB_MMU
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010547 if (builtin_argc) {
10548 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10549 const struct built_in_command *x;
10550 x = find_builtin(G.global_argv[0]);
10551 if (x) { /* paranoia */
10552 argv = G.global_argv;
10553 G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
10554 G.global_argv += builtin_argc + 1;
10555 G.global_argv[-1] = NULL; /* replace "" */
10556 G.last_exitcode = x->b_function(argv);
10557 }
10558 goto final_return;
10559 }
Denys Vlasenko49142d42020-12-13 18:44:07 +010010560#endif
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010561
10562 script = G.global_argv[0];
10563 if (!script)
10564 bb_error_msg_and_die(bb_msg_requires_arg, "-c");
10565 if (!G.global_argv[1]) {
10566 /* -c 'script' (no params): prevent empty $0 */
10567 G.global_argv[0] = argv[0];
10568 } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
10569 G.global_argc--;
10570 G.global_argv++;
10571 }
10572 parse_and_run_string(script);
10573 goto final_return;
10574 }
10575
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010576 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010577 if (!G.opt_s && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010578 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010579 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010580 * "bash <script>" (which is never interactive (unless -i?))
10581 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010582 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010583 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010584 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010585 G.global_argc--;
10586 G.global_argv++;
10587 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010588 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010589 input = hfopen(G.global_argv[0]);
10590 if (!input) {
10591 bb_simple_perror_msg_and_die(G.global_argv[0]);
10592 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010593 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010594 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010595 parse_and_run_file(input);
10596#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010597 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010598#endif
10599 goto final_return;
10600 }
Denys Vlasenkof3634582019-06-03 12:21:04 +020010601 /* "implicit" -s: bare interactive hush shows 's' in $- */
Denys Vlasenkod8740b22019-05-19 19:11:21 +020010602 G.opt_s = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010603
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010604 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010605 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010606 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010607
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010608 /* A shell is interactive if the '-i' flag was given,
10609 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010610 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010611 * no arguments remaining or the -s flag given
10612 * standard input is a terminal
10613 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010614 * Refer to Posix.2, the description of the 'sh' utility.
10615 */
10616#if ENABLE_HUSH_JOB
10617 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010618 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10619 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10620 if (G_saved_tty_pgrp < 0)
10621 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010622
10623 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010624 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010625 if (G_interactive_fd < 0) {
10626 /* try to dup to any fd */
10627 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010628 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010629 /* give up */
10630 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010631 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010632 }
10633 }
Eric Andersen25f27032001-04-26 23:22:31 +000010634 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010635 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010636 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010637 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010638
Mike Frysinger38478a62009-05-20 04:48:06 -040010639 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010640 /* If we were run as 'hush &', sleep until we are
10641 * in the foreground (tty pgrp == our pgrp).
10642 * If we get started under a job aware app (like bash),
10643 * make sure we are now in charge so we don't fight over
10644 * who gets the foreground */
10645 while (1) {
10646 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010647 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10648 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010649 break;
10650 /* send TTIN to ourself (should stop us) */
10651 kill(- shell_pgrp, SIGTTIN);
10652 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010653 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010654
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010655 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010656 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010657
Mike Frysinger38478a62009-05-20 04:48:06 -040010658 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010659 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010660 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010661 /* Put ourselves in our own process group
10662 * (bash, too, does this only if ctty is available) */
10663 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10664 /* Grab control of the terminal */
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010665 tcsetpgrp(G_interactive_fd, cached_getpid);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010666 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010667 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010668
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010669# if ENABLE_FEATURE_EDITING
10670 G.line_input_state = new_line_input_t(FOR_SHELL);
Ron Yorston9e2a5662020-01-21 16:01:58 +000010671 G.line_input_state->get_exe_name = get_builtin_name;
Ron Yorston7d1c7d82022-03-24 12:17:25 +000010672 G.line_input_state->sh_get_var = get_local_var_value;
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010673# endif
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010674# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10675 {
10676 const char *hp = get_local_var_value("HISTFILE");
10677 if (!hp) {
10678 hp = get_local_var_value("HOME");
10679 if (hp)
10680 hp = concat_path_file(hp, ".hush_history");
10681 } else {
10682 hp = xstrdup(hp);
10683 }
10684 if (hp) {
10685 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010686 //set_local_var(xasprintf("HISTFILE=%s", ...));
10687 }
10688# if ENABLE_FEATURE_SH_HISTFILESIZE
10689 hp = get_local_var_value("HISTFILESIZE");
10690 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10691# endif
10692 }
10693# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010694 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010695 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010696 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010697#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010698 /* No job control compiled in, only prompt/line editing */
10699 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010700 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010701 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010702 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010703 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010704 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010705 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010706 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010707 }
10708 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010709 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010710 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010711 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010712 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010713#else
10714 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010715 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010716#endif
10717 /* bash:
10718 * if interactive but not a login shell, sources ~/.bashrc
10719 * (--norc turns this off, --rcfile <file> overrides)
10720 */
10721
Denys Vlasenko0c360192019-05-19 15:37:50 +020010722 if (G_interactive_fd) {
10723#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
10724 /* Set (but not export) PS1/2 unless already set */
10725 if (!get_local_var_value("PS1"))
10726 set_local_var_from_halves("PS1", "\\w \\$ ");
10727 if (!get_local_var_value("PS2"))
10728 set_local_var_from_halves("PS2", "> ");
10729#endif
10730 if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
10731 /* note: ash and hush share this string */
10732 printf("\n\n%s %s\n"
10733 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10734 "\n",
10735 bb_banner,
10736 "hush - the humble shell"
10737 );
10738 }
Mike Frysingerb2705e12009-03-23 08:44:02 +000010739 }
10740
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010741 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010742
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010743 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010744 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010745}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010746
10747
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010748/*
10749 * Built-ins
10750 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010751static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010752{
10753 return 0;
10754}
10755
Denys Vlasenko265062d2017-01-10 15:13:30 +010010756#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenkoa8e19602020-12-14 03:52:54 +010010757static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010758{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010759 int argc = string_array_len(argv);
10760 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010761}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010762#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010763#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010764static int FAST_FUNC builtin_test(char **argv)
10765{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010766 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010767}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010768#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010769#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010770static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010771{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010772 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010773}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010774#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010775#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010776static int FAST_FUNC builtin_printf(char **argv)
10777{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010778 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010779}
10780#endif
10781
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010782#if ENABLE_HUSH_HELP
10783static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10784{
10785 const struct built_in_command *x;
10786
10787 printf(
10788 "Built-in commands:\n"
10789 "------------------\n");
10790 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10791 if (x->b_descr)
10792 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10793 }
10794 return EXIT_SUCCESS;
10795}
10796#endif
10797
10798#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10799static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10800{
Ron Yorston9f3b4102019-12-16 09:31:10 +000010801 show_history(G.line_input_state);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010802 return EXIT_SUCCESS;
10803}
10804#endif
10805
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010806static char **skip_dash_dash(char **argv)
10807{
10808 argv++;
10809 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10810 argv++;
10811 return argv;
10812}
10813
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010814static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010815{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010816 const char *newdir;
10817
10818 argv = skip_dash_dash(argv);
10819 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010820 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010821 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010822 * bash says "bash: cd: HOME not set" and does nothing
10823 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010824 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010825 const char *home = get_local_var_value("HOME");
10826 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010827 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010828 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010829 /* Mimic bash message exactly */
10830 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010831 return EXIT_FAILURE;
10832 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010833 /* Read current dir (get_cwd(1) is inside) and set PWD.
10834 * Note: do not enforce exporting. If PWD was unset or unexported,
10835 * set it again, but do not export. bash does the same.
10836 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010837 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010838 return EXIT_SUCCESS;
10839}
10840
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010841static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10842{
10843 puts(get_cwd(0));
10844 return EXIT_SUCCESS;
10845}
10846
10847static int FAST_FUNC builtin_eval(char **argv)
10848{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010849 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010850
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010851 if (!argv[0])
10852 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010853
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010854 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010855 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010856 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010857 /* bash:
10858 * eval "echo Hi; done" ("done" is syntax error):
10859 * "echo Hi" will not execute too.
10860 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010861 parse_and_run_string(argv[0]);
10862 } else {
10863 /* "The eval utility shall construct a command by
10864 * concatenating arguments together, separating
10865 * each with a <space> character."
10866 */
10867 char *str, *p;
10868 unsigned len = 0;
10869 char **pp = argv;
10870 do
10871 len += strlen(*pp) + 1;
10872 while (*++pp);
10873 str = p = xmalloc(len);
10874 pp = argv;
10875 for (;;) {
10876 p = stpcpy(p, *pp);
10877 pp++;
10878 if (!*pp)
10879 break;
10880 *p++ = ' ';
10881 }
10882 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010883 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010884 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010885 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010886 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010887 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010888}
10889
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010890static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010891{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010892 argv = skip_dash_dash(argv);
10893 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010894 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010895
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010896 /* Careful: we can end up here after [v]fork. Do not restore
10897 * tty pgrp then, only top-level shell process does that */
10898 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10899 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10900
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010901 /* Saved-redirect fds, script fds and G_interactive_fd are still
10902 * open here. However, they are all CLOEXEC, and execv below
10903 * closes them. Try interactive "exec ls -l /proc/self/fd",
10904 * it should show no extra open fds in the "ls" process.
10905 * If we'd try to run builtins/NOEXECs, this would need improving.
10906 */
10907 //close_saved_fds_and_FILE_fds();
10908
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010909 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010910 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010911 * and tcsetpgrp, and this is inherently racy.
10912 */
10913 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010914}
10915
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010916static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010917{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010918 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010919
10920 /* interactive bash:
10921 * # trap "echo EEE" EXIT
10922 * # exit
10923 * exit
10924 * There are stopped jobs.
10925 * (if there are _stopped_ jobs, running ones don't count)
10926 * # exit
10927 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010928 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010929 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010930 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010931 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010932
10933 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010934 argv = skip_dash_dash(argv);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010935 if (argv[0] == NULL) {
10936#if ENABLE_HUSH_TRAP
10937 if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
10938 hush_exit(G.pre_trap_exitcode);
10939#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010940 hush_exit(G.last_exitcode);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010941 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010942 /* mimic bash: exit 123abc == exit 255 + error msg */
10943 xfunc_error_retval = 255;
10944 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010945 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010946}
10947
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010948#if ENABLE_HUSH_TYPE
10949/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10950static int FAST_FUNC builtin_type(char **argv)
10951{
10952 int ret = EXIT_SUCCESS;
10953
10954 while (*++argv) {
10955 const char *type;
10956 char *path = NULL;
10957
10958 if (0) {} /* make conditional compile easier below */
10959 /*else if (find_alias(*argv))
10960 type = "an alias";*/
Denys Vlasenko259747c2019-11-28 10:28:14 +010010961# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010962 else if (find_function(*argv))
10963 type = "a function";
Denys Vlasenko259747c2019-11-28 10:28:14 +010010964# endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010965 else if (find_builtin(*argv))
10966 type = "a shell builtin";
10967 else if ((path = find_in_path(*argv)) != NULL)
10968 type = path;
10969 else {
10970 bb_error_msg("type: %s: not found", *argv);
10971 ret = EXIT_FAILURE;
10972 continue;
10973 }
10974
10975 printf("%s is %s\n", *argv, type);
10976 free(path);
10977 }
10978
10979 return ret;
10980}
10981#endif
10982
10983#if ENABLE_HUSH_READ
10984/* Interruptibility of read builtin in bash
10985 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10986 *
10987 * Empty trap makes read ignore corresponding signal, for any signal.
10988 *
10989 * SIGINT:
10990 * - terminates non-interactive shell;
10991 * - interrupts read in interactive shell;
10992 * if it has non-empty trap:
10993 * - executes trap and returns to command prompt in interactive shell;
10994 * - executes trap and returns to read in non-interactive shell;
10995 * SIGTERM:
10996 * - is ignored (does not interrupt) read in interactive shell;
10997 * - terminates non-interactive shell;
10998 * if it has non-empty trap:
10999 * - executes trap and returns to read;
11000 * SIGHUP:
11001 * - terminates shell (regardless of interactivity);
11002 * if it has non-empty trap:
11003 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020011004 * SIGCHLD from children:
11005 * - does not interrupt read regardless of interactivity:
11006 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011007 */
11008static int FAST_FUNC builtin_read(char **argv)
11009{
11010 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020011011 struct builtin_read_params params;
11012
11013 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011014
11015 /* "!": do not abort on errors.
11016 * Option string must start with "sr" to match BUILTIN_READ_xxx
11017 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020011018 params.read_flags = getopt32(argv,
Denys Vlasenko259747c2019-11-28 10:28:14 +010011019# if BASH_READ_D
Denys Vlasenko457825f2021-06-06 12:07:11 +020011020 IF_NOT_HUSH_BASH_COMPAT("^")
11021 "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
11022 &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko259747c2019-11-28 10:28:14 +010011023# else
Denys Vlasenko457825f2021-06-06 12:07:11 +020011024 IF_NOT_HUSH_BASH_COMPAT("^")
11025 "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
11026 &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko259747c2019-11-28 10:28:14 +010011027# endif
Denys Vlasenko457825f2021-06-06 12:07:11 +020011028//TODO: print "read: need variable name"
11029//for the case of !BASH "read" with no args (now it fails silently)
11030//(or maybe extend getopt32() to emit a message if "-1" fails)
Denys Vlasenko1f41c882017-08-09 13:52:36 +020011031 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020011032 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011033 return EXIT_FAILURE;
11034 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020011035 params.argv = argv;
11036 params.setvar = set_local_var_from_halves;
11037 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011038
11039 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020011040 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011041
11042 if ((uintptr_t)r == 1 && errno == EINTR) {
11043 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020011044 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011045 goto again;
11046 }
11047
11048 if ((uintptr_t)r > 1) {
James Byrne69374872019-07-02 11:35:03 +020011049 bb_simple_error_msg(r);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011050 r = (char*)(uintptr_t)1;
11051 }
11052
11053 return (uintptr_t)r;
11054}
11055#endif
11056
11057#if ENABLE_HUSH_UMASK
11058static int FAST_FUNC builtin_umask(char **argv)
11059{
11060 int rc;
11061 mode_t mask;
11062
11063 rc = 1;
11064 mask = umask(0);
11065 argv = skip_dash_dash(argv);
11066 if (argv[0]) {
11067 mode_t old_mask = mask;
11068
11069 /* numeric umasks are taken as-is */
11070 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
11071 if (!isdigit(argv[0][0]))
11072 mask ^= 0777;
11073 mask = bb_parse_mode(argv[0], mask);
11074 if (!isdigit(argv[0][0]))
11075 mask ^= 0777;
11076 if ((unsigned)mask > 0777) {
11077 mask = old_mask;
11078 /* bash messages:
11079 * bash: umask: 'q': invalid symbolic mode operator
11080 * bash: umask: 999: octal number out of range
11081 */
11082 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
11083 rc = 0;
11084 }
11085 } else {
11086 /* Mimic bash */
11087 printf("%04o\n", (unsigned) mask);
11088 /* fall through and restore mask which we set to 0 */
11089 }
11090 umask(mask);
11091
11092 return !rc; /* rc != 0 - success */
11093}
11094#endif
11095
Denys Vlasenko41ade052017-01-08 18:56:24 +010011096#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011097static void print_escaped(const char *s)
11098{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020011099 if (*s == '\'')
11100 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011101 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020011102 const char *p = strchrnul(s, '\'');
11103 /* print 'xxxx', possibly just '' */
11104 printf("'%.*s'", (int)(p - s), s);
11105 if (*p == '\0')
11106 break;
11107 s = p;
11108 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011109 /* s points to '; print "'''...'''" */
11110 putchar('"');
11111 do putchar('\''); while (*++s == '\'');
11112 putchar('"');
11113 } while (*s);
11114}
Denys Vlasenko41ade052017-01-08 18:56:24 +010011115#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011116
Denys Vlasenko1e660422017-07-17 21:10:50 +020011117#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011118static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020011119{
11120 do {
11121 char *name = *argv;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020011122 const char *name_end = endofname(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011123
Denys Vlasenko27c56f12010-09-07 09:56:34 +020011124 if (*name_end == '\0') {
11125 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020011126
Denys Vlasenko27c56f12010-09-07 09:56:34 +020011127 vpp = get_ptr_to_local_var(name, name_end - name);
11128 var = vpp ? *vpp : NULL;
11129
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011130 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020011131 /* export -n NAME (without =VALUE) */
11132 if (var) {
11133 var->flg_export = 0;
11134 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
11135 unsetenv(name);
11136 } /* else: export -n NOT_EXISTING_VAR: no-op */
11137 continue;
11138 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011139 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020011140 /* export NAME (without =VALUE) */
11141 if (var) {
11142 var->flg_export = 1;
11143 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
11144 putenv(var->varstr);
11145 continue;
11146 }
11147 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020011148 if (flags & SETFLAG_MAKE_RO) {
11149 /* readonly NAME (without =VALUE) */
11150 if (var) {
11151 var->flg_read_only = 1;
11152 continue;
11153 }
11154 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011155# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020011156 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011157 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020011158 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
11159 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020011160 /* "local x=abc; ...; local x" - ignore second local decl */
11161 continue;
11162 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011163 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011164# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020011165 /* Exporting non-existing variable.
11166 * bash does not put it in environment,
11167 * but remembers that it is exported,
11168 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020011169 * We just set it to "" and export.
11170 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020011171 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020011172 * bash sets the value to "".
11173 */
11174 /* Or, it's "readonly NAME" (without =VALUE).
11175 * bash remembers NAME and disallows its creation
11176 * in the future.
11177 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020011178 name = xasprintf("%s=", name);
11179 } else {
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020011180 if (*name_end != '=') {
11181 bb_error_msg("'%s': bad variable name", name);
11182 /* do not parse following argv[]s: */
11183 return 1;
11184 }
Denys Vlasenko295fef82009-06-03 12:47:26 +020011185 /* (Un)exporting/making local NAME=VALUE */
11186 name = xstrdup(name);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020011187 /* Testcase: export PS1='\w \$ ' */
11188 unbackslash(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011189 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020011190 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020011191 if (set_local_var(name, flags))
11192 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020011193 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020011194 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020011195}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011196#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020011197
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011198#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011199static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011200{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000011201 unsigned opt_unexport;
11202
Denys Vlasenko259747c2019-11-28 10:28:14 +010011203# if ENABLE_HUSH_EXPORT_N
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020011204 /* "!": do not abort on errors */
11205 opt_unexport = getopt32(argv, "!n");
11206 if (opt_unexport == (uint32_t)-1)
11207 return EXIT_FAILURE;
11208 argv += optind;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011209# else
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020011210 opt_unexport = 0;
11211 argv++;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011212# endif
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020011213
11214 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011215 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011216 if (e) {
11217 while (*e) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010011218# if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011219 puts(*e++);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011220# else
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011221 /* ash emits: export VAR='VAL'
11222 * bash: declare -x VAR="VAL"
11223 * we follow ash example */
11224 const char *s = *e++;
11225 const char *p = strchr(s, '=');
11226
11227 if (!p) /* wtf? take next variable */
11228 continue;
11229 /* export var= */
11230 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011231 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011232 putchar('\n');
Denys Vlasenko259747c2019-11-28 10:28:14 +010011233# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011234 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011235 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011236 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011237 return EXIT_SUCCESS;
11238 }
11239
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011240 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011241}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011242#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011243
Denys Vlasenko295fef82009-06-03 12:47:26 +020011244#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011245static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020011246{
11247 if (G.func_nest_level == 0) {
11248 bb_error_msg("%s: not in a function", argv[0]);
11249 return EXIT_FAILURE; /* bash compat */
11250 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020011251 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020011252 /* Since all builtins run in a nested variable level,
11253 * need to use level - 1 here. Or else the variable will be removed at once
11254 * after builtin returns.
11255 */
11256 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011257}
11258#endif
11259
Denys Vlasenko1e660422017-07-17 21:10:50 +020011260#if ENABLE_HUSH_READONLY
11261static int FAST_FUNC builtin_readonly(char **argv)
11262{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011263 argv++;
11264 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020011265 /* bash: readonly [-p]: list all readonly VARs
11266 * (-p has no effect in bash)
11267 */
11268 struct variable *e;
11269 for (e = G.top_var; e; e = e->next) {
11270 if (e->flg_read_only) {
11271//TODO: quote value: readonly VAR='VAL'
11272 printf("readonly %s\n", e->varstr);
11273 }
11274 }
11275 return EXIT_SUCCESS;
11276 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011277 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020011278}
11279#endif
11280
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011281#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011282/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
11283static int FAST_FUNC builtin_unset(char **argv)
11284{
11285 int ret;
11286 unsigned opts;
11287
11288 /* "!": do not abort on errors */
11289 /* "+": stop at 1st non-option */
11290 opts = getopt32(argv, "!+vf");
11291 if (opts == (unsigned)-1)
11292 return EXIT_FAILURE;
11293 if (opts == 3) {
James Byrne69374872019-07-02 11:35:03 +020011294 bb_simple_error_msg("unset: -v and -f are exclusive");
Denys Vlasenko61508d92016-10-02 21:12:02 +020011295 return EXIT_FAILURE;
11296 }
11297 argv += optind;
11298
11299 ret = EXIT_SUCCESS;
11300 while (*argv) {
11301 if (!(opts & 2)) { /* not -f */
11302 if (unset_local_var(*argv)) {
11303 /* unset <nonexistent_var> doesn't fail.
11304 * Error is when one tries to unset RO var.
11305 * Message was printed by unset_local_var. */
11306 ret = EXIT_FAILURE;
11307 }
11308 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011309# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020011310 else {
11311 unset_func(*argv);
11312 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011313# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011314 argv++;
11315 }
11316 return ret;
11317}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011318#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011319
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011320#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011321/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
11322 * built-in 'set' handler
11323 * SUSv3 says:
11324 * set [-abCefhmnuvx] [-o option] [argument...]
11325 * set [+abCefhmnuvx] [+o option] [argument...]
11326 * set -- [argument...]
11327 * set -o
11328 * set +o
11329 * Implementations shall support the options in both their hyphen and
11330 * plus-sign forms. These options can also be specified as options to sh.
11331 * Examples:
11332 * Write out all variables and their values: set
11333 * Set $1, $2, and $3 and set "$#" to 3: set c a b
11334 * Turn on the -x and -v options: set -xv
11335 * Unset all positional parameters: set --
11336 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
11337 * Set the positional parameters to the expansion of x, even if x expands
11338 * with a leading '-' or '+': set -- $x
11339 *
11340 * So far, we only support "set -- [argument...]" and some of the short names.
11341 */
11342static int FAST_FUNC builtin_set(char **argv)
11343{
11344 int n;
11345 char **pp, **g_argv;
11346 char *arg = *++argv;
11347
11348 if (arg == NULL) {
11349 struct variable *e;
11350 for (e = G.top_var; e; e = e->next)
11351 puts(e->varstr);
11352 return EXIT_SUCCESS;
11353 }
11354
11355 do {
11356 if (strcmp(arg, "--") == 0) {
11357 ++argv;
11358 goto set_argv;
11359 }
11360 if (arg[0] != '+' && arg[0] != '-')
11361 break;
11362 for (n = 1; arg[n]; ++n) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020011363 if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
11364 bb_error_msg("%s: %s: invalid option", "set", arg);
11365 return EXIT_FAILURE;
11366 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011367 if (arg[n] == 'o' && argv[1])
11368 argv++;
11369 }
11370 } while ((arg = *++argv) != NULL);
11371 /* Now argv[0] is 1st argument */
11372
11373 if (arg == NULL)
11374 return EXIT_SUCCESS;
11375 set_argv:
11376
11377 /* NB: G.global_argv[0] ($0) is never freed/changed */
11378 g_argv = G.global_argv;
11379 if (G.global_args_malloced) {
11380 pp = g_argv;
11381 while (*++pp)
11382 free(*pp);
11383 g_argv[1] = NULL;
11384 } else {
11385 G.global_args_malloced = 1;
11386 pp = xzalloc(sizeof(pp[0]) * 2);
11387 pp[0] = g_argv[0]; /* retain $0 */
11388 g_argv = pp;
11389 }
11390 /* This realloc's G.global_argv */
11391 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
11392
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020011393 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020011394
11395 return EXIT_SUCCESS;
Denys Vlasenko61508d92016-10-02 21:12:02 +020011396}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011397#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011398
11399static int FAST_FUNC builtin_shift(char **argv)
11400{
11401 int n = 1;
11402 argv = skip_dash_dash(argv);
11403 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020011404 n = bb_strtou(argv[0], NULL, 10);
11405 if (errno || n < 0) {
11406 /* shared string with ash.c */
11407 bb_error_msg("Illegal number: %s", argv[0]);
11408 /*
11409 * ash aborts in this case.
11410 * bash prints error message and set $? to 1.
11411 * Interestingly, for "shift 99999" bash does not
11412 * print error message, but does set $? to 1
11413 * (and does no shifting at all).
11414 */
11415 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011416 }
11417 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010011418 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020011419 int m = 1;
11420 while (m <= n)
11421 free(G.global_argv[m++]);
11422 }
11423 G.global_argc -= n;
11424 memmove(&G.global_argv[1], &G.global_argv[n+1],
11425 G.global_argc * sizeof(G.global_argv[0]));
11426 return EXIT_SUCCESS;
11427 }
11428 return EXIT_FAILURE;
11429}
11430
Denys Vlasenko74d40582017-08-11 01:32:46 +020011431#if ENABLE_HUSH_GETOPTS
11432static int FAST_FUNC builtin_getopts(char **argv)
11433{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011434/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11435
Denys Vlasenko74d40582017-08-11 01:32:46 +020011436TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011437If a required argument is not found, and getopts is not silent,
11438a question mark (?) is placed in VAR, OPTARG is unset, and a
11439diagnostic message is printed. If getopts is silent, then a
11440colon (:) is placed in VAR and OPTARG is set to the option
11441character found.
11442
11443Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011444
11445"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011446*/
11447 char cbuf[2];
11448 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011449 int c, n, exitcode, my_opterr;
11450 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011451
11452 optstring = *++argv;
11453 if (!optstring || !(var = *++argv)) {
James Byrne69374872019-07-02 11:35:03 +020011454 bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
Denys Vlasenko74d40582017-08-11 01:32:46 +020011455 return EXIT_FAILURE;
11456 }
11457
Denys Vlasenko238ff982017-08-29 13:38:30 +020011458 if (argv[1])
11459 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11460 else
11461 argv = G.global_argv;
11462 cbuf[1] = '\0';
11463
11464 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011465 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011466 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011467 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011468 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011469 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011470
11471 /* getopts stops on first non-option. Add "+" to force that */
11472 /*if (optstring[0] != '+')*/ {
11473 char *s = alloca(strlen(optstring) + 2);
11474 sprintf(s, "+%s", optstring);
11475 optstring = s;
11476 }
11477
Denys Vlasenko238ff982017-08-29 13:38:30 +020011478 /* Naively, now we should just
11479 * cp = get_local_var_value("OPTIND");
11480 * optind = cp ? atoi(cp) : 0;
11481 * optarg = NULL;
11482 * opterr = my_opterr;
11483 * c = getopt(string_array_len(argv), argv, optstring);
11484 * and be done? Not so fast...
11485 * Unlike normal getopt() usage in C programs, here
11486 * each successive call will (usually) have the same argv[] CONTENTS,
11487 * but not the ADDRESSES. Worse yet, it's possible that between
11488 * invocations of "getopts", there will be calls to shell builtins
11489 * which use getopt() internally. Example:
11490 * while getopts "abc" RES -a -bc -abc de; do
11491 * unset -ff func
11492 * done
11493 * This would not work correctly: getopt() call inside "unset"
11494 * modifies internal libc state which is tracking position in
11495 * multi-option strings ("-abc"). At best, it can skip options
11496 * or return the same option infinitely. With glibc implementation
11497 * of getopt(), it would use outright invalid pointers and return
11498 * garbage even _without_ "unset" mangling internal state.
11499 *
11500 * We resort to resetting getopt() state and calling it N times,
11501 * until we get Nth result (or failure).
11502 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11503 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011504 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011505 count = 0;
11506 n = string_array_len(argv);
11507 do {
11508 optarg = NULL;
11509 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11510 c = getopt(n, argv, optstring);
11511 if (c < 0)
11512 break;
11513 count++;
11514 } while (count <= G.getopt_count);
11515
11516 /* Set OPTIND. Prevent resetting of the magic counter! */
11517 set_local_var_from_halves("OPTIND", utoa(optind));
11518 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011519 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011520
11521 /* Set OPTARG */
11522 /* Always set or unset, never left as-is, even on exit/error:
11523 * "If no option was found, or if the option that was found
11524 * does not have an option-argument, OPTARG shall be unset."
11525 */
11526 cp = optarg;
11527 if (c == '?') {
11528 /* If ":optstring" and unknown option is seen,
11529 * it is stored to OPTARG.
11530 */
11531 if (optstring[1] == ':') {
11532 cbuf[0] = optopt;
11533 cp = cbuf;
11534 }
11535 }
11536 if (cp)
11537 set_local_var_from_halves("OPTARG", cp);
11538 else
11539 unset_local_var("OPTARG");
11540
11541 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011542 exitcode = EXIT_SUCCESS;
11543 if (c < 0) { /* -1: end of options */
11544 exitcode = EXIT_FAILURE;
11545 c = '?';
11546 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011547
Denys Vlasenko238ff982017-08-29 13:38:30 +020011548 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011549 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011550 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011551
Denys Vlasenko74d40582017-08-11 01:32:46 +020011552 return exitcode;
11553}
11554#endif
11555
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011556static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011557{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011558 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011559 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011560 save_arg_t sv;
11561 char *args_need_save;
11562#if ENABLE_HUSH_FUNCTIONS
11563 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011564#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011565
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011566 argv = skip_dash_dash(argv);
11567 filename = argv[0];
11568 if (!filename) {
11569 /* bash says: "bash: .: filename argument required" */
11570 return 2; /* bash compat */
11571 }
11572 arg_path = NULL;
11573 if (!strchr(filename, '/')) {
11574 arg_path = find_in_path(filename);
11575 if (arg_path)
11576 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011577 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011578 errno = ENOENT;
11579 bb_simple_perror_msg(filename);
11580 return EXIT_FAILURE;
11581 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011582 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011583 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011584 free(arg_path);
11585 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011586 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011587 /* POSIX: non-interactive shell should abort here,
11588 * not merely fail. So far no one complained :)
11589 */
11590 return EXIT_FAILURE;
11591 }
11592
11593#if ENABLE_HUSH_FUNCTIONS
11594 sv_flg = G_flag_return_in_progress;
11595 /* "we are inside sourced file, ok to use return" */
11596 G_flag_return_in_progress = -1;
11597#endif
11598 args_need_save = argv[1]; /* used as a boolean variable */
11599 if (args_need_save)
11600 save_and_replace_G_args(&sv, argv);
11601
11602 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11603 G.last_exitcode = 0;
11604 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011605 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011606
11607 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11608 restore_G_args(&sv, argv);
11609#if ENABLE_HUSH_FUNCTIONS
11610 G_flag_return_in_progress = sv_flg;
11611#endif
11612
11613 return G.last_exitcode;
11614}
11615
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011616#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011617static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011618{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011619 int sig;
11620 char *new_cmd;
11621
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011622 if (!G_traps)
11623 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011624
11625 argv++;
11626 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011627 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011628 /* No args: print all trapped */
11629 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011630 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011631 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011632 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011633 /* note: bash adds "SIG", but only if invoked
11634 * as "bash". If called as "sh", or if set -o posix,
11635 * then it prints short signal names.
11636 * We are printing short names: */
11637 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011638 }
11639 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011640 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011641 return EXIT_SUCCESS;
11642 }
11643
11644 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011645 /* If first arg is a number: reset all specified signals */
11646 sig = bb_strtou(*argv, NULL, 10);
11647 if (errno == 0) {
11648 int ret;
11649 process_sig_list:
11650 ret = EXIT_SUCCESS;
11651 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011652 sighandler_t handler;
11653
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011654 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011655 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011656 ret = EXIT_FAILURE;
11657 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011658 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011659 continue;
11660 }
11661
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011662 free(G_traps[sig]);
11663 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011664
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011665 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011666 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011667
11668 /* There is no signal for 0 (EXIT) */
11669 if (sig == 0)
11670 continue;
11671
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011672 if (new_cmd)
11673 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11674 else
11675 /* We are removing trap handler */
11676 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011677 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011678 }
11679 return ret;
11680 }
11681
11682 if (!argv[1]) { /* no second arg */
James Byrne69374872019-07-02 11:35:03 +020011683 bb_simple_error_msg("trap: invalid arguments");
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011684 return EXIT_FAILURE;
11685 }
11686
11687 /* First arg is "-": reset all specified to default */
11688 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11689 /* Everything else: set arg as signal handler
11690 * (includes "" case, which ignores signal) */
11691 if (argv[0][0] == '-') {
11692 if (argv[0][1] == '\0') { /* "-" */
11693 /* new_cmd remains NULL: "reset these sigs" */
11694 goto reset_traps;
11695 }
11696 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11697 argv++;
11698 }
11699 /* else: "-something", no special meaning */
11700 }
11701 new_cmd = *argv;
11702 reset_traps:
11703 argv++;
11704 goto process_sig_list;
11705}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011706#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011707
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011708#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011709static struct pipe *parse_jobspec(const char *str)
11710{
11711 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011712 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011713
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011714 if (sscanf(str, "%%%u", &jobnum) != 1) {
11715 if (str[0] != '%'
11716 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11717 ) {
11718 bb_error_msg("bad argument '%s'", str);
11719 return NULL;
11720 }
11721 /* It is "%%", "%+" or "%" - current job */
11722 jobnum = G.last_jobid;
11723 if (jobnum == 0) {
James Byrne69374872019-07-02 11:35:03 +020011724 bb_simple_error_msg("no current job");
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011725 return NULL;
11726 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011727 }
11728 for (pi = G.job_list; pi; pi = pi->next) {
11729 if (pi->jobid == jobnum) {
11730 return pi;
11731 }
11732 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011733 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011734 return NULL;
11735}
11736
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011737static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11738{
11739 struct pipe *job;
11740 const char *status_string;
11741
11742 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11743 for (job = G.job_list; job; job = job->next) {
11744 if (job->alive_cmds == job->stopped_cmds)
11745 status_string = "Stopped";
11746 else
11747 status_string = "Running";
11748
11749 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11750 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011751
11752 clean_up_last_dead_job();
11753
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011754 return EXIT_SUCCESS;
11755}
11756
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011757/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011758static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011759{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011760 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011761 struct pipe *pi;
11762
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011763 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011764 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011765
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011766 /* If they gave us no args, assume they want the last backgrounded task */
11767 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011768 for (pi = G.job_list; pi; pi = pi->next) {
11769 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011770 goto found;
11771 }
11772 }
11773 bb_error_msg("%s: no current job", argv[0]);
11774 return EXIT_FAILURE;
11775 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011776
11777 pi = parse_jobspec(argv[1]);
11778 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011779 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011780 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011781 /* TODO: bash prints a string representation
11782 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011783 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denys Vlasenko62f1eed2021-10-12 22:39:11 +020011784 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011785 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011786 }
11787
11788 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011789 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11790 for (i = 0; i < pi->num_cmds; i++) {
11791 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011792 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011793 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011794
11795 i = kill(- pi->pgrp, SIGCONT);
11796 if (i < 0) {
11797 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011798 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011799 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011800 }
James Byrne69374872019-07-02 11:35:03 +020011801 bb_simple_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011802 }
11803
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011804 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011805 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011806 return checkjobs_and_fg_shell(pi);
11807 }
11808 return EXIT_SUCCESS;
11809}
11810#endif
11811
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011812#if ENABLE_HUSH_KILL
11813static int FAST_FUNC builtin_kill(char **argv)
11814{
11815 int ret = 0;
11816
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011817# if ENABLE_HUSH_JOB
11818 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11819 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011820
11821 do {
11822 struct pipe *pi;
11823 char *dst;
11824 int j, n;
11825
11826 if (argv[i][0] != '%')
11827 continue;
11828 /*
11829 * "kill %N" - job kill
11830 * Converting to pgrp / pid kill
11831 */
11832 pi = parse_jobspec(argv[i]);
11833 if (!pi) {
11834 /* Eat bad jobspec */
11835 j = i;
11836 do {
11837 j++;
11838 argv[j - 1] = argv[j];
11839 } while (argv[j]);
11840 ret = 1;
11841 i--;
11842 continue;
11843 }
11844 /*
11845 * In jobs started under job control, we signal
11846 * entire process group by kill -PGRP_ID.
11847 * This happens, f.e., in interactive shell.
11848 *
11849 * Otherwise, we signal each child via
11850 * kill PID1 PID2 PID3.
11851 * Testcases:
11852 * sh -c 'sleep 1|sleep 1 & kill %1'
11853 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11854 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11855 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011856 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011857 dst = alloca(n * sizeof(int)*4);
11858 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011859 if (G_interactive_fd)
11860 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011861 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011862 struct command *cmd = &pi->cmds[j];
11863 /* Skip exited members of the job */
11864 if (cmd->pid == 0)
11865 continue;
11866 /*
11867 * kill_main has matching code to expect
11868 * leading space. Needed to not confuse
11869 * negative pids with "kill -SIGNAL_NO" syntax
11870 */
11871 dst += sprintf(dst, " %u", (int)cmd->pid);
11872 }
11873 *dst = '\0';
11874 } while (argv[++i]);
11875 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011876# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011877
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011878 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011879 ret = run_applet_main(argv, kill_main);
11880 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011881 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011882 return ret;
11883}
11884#endif
11885
11886#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011887/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011888# if !ENABLE_HUSH_JOB
11889# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11890# endif
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011891static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011892{
11893 int ret = 0;
11894 for (;;) {
11895 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011896 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011897
Denys Vlasenko830ea352016-11-08 04:59:11 +010011898 if (!sigisemptyset(&G.pending_set))
11899 goto check_sig;
11900
Denys Vlasenko7e675362016-10-28 21:57:31 +020011901 /* waitpid is not interruptible by SA_RESTARTed
11902 * signals which we use. Thus, this ugly dance:
11903 */
11904
11905 /* Make sure possible SIGCHLD is stored in kernel's
11906 * pending signal mask before we call waitpid.
11907 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011908 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011909 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011910 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011911 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011912
11913 if (!sigisemptyset(&G.pending_set)) {
11914 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011915 goto restore;
11916 }
11917
11918 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011919/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011920 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011921 debug_printf_exec("checkjobs:%d\n", ret);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011922# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011923 if (waitfor_pipe) {
11924 int rcode = job_exited_or_stopped(waitfor_pipe);
11925 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11926 if (rcode >= 0) {
11927 ret = rcode;
11928 sigprocmask(SIG_SETMASK, &oldset, NULL);
11929 break;
11930 }
11931 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011932# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011933 /* if ECHILD, there are no children (ret is -1 or 0) */
11934 /* if ret == 0, no children changed state */
11935 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011936 if (errno == ECHILD || ret) {
11937 ret--;
11938 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011939 ret = 0;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011940# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011941 if (waitfor_pid == -1 && errno == ECHILD) {
11942 /* exitcode of "wait -n" with no children is 127, not 0 */
11943 ret = 127;
11944 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011945# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011946 sigprocmask(SIG_SETMASK, &oldset, NULL);
11947 break;
11948 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011949 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011950 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11951 /* Note: sigsuspend invokes signal handler */
11952 sigsuspend(&oldset);
Denys Vlasenko23bc5622020-02-18 16:46:01 +010011953 /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
11954 * to make sure SIGCHLD is not masked off?
11955 * It was reported that this:
11956 * fn() { : | return; }
11957 * shopt -s lastpipe
11958 * fn
11959 * exec hush SCRIPT
11960 * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
11961 * making "wait" commands in SCRIPT block forever.
11962 */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011963 restore:
11964 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011965 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011966 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011967 sig = check_and_run_traps();
11968 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011969 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko93e2a222020-12-23 12:23:21 +010011970 ret = 128 | sig;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011971 break;
11972 }
11973 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11974 }
11975 return ret;
11976}
11977
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011978static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011979{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011980 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011981 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011982
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011983 argv = skip_dash_dash(argv);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011984# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011985 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011986 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011987 /* (bash accepts "wait -n PID" too and ignores PID) */
11988 G.dead_job_exitcode = -1;
11989 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011990 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011991# endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011992 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011993 /* Don't care about wait results */
11994 /* Note 1: must wait until there are no more children */
11995 /* Note 2: must be interruptible */
11996 /* Examples:
11997 * $ sleep 3 & sleep 6 & wait
11998 * [1] 30934 sleep 3
11999 * [2] 30935 sleep 6
12000 * [1] Done sleep 3
12001 * [2] Done sleep 6
12002 * $ sleep 3 & sleep 6 & wait
12003 * [1] 30936 sleep 3
12004 * [2] 30937 sleep 6
12005 * [1] Done sleep 3
12006 * ^C <-- after ~4 sec from keyboard
12007 * $
12008 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010012009 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000012010 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000012011
Denys Vlasenko7e675362016-10-28 21:57:31 +020012012 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000012013 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020012014 if (errno || pid <= 0) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010012015# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010012016 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010012017 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010012018 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010012019 wait_pipe = parse_jobspec(*argv);
12020 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010012021 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020012022 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010012023 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020012024 } else {
12025 /* waiting on "last dead job" removes it */
12026 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020012027 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010012028 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010012029 /* else: parse_jobspec() already emitted error msg */
12030 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010012031 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010012032# endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000012033 /* mimic bash message */
12034 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012035 ret = EXIT_FAILURE;
12036 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000012037 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010012038
Denys Vlasenko7e675362016-10-28 21:57:31 +020012039 /* Do we have such child? */
12040 ret = waitpid(pid, &status, WNOHANG);
12041 if (ret < 0) {
12042 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020012043 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020012044 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020012045 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012046 /* "wait $!" but last bg task has already exited. Try:
12047 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
12048 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010012049 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012050 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020012051 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010012052 } else {
12053 /* Example: "wait 1". mimic bash message */
Denys Vlasenko259747c2019-11-28 10:28:14 +010012054 bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012055 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020012056 } else {
12057 /* ??? */
12058 bb_perror_msg("wait %s", *argv);
12059 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012060 continue; /* bash checks all argv[] */
12061 }
12062 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020012063 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010012064 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020012065 } else {
12066 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010012067 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020012068 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000012069 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +010012070 ret = 128 | WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000012071 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012072 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000012073
12074 return ret;
12075}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010012076#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000012077
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012078#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
12079static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
12080{
12081 if (argv[1]) {
12082 def = bb_strtou(argv[1], NULL, 10);
12083 if (errno || def < def_min || argv[2]) {
12084 bb_error_msg("%s: bad arguments", argv[0]);
12085 def = UINT_MAX;
12086 }
12087 }
12088 return def;
12089}
12090#endif
12091
Denis Vlasenkodadfb492008-07-29 10:16:05 +000012092#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012093static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012094{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012095 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000012096 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000012097 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020012098 /* if we came from builtin_continue(), need to undo "= 1" */
12099 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000012100 return EXIT_SUCCESS; /* bash compat */
12101 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020012102 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012103
12104 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
12105 if (depth == UINT_MAX)
12106 G.flag_break_continue = BC_BREAK;
12107 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000012108 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012109
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012110 return EXIT_SUCCESS;
12111}
12112
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012113static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012114{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000012115 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
12116 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012117}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000012118#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012119
12120#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012121static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012122{
12123 int rc;
12124
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020012125 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012126 bb_error_msg("%s: not in a function or sourced script", argv[0]);
12127 return EXIT_FAILURE; /* bash compat */
12128 }
12129
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020012130 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012131
12132 /* bash:
12133 * out of range: wraps around at 256, does not error out
12134 * non-numeric param:
12135 * f() { false; return qwe; }; f; echo $?
12136 * bash: return: qwe: numeric argument required <== we do this
12137 * 255 <== we also do this
12138 */
12139 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
Denys Vlasenkobb095f42020-02-20 16:37:59 +010012140# if ENABLE_HUSH_TRAP
12141 if (argv[1]) { /* "return ARG" inside a running trap sets $? */
12142 debug_printf_exec("G.return_exitcode=%d\n", rc);
12143 G.return_exitcode = rc;
12144 }
12145# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012146 return rc;
12147}
12148#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010012149
Denys Vlasenko11f2e992017-08-10 16:34:03 +020012150#if ENABLE_HUSH_TIMES
12151static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
12152{
12153 static const uint8_t times_tbl[] ALIGN1 = {
12154 ' ', offsetof(struct tms, tms_utime),
12155 '\n', offsetof(struct tms, tms_stime),
12156 ' ', offsetof(struct tms, tms_cutime),
12157 '\n', offsetof(struct tms, tms_cstime),
12158 0
12159 };
12160 const uint8_t *p;
12161 unsigned clk_tck;
12162 struct tms buf;
12163
12164 clk_tck = bb_clk_tck();
12165
12166 times(&buf);
12167 p = times_tbl;
12168 do {
12169 unsigned sec, frac;
12170 unsigned long t;
12171 t = *(clock_t *)(((char *) &buf) + p[1]);
12172 sec = t / clk_tck;
12173 frac = t % clk_tck;
12174 printf("%um%u.%03us%c",
12175 sec / 60, sec % 60,
12176 (frac * 1000) / clk_tck,
12177 p[0]);
12178 p += 2;
12179 } while (*p);
12180
12181 return EXIT_SUCCESS;
12182}
12183#endif
12184
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010012185#if ENABLE_HUSH_MEMLEAK
12186static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
12187{
12188 void *p;
12189 unsigned long l;
12190
12191# ifdef M_TRIM_THRESHOLD
12192 /* Optional. Reduces probability of false positives */
12193 malloc_trim(0);
12194# endif
12195 /* Crude attempt to find where "free memory" starts,
12196 * sans fragmentation. */
12197 p = malloc(240);
12198 l = (unsigned long)p;
12199 free(p);
12200 p = malloc(3400);
12201 if (l < (unsigned long)p) l = (unsigned long)p;
12202 free(p);
12203
12204
12205# if 0 /* debug */
12206 {
12207 struct mallinfo mi = mallinfo();
12208 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
12209 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
12210 }
12211# endif
12212
12213 if (!G.memleak_value)
12214 G.memleak_value = l;
12215
12216 l -= G.memleak_value;
12217 if ((long)l < 0)
12218 l = 0;
12219 l /= 1024;
12220 if (l > 127)
12221 l = 127;
12222
12223 /* Exitcode is "how many kilobytes we leaked since 1st call" */
12224 return l;
12225}
12226#endif