blob: 6d472337fb398662f50e09345cff7f88b1074476 [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 Vlasenko1f60d882021-06-15 10:00:18 +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
Ron Yorston71df2d32018-11-27 14:34:25 +0000376#if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
377# 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
567static const char *const assignment_flag[] = {
568 "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
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000921 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000922#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000923 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000924#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000925#if ENABLE_HUSH_FUNCTIONS
926 /* 0: outside of a function (or sourced file)
927 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000928 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000929 */
930 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200931# define G_flag_return_in_progress (G.flag_return_in_progress)
932#else
933# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000934#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000935 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100936 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000937 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200938 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200939 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100940#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000941 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000942 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100943# define G_global_args_malloced (G.global_args_malloced)
944#else
945# define G_global_args_malloced 0
946#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100947#if ENABLE_HUSH_BASH_COMPAT
948 int dead_job_exitcode; /* for "wait -n" */
949#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000950 /* how many non-NULL argv's we have. NB: $# + 1 */
951 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000952 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000953#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000954 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000955#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000956#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000957 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000958 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000959#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200960#if ENABLE_HUSH_GETOPTS
961 unsigned getopt_count;
962#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000963 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200964 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000965 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200966 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200967 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200968 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200969 unsigned var_nest_level;
970#if ENABLE_HUSH_FUNCTIONS
971# if ENABLE_HUSH_LOCAL
972 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200973# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200974 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000975#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000976 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200977#if ENABLE_HUSH_FAST
978 unsigned count_SIGCHLD;
979 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200980 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200981#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100982#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +0200983 unsigned parse_lineno;
984 unsigned execute_lineno;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100985#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200986 HFILE *HFILE_list;
Denys Vlasenko21806562019-11-01 14:16:07 +0100987 HFILE *HFILE_stdin;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200988 /* Which signals have non-DFL handler (even with no traps set)?
989 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200990 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200991 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200992 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200993 * Other than these two times, never modified.
994 */
995 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200996#if ENABLE_HUSH_JOB
997 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100998# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200999#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001000# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001001#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001002#if ENABLE_HUSH_TRAP
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01001003 int pre_trap_exitcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01001004# if ENABLE_HUSH_FUNCTIONS
1005 int return_exitcode;
1006# endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001007 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001008# define G_traps G.traps
1009#else
1010# define G_traps ((char**)NULL)
1011#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001012 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +01001013#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001014 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +01001015#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001016#if ENABLE_HUSH_MODE_X
1017 unsigned x_mode_depth;
1018 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1019 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1020 * for all subsequent output.
1021 */
1022 int x_mode_fd;
1023 o_string x_mode_buf;
1024#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001025#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001026 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001027#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001028 struct sigaction sa;
Denys Vlasenkof3634582019-06-03 12:21:04 +02001029 char optstring_buf[sizeof("eixcs")];
Ron Yorstona81700b2019-04-15 10:48:29 +01001030#if BASH_EPOCH_VARS
Denys Vlasenko3c13da32020-12-30 23:48:01 +01001031 char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
Ron Yorstona81700b2019-04-15 10:48:29 +01001032#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001033#if ENABLE_FEATURE_EDITING
1034 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1035#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001036};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001037#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001038/* Not #defining name to G.name - this quickly gets unwieldy
1039 * (too many defines). Also, I actually prefer to see when a variable
1040 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001041#define INIT_G() do { \
1042 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001043 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1044 sigfillset(&G.sa.sa_mask); \
1045 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001046} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001047
1048
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001049/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001050static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001051#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001052static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001053#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_eval(char **argv) FAST_FUNC;
1055static int builtin_exec(char **argv) FAST_FUNC;
1056static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001057#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001058static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001059#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001060#if ENABLE_HUSH_READONLY
1061static int builtin_readonly(char **argv) FAST_FUNC;
1062#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001063#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001064static int builtin_fg_bg(char **argv) FAST_FUNC;
1065static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001066#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001067#if ENABLE_HUSH_GETOPTS
1068static int builtin_getopts(char **argv) FAST_FUNC;
1069#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001070#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001071static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001072#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001073#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001074static int builtin_history(char **argv) FAST_FUNC;
1075#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001076#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001077static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001078#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001079#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001080static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001081#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001082#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001083static int builtin_printf(char **argv) FAST_FUNC;
1084#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001085static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001086#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001087static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001088#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001089#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001090static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001091#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001092static int builtin_shift(char **argv) FAST_FUNC;
1093static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001094#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001095static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001096#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001097#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001098static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001099#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001100#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001101static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001102#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001103#if ENABLE_HUSH_TIMES
1104static int builtin_times(char **argv) FAST_FUNC;
1105#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001106static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001107#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001108static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001109#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001110#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001111static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001112#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001113#if ENABLE_HUSH_KILL
1114static int builtin_kill(char **argv) FAST_FUNC;
1115#endif
1116#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001117static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001118#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001119#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001120static int builtin_break(char **argv) FAST_FUNC;
1121static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001122#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001123#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001124static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001125#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001126
1127/* Table of built-in functions. They can be forked or not, depending on
1128 * context: within pipes, they fork. As simple commands, they do not.
1129 * When used in non-forking context, they can change global variables
1130 * in the parent shell process. If forked, of course they cannot.
1131 * For example, 'unset foo | whatever' will parse and run, but foo will
1132 * still be set at the end. */
1133struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001134 const char *b_cmd;
1135 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001136#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001137 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001138# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001139#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001140# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001141#endif
1142};
1143
Denys Vlasenko965b7952020-11-30 13:03:03 +01001144static const struct built_in_command bltins1[] ALIGN_PTR = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001145 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001146 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001147#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001148 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001149#endif
1150#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001151 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001152#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001153 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001154#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001156#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001157 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1158 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001159 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001160#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001161 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001162#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001163#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001164 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001165#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001166#if ENABLE_HUSH_GETOPTS
1167 BLTIN("getopts" , builtin_getopts , NULL),
1168#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001169#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001171#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001172#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001173 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001174#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001175#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001176 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001177#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001178#if ENABLE_HUSH_KILL
1179 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1180#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001181#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001182 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001183#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001184#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001185 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001186#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001187#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001188 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001189#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001190#if ENABLE_HUSH_READONLY
1191 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1192#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001193#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001194 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001195#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001196#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001197 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001198#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001199 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001200#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001201 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001202#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001203#if ENABLE_HUSH_TIMES
1204 BLTIN("times" , builtin_times , NULL),
1205#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001206#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001207 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001208#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001209 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001210#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001211 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001212#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001213#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001214 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001215#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001216#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001217 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001218#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001219#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001220 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001221#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001222#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001223 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001224#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001225};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001226/* These builtins won't be used if we are on NOMMU and need to re-exec
1227 * (it's cheaper to run an external program in this case):
1228 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01001229static const struct built_in_command bltins2[] ALIGN_PTR = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001230#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001231 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001232#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001233#if BASH_TEST2
1234 BLTIN("[[" , builtin_test , NULL),
1235#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001236#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001237 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001238#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001239#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001240 BLTIN("printf" , builtin_printf , NULL),
1241#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001242 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001243#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001244 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001245#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001246};
1247
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001248
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001249/* Debug printouts.
1250 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001251#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001252/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001253# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001254# define debug_enter() (G.debug_indent++)
1255# define debug_leave() (G.debug_indent--)
1256#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001257# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258# define debug_enter() ((void)0)
1259# define debug_leave() ((void)0)
1260#endif
1261
1262#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001263# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001264#endif
1265
1266#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001267# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001268#endif
1269
Denys Vlasenko3675c372018-07-23 16:31:21 +02001270#ifndef debug_printf_heredoc
1271# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1272#endif
1273
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001274#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001275#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001276#endif
1277
1278#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001279# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001280#endif
1281
1282#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001283# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001284# define DEBUG_JOBS 1
1285#else
1286# define DEBUG_JOBS 0
1287#endif
1288
1289#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001290# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001291# define DEBUG_EXPAND 1
1292#else
1293# define DEBUG_EXPAND 0
1294#endif
1295
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001296#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001297# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001298#endif
1299
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001300#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001301# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001302# define DEBUG_GLOB 1
1303#else
1304# define DEBUG_GLOB 0
1305#endif
1306
Denys Vlasenko2db74612017-07-07 22:07:28 +02001307#ifndef debug_printf_redir
1308# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1309#endif
1310
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001311#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001312# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001313#endif
1314
1315#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001316# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001317#endif
1318
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001319#ifndef debug_printf_prompt
1320# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1321#endif
1322
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001323#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001324# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001325# define DEBUG_CLEAN 1
1326#else
1327# define DEBUG_CLEAN 0
1328#endif
1329
1330#if DEBUG_EXPAND
1331static void debug_print_strings(const char *prefix, char **vv)
1332{
1333 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001334 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001335 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001336 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001337}
1338#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001339# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001340#endif
1341
1342
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001343/* Leak hunting. Use hush_leaktool.sh for post-processing.
1344 */
1345#if LEAK_HUNTING
1346static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001347{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001348 void *ptr = xmalloc((size + 0xff) & ~0xff);
1349 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1350 return ptr;
1351}
1352static void *xxrealloc(int lineno, void *ptr, size_t size)
1353{
1354 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1355 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1356 return ptr;
1357}
1358static char *xxstrdup(int lineno, const char *str)
1359{
1360 char *ptr = xstrdup(str);
1361 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1362 return ptr;
1363}
1364static void xxfree(void *ptr)
1365{
1366 fdprintf(2, "free %p\n", ptr);
1367 free(ptr);
1368}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001369# define xmalloc(s) xxmalloc(__LINE__, s)
1370# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1371# define xstrdup(s) xxstrdup(__LINE__, s)
1372# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001373#endif
1374
1375
1376/* Syntax and runtime errors. They always abort scripts.
1377 * In interactive use they usually discard unparsed and/or unexecuted commands
1378 * and return to the prompt.
1379 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1380 */
1381#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001382# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001383# define syntax_error(lineno, msg) syntax_error(msg)
1384# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1385# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1386# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1387# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001388#endif
1389
Denys Vlasenko39701202017-08-02 19:44:05 +02001390static void die_if_script(void)
1391{
1392 if (!G_interactive_fd) {
1393 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1394 xfunc_error_retval = G.last_exitcode;
1395 xfunc_die();
1396 }
1397}
1398
1399static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001400{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001401 va_list p;
1402
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001403#if HUSH_DEBUG >= 2
1404 bb_error_msg("hush.c:%u", lineno);
1405#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001406 va_start(p, fmt);
1407 bb_verror_msg(fmt, p, NULL);
1408 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001409 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001410}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001411
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001412static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001413{
1414 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001415 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001416 else
James Byrne69374872019-07-02 11:35:03 +02001417 bb_simple_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001418 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001419}
1420
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001421static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001422{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001423 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001424 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001425}
1426
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001427static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001428{
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01001429 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001430//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1431// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001432}
1433
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001434static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001435{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001436 char msg[2] = { ch, '\0' };
1437 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001438}
1439
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001440static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001441{
1442 char msg[2];
1443 msg[0] = ch;
1444 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001445#if HUSH_DEBUG >= 2
1446 bb_error_msg("hush.c:%u", lineno);
1447#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001448 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001449 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001450}
1451
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001452#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001453# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001454# undef syntax_error
1455# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001456# undef syntax_error_unterm_ch
1457# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001458# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001459#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001460# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001461# define syntax_error(msg) syntax_error(__LINE__, msg)
1462# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1463# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1464# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1465# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001466#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001467
Denis Vlasenko552433b2009-04-04 19:29:21 +00001468
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001469/* Utility functions
1470 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001471/* Replace each \x with x in place, return ptr past NUL. */
1472static char *unbackslash(char *src)
1473{
Denys Vlasenko71885402009-09-24 01:44:13 +02001474 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001475 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001476 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001477 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001478 if (*src != '\0') {
1479 /* \x -> x */
1480 *dst++ = *src++;
1481 continue;
1482 }
1483 /* else: "\<nul>". Do not delete this backslash.
1484 * Testcase: eval 'echo ok\'
1485 */
1486 *dst++ = '\\';
1487 /* fallthrough */
1488 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001489 if ((*dst++ = *src++) == '\0')
1490 break;
1491 }
1492 return dst;
1493}
1494
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001495static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001496{
1497 int i;
1498 unsigned count1;
1499 unsigned count2;
1500 char **v;
1501
1502 v = strings;
1503 count1 = 0;
1504 if (v) {
1505 while (*v) {
1506 count1++;
1507 v++;
1508 }
1509 }
1510 count2 = 0;
1511 v = add;
1512 while (*v) {
1513 count2++;
1514 v++;
1515 }
1516 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1517 v[count1 + count2] = NULL;
1518 i = count2;
1519 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001520 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001521 return v;
1522}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001523#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001524static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1525{
1526 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1527 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1528 return ptr;
1529}
1530#define add_strings_to_strings(strings, add, need_to_dup) \
1531 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1532#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001533
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001534/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001535static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001536{
1537 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001538 v[0] = add;
1539 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001540 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001541}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001542#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001543static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1544{
1545 char **ptr = add_string_to_strings(strings, add);
1546 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1547 return ptr;
1548}
1549#define add_string_to_strings(strings, add) \
1550 xx_add_string_to_strings(__LINE__, strings, add)
1551#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001552
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001553static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001554{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001555 char **v;
1556
1557 if (!strings)
1558 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001559 v = strings;
1560 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001561 free(*v);
1562 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001563 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001564 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001565}
1566
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001567static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001568{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001569 int newfd;
1570 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001571 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1572 if (newfd >= 0) {
1573 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1574 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1575 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001576 if (errno == EBUSY)
1577 goto repeat;
1578 if (errno == EINTR)
1579 goto repeat;
1580 }
1581 return newfd;
1582}
1583
Denys Vlasenko657e9002017-07-30 23:34:04 +02001584static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001585{
1586 int newfd;
1587 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001588 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001589 if (newfd < 0) {
1590 if (errno == EBUSY)
1591 goto repeat;
1592 if (errno == EINTR)
1593 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001594 /* fd was not open? */
1595 if (errno == EBADF)
1596 return fd;
1597 xfunc_die();
1598 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001599 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1600 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001601 close(fd);
1602 return newfd;
1603}
1604
1605
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001606/* Manipulating HFILEs */
1607static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001608{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001609 HFILE *fp;
1610 int fd;
1611
1612 fd = STDIN_FILENO;
1613 if (name) {
1614 fd = open(name, O_RDONLY | O_CLOEXEC);
1615 if (fd < 0)
1616 return NULL;
1617 if (O_CLOEXEC == 0) /* ancient libc */
1618 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001619 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001620
1621 fp = xmalloc(sizeof(*fp));
Denys Vlasenko21806562019-11-01 14:16:07 +01001622 if (name == NULL)
1623 G.HFILE_stdin = fp;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001624 fp->fd = fd;
1625 fp->cur = fp->end = fp->buf;
1626 fp->next_hfile = G.HFILE_list;
1627 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001628 return fp;
1629}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001630static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001631{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001632 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001633 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001634 HFILE *cur = *pp;
1635 if (cur == fp) {
1636 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001637 break;
1638 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001639 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001640 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001641 if (fp->fd >= 0)
1642 close(fp->fd);
1643 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001644}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001645static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001646{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001647 int n;
1648
1649 if (fp->fd < 0) {
1650 /* Already saw EOF */
1651 return EOF;
1652 }
Denys Vlasenko521220e2020-12-23 23:44:55 +01001653#if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
1654 /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
1655 * IOW: ^C will not immediately stop line input.
1656 * But poll() is different: it does NOT restart after signals.
1657 */
1658 if (fp == G.HFILE_stdin) {
1659 struct pollfd pfd[1];
1660 pfd[0].fd = fp->fd;
1661 pfd[0].events = POLLIN;
1662 n = poll(pfd, 1, -1);
1663 if (n < 0
1664 /*&& errno == EINTR - assumed true */
1665 && sigismember(&G.pending_set, SIGINT)
1666 ) {
1667 return '\0';
1668 }
1669 }
1670#else
1671/* if FEATURE_EDITING=y, we do not use this routine for interactive input */
1672#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001673 /* Try to buffer more input */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001674 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1675 if (n < 0) {
James Byrne69374872019-07-02 11:35:03 +02001676 bb_simple_perror_msg("read error");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001677 n = 0;
1678 }
Denys Vlasenko93e2a222020-12-23 12:23:21 +01001679 fp->cur = fp->buf;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001680 fp->end = fp->buf + n;
1681 if (n == 0) {
1682 /* EOF/error */
1683 close(fp->fd);
1684 fp->fd = -1;
1685 return EOF;
1686 }
1687 return (unsigned char)(*fp->cur++);
1688}
1689/* Inlined for common case of non-empty buffer.
1690 */
1691static ALWAYS_INLINE int hfgetc(HFILE *fp)
1692{
1693 if (fp->cur < fp->end)
1694 return (unsigned char)(*fp->cur++);
1695 /* Buffer empty */
1696 return refill_HFILE_and_getc(fp);
1697}
1698static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1699{
1700 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001701 while (fl) {
1702 if (fd == fl->fd) {
1703 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001704 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001705 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 +02001706 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001707 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001708 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001709 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001710#if ENABLE_HUSH_MODE_X
1711 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1712 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1713 return 1; /* "found and moved" */
1714 }
1715#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001716 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001717}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001718#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001719static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001720{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001721 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001722 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001723 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001724 * It is disastrous if we share memory with a vforked parent.
1725 * I'm not sure we never come here after vfork.
1726 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001727 *
1728 * ">" instead of ">=": we don't close fd#0,
1729 * interactive shell uses hfopen(NULL) as stdin input
1730 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1731 * If we'd close it here, then e.g. interactive "set | sort"
1732 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001733 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001734 if (fl->fd > 0)
1735 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001736 close(fl->fd);
1737 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001738 }
1739}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001740#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001741static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001742{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001743 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001744 while (fl) {
1745 if (fl->fd == fd)
1746 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001747 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001748 }
1749 return 0;
1750}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001751
1752
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001753/* Helpers for setting new $n and restoring them back
1754 */
1755typedef struct save_arg_t {
1756 char *sv_argv0;
1757 char **sv_g_argv;
1758 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001759 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001760} save_arg_t;
1761
1762static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1763{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001764 sv->sv_argv0 = argv[0];
1765 sv->sv_g_argv = G.global_argv;
1766 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001767 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001768
1769 argv[0] = G.global_argv[0]; /* retain $0 */
1770 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001771 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001772
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001773 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001774}
1775
1776static void restore_G_args(save_arg_t *sv, char **argv)
1777{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001778#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001779 if (G.global_args_malloced) {
1780 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001781 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001782 while (*++pp) /* note: does not free $0 */
1783 free(*pp);
1784 free(G.global_argv);
1785 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001786#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001787 argv[0] = sv->sv_argv0;
1788 G.global_argv = sv->sv_g_argv;
1789 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001790 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001791}
1792
1793
Denis Vlasenkod5762932009-03-31 11:22:57 +00001794/* Basic theory of signal handling in shell
1795 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001796 * This does not describe what hush does, rather, it is current understanding
1797 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001798 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1799 *
1800 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1801 * is finished or backgrounded. It is the same in interactive and
1802 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001803 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001804 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001805 * backgrounds (i.e. stops) or kills all members of currently running
1806 * pipe.
1807 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001808 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001809 * or by SIGINT in interactive shell.
1810 *
1811 * Trap handlers will execute even within trap handlers. (right?)
1812 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001813 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1814 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001815 *
1816 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001817 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001818 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001819 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001820 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001821 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001822 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001823 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001824 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001825 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001826 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001827 *
1828 * SIGQUIT: ignore
1829 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001830 * SIGHUP (interactive):
1831 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001832 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001833 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1834 * that all pipe members are stopped. Try this in bash:
1835 * while :; do :; done - ^Z does not background it
1836 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001837 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001838 * of the command line, show prompt. NB: ^C does not send SIGINT
1839 * to interactive shell while shell is waiting for a pipe,
1840 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001841 * Example 1: this waits 5 sec, but does not execute ls:
1842 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1843 * Example 2: this does not wait and does not execute ls:
1844 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1845 * Example 3: this does not wait 5 sec, but executes ls:
1846 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001847 * Example 4: this does not wait and does not execute ls:
1848 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001849 *
1850 * (What happens to signals which are IGN on shell start?)
1851 * (What happens with signal mask on shell start?)
1852 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001853 * Old implementation
1854 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001855 * We use in-kernel pending signal mask to determine which signals were sent.
1856 * We block all signals which we don't want to take action immediately,
1857 * i.e. we block all signals which need to have special handling as described
1858 * above, and all signals which have traps set.
1859 * After each pipe execution, we extract any pending signals via sigtimedwait()
1860 * and act on them.
1861 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001862 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001863 * sigset_t blocked_set: current blocked signal set
1864 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001865 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001866 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001867 * "trap 'cmd' SIGxxx":
1868 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001869 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001870 * unblock signals with special interactive handling
1871 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001872 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001873 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001874 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001875 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001876 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001877 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001878 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001879 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001880 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001881 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001882 * Standard says "When a subshell is entered, traps that are not being ignored
1883 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001884 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001885 *
1886 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001887 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001888 * masked signals are not visible!
1889 *
1890 * New implementation
1891 * ==================
1892 * We record each signal we are interested in by installing signal handler
1893 * for them - a bit like emulating kernel pending signal mask in userspace.
1894 * We are interested in: signals which need to have special handling
1895 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001896 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001897 * After each pipe execution, we extract any pending signals
1898 * and act on them.
1899 *
1900 * unsigned special_sig_mask: a mask of shell-special signals.
1901 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1902 * char *traps[sig] if trap for sig is set (even if it's '').
1903 * sigset_t pending_set: set of sigs we received.
1904 *
1905 * "trap - SIGxxx":
1906 * if sig is in special_sig_mask, set handler back to:
1907 * record_pending_signo, or to IGN if it's a tty stop signal
1908 * if sig is in fatal_sig_mask, set handler back to sigexit.
1909 * else: set handler back to SIG_DFL
1910 * "trap 'cmd' SIGxxx":
1911 * set handler to record_pending_signo.
1912 * "trap '' SIGxxx":
1913 * set handler to SIG_IGN.
1914 * after [v]fork, if we plan to be a shell:
1915 * set signals with special interactive handling to SIG_DFL
1916 * (because child shell is not interactive),
1917 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1918 * after [v]fork, if we plan to exec:
1919 * POSIX says fork clears pending signal mask in child - no need to clear it.
1920 *
1921 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1922 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1923 *
1924 * Note (compat):
1925 * Standard says "When a subshell is entered, traps that are not being ignored
1926 * are set to the default actions". bash interprets it so that traps which
1927 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001928 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001929enum {
1930 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001931 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001932 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001933 | (1 << SIGHUP)
1934 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001935 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001936#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001937 | (1 << SIGTTIN)
1938 | (1 << SIGTTOU)
1939 | (1 << SIGTSTP)
1940#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001941 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001942};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001943
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001944static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001945{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001946 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001947#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001948 if (sig == SIGCHLD) {
1949 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001950//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 +02001951 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001952#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001953}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001954
Denys Vlasenko0806e402011-05-12 23:06:20 +02001955static sighandler_t install_sighandler(int sig, sighandler_t handler)
1956{
1957 struct sigaction old_sa;
1958
1959 /* We could use signal() to install handlers... almost:
1960 * except that we need to mask ALL signals while handlers run.
1961 * I saw signal nesting in strace, race window isn't small.
1962 * SA_RESTART is also needed, but in Linux, signal()
1963 * sets SA_RESTART too.
1964 */
1965 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1966 /* sigfillset(&G.sa.sa_mask); - already done */
1967 /* G.sa.sa_flags = SA_RESTART; - already done */
1968 G.sa.sa_handler = handler;
1969 sigaction(sig, &G.sa, &old_sa);
1970 return old_sa.sa_handler;
1971}
1972
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001973static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001974
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001975static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001976static void restore_ttypgrp_and__exit(void)
1977{
1978 /* xfunc has failed! die die die */
1979 /* no EXIT traps, this is an escape hatch! */
1980 G.exiting = 1;
1981 hush_exit(xfunc_error_retval);
1982}
1983
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001984#if ENABLE_HUSH_JOB
1985
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001986/* Needed only on some libc:
1987 * It was observed that on exit(), fgetc'ed buffered data
1988 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1989 * With the net effect that even after fork(), not vfork(),
1990 * exit() in NOEXECed applet in "sh SCRIPT":
1991 * noexec_applet_here
1992 * echo END_OF_SCRIPT
1993 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1994 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001995 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001996 * and in `cmd` handling.
1997 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1998 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001999static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002000static void fflush_and__exit(void)
2001{
2002 fflush_all();
2003 _exit(xfunc_error_retval);
2004}
2005
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002006/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002007# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00002008/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002009# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002010
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002011/* Restores tty foreground process group, and exits.
2012 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002013 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002014 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002015 * We also call it if xfunc is exiting.
2016 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002017static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002018static void sigexit(int sig)
2019{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002020 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00002021 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002022 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
2023 /* Disable all signals: job control, SIGPIPE, etc.
2024 * Mostly paranoid measure, to prevent infinite SIGTTOU.
2025 */
2026 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04002027 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002028 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002029
2030 /* Not a signal, just exit */
2031 if (sig <= 0)
2032 _exit(- sig);
2033
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00002034 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002035}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002036#else
2037
Denys Vlasenko8391c482010-05-22 17:50:43 +02002038# define disable_restore_tty_pgrp_on_exit() ((void)0)
2039# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002040
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002041#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002042
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002043static sighandler_t pick_sighandler(unsigned sig)
2044{
2045 sighandler_t handler = SIG_DFL;
2046 if (sig < sizeof(unsigned)*8) {
2047 unsigned sigmask = (1 << sig);
2048
2049#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002050 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002051 if (G_fatal_sig_mask & sigmask)
2052 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002053 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002054#endif
2055 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002056 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002057 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002058 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002059 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002060 * in an endless loop when we try to do some
2061 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002062 */
2063 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2064 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002065 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002066 }
2067 return handler;
2068}
2069
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002070/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002071static void hush_exit(int exitcode)
2072{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002073#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
Denys Vlasenko00eb23b2020-12-21 21:36:58 +01002074 save_history(G.line_input_state); /* may be NULL */
Denys Vlasenkobede2152011-09-04 16:12:33 +02002075#endif
2076
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002077 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002078 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002079 char *argv[3];
2080 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002081 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002082 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002083 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002084 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002085 * "trap" will still show it, if executed
2086 * in the handler */
2087 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002088 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002089
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002090#if ENABLE_FEATURE_CLEAN_UP
2091 {
2092 struct variable *cur_var;
2093 if (G.cwd != bb_msg_unknown)
2094 free((char*)G.cwd);
2095 cur_var = G.top_var;
2096 while (cur_var) {
2097 struct variable *tmp = cur_var;
2098 if (!cur_var->max_len)
2099 free(cur_var->varstr);
2100 cur_var = cur_var->next;
2101 free(tmp);
2102 }
2103 }
2104#endif
2105
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002106 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002107#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002108 sigexit(- (exitcode & 0xff));
2109#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002110 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002111#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002112}
2113
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002114//TODO: return a mask of ALL handled sigs?
2115static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002116{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002117 int last_sig = 0;
2118
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002119 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002120 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002121
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002122 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002123 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002124 sig = 0;
2125 do {
2126 sig++;
2127 if (sigismember(&G.pending_set, sig)) {
2128 sigdelset(&G.pending_set, sig);
2129 goto got_sig;
2130 }
2131 } while (sig < NSIG);
2132 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002133 got_sig:
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002134#if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002135 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002136 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002137 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002138 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002139 smalluint save_rcode;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002140 int save_pre;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002141 char *argv[3];
2142 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002143 argv[1] = xstrdup(G_traps[sig]);
2144 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002145 argv[2] = NULL;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002146 save_pre = G.pre_trap_exitcode;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01002147 G.pre_trap_exitcode = save_rcode = G.last_exitcode;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002148 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002149 free(argv[1]);
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002150 G.pre_trap_exitcode = save_pre;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002151 G.last_exitcode = save_rcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002152# if ENABLE_HUSH_FUNCTIONS
2153 if (G.return_exitcode >= 0) {
2154 debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
2155 G.last_exitcode = G.return_exitcode;
2156 }
2157# endif
Denys Vlasenkob8709032011-05-08 21:20:01 +02002158 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002159 } /* else: "" trap, ignoring signal */
2160 continue;
2161 }
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002162#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002163 /* not a trap: special action */
2164 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002165 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002166 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002167 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002168 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002169 break;
2170#if ENABLE_HUSH_JOB
2171 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002172//TODO: why are we doing this? ash and dash don't do this,
2173//they have no handler for SIGHUP at all,
2174//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002175 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002176 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002177 /* bash is observed to signal whole process groups,
2178 * not individual processes */
2179 for (job = G.job_list; job; job = job->next) {
2180 if (job->pgrp <= 0)
2181 continue;
2182 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2183 if (kill(- job->pgrp, SIGHUP) == 0)
2184 kill(- job->pgrp, SIGCONT);
2185 }
2186 sigexit(SIGHUP);
2187 }
2188#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002189#if ENABLE_HUSH_FAST
2190 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002191 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002192 G.count_SIGCHLD++;
2193//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2194 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002195 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002196 * This simplifies wait builtin a bit.
2197 */
2198 break;
2199#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002200 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002201 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002202 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002203 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002204 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002205 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002206 * in interactive shell, because TERM is ignored.
2207 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002208 break;
2209 }
2210 }
2211 return last_sig;
2212}
2213
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002214
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002215static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002216{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002217 if (force || G.cwd == NULL) {
2218 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2219 * we must not try to free(bb_msg_unknown) */
2220 if (G.cwd == bb_msg_unknown)
2221 G.cwd = NULL;
2222 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2223 if (!G.cwd)
2224 G.cwd = bb_msg_unknown;
2225 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002226 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002227}
2228
Denis Vlasenko83506862007-11-23 13:11:42 +00002229
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002230/*
2231 * Shell and environment variable support
2232 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002233static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002234{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002235 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002236 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002237
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002238 pp = &G.top_var;
2239 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002240 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002241 return pp;
2242 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002243 }
2244 return NULL;
2245}
2246
Denys Vlasenko03dad222010-01-12 23:29:57 +01002247static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002248{
Denys Vlasenko29082232010-07-16 13:52:32 +02002249 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002250 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002251
2252 if (G.expanded_assignments) {
2253 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002254 while (*cpp) {
2255 char *cp = *cpp;
2256 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2257 return cp + len + 1;
2258 cpp++;
2259 }
2260 }
2261
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002262 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002263 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002264 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002265
Denys Vlasenkodea47882009-10-09 15:40:49 +02002266 if (strcmp(name, "PPID") == 0)
2267 return utoa(G.root_ppid);
2268 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002269#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002270 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002271 return utoa(next_random(&G.random_gen));
2272#endif
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002273#if ENABLE_HUSH_LINENO_VAR
2274 if (strcmp(name, "LINENO") == 0)
2275 return utoa(G.execute_lineno);
2276#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002277#if BASH_EPOCH_VARS
2278 {
2279 const char *fmt = NULL;
2280 if (strcmp(name, "EPOCHSECONDS") == 0)
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002281 fmt = "%llu";
Ron Yorstona81700b2019-04-15 10:48:29 +01002282 else if (strcmp(name, "EPOCHREALTIME") == 0)
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002283 fmt = "%llu.%06u";
Ron Yorstona81700b2019-04-15 10:48:29 +01002284 if (fmt) {
2285 struct timeval tv;
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002286 xgettimeofday(&tv);
2287 sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
Ron Yorstona81700b2019-04-15 10:48:29 +01002288 (unsigned)tv.tv_usec);
2289 return G.epoch_buf;
2290 }
2291 }
2292#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002293 return NULL;
2294}
2295
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002296#if ENABLE_HUSH_GETOPTS
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002297static void handle_changed_special_names(const char *name, unsigned name_len)
2298{
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002299 if (name_len == 6) {
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002300 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002301 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002302 return;
2303 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002304 }
2305}
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002306#else
2307/* Do not even bother evaluating arguments */
2308# define handle_changed_special_names(...) ((void)0)
2309#endif
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002310
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002311/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002312 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002313 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002314#define SETFLAG_EXPORT (1 << 0)
2315#define SETFLAG_UNEXPORT (1 << 1)
2316#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002317#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002318static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002319{
Denys Vlasenko61407802018-04-04 21:14:28 +02002320 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002321 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002322 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002323 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002324 int name_len;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002325 int retval;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002326 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002327
Denis Vlasenko950bd722009-04-21 11:23:56 +00002328 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002329 if (HUSH_DEBUG && !eq_sign)
James Byrne69374872019-07-02 11:35:03 +02002330 bb_simple_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002331
Denis Vlasenko950bd722009-04-21 11:23:56 +00002332 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002333 cur_pp = &G.top_var;
2334 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002335 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002336 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002337 continue;
2338 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002339
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002340 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002341 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002342 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002343 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002344//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2345//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002346 return -1;
2347 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002348 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002349 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2350 *eq_sign = '\0';
2351 unsetenv(str);
2352 *eq_sign = '=';
2353 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002354 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002355 /* bash 3.2.33(1) and exported vars:
2356 * # export z=z
2357 * # f() { local z=a; env | grep ^z; }
2358 * # f
2359 * z=a
2360 * # env | grep ^z
2361 * z=z
2362 */
2363 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002364 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002365 /* New variable is local ("local VAR=VAL" or
2366 * "VAR=VAL cmd")
2367 * and existing one is global, or local
2368 * on a lower level that new one.
2369 * Remove it from global variable list:
2370 */
2371 *cur_pp = cur->next;
2372 if (G.shadowed_vars_pp) {
2373 /* Save in "shadowed" list */
2374 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2375 cur->flg_export ? "exported " : "",
2376 cur->varstr, cur->var_nest_level, str, local_lvl
2377 );
2378 cur->next = *G.shadowed_vars_pp;
2379 *G.shadowed_vars_pp = cur;
2380 } else {
2381 /* Came from pseudo_exec_argv(), no need to save: delete it */
2382 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2383 cur->flg_export ? "exported " : "",
2384 cur->varstr, cur->var_nest_level, str, local_lvl
2385 );
2386 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2387 free_me = cur->varstr; /* then free it later */
2388 free(cur);
2389 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002390 break;
2391 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002392
Denis Vlasenko950bd722009-04-21 11:23:56 +00002393 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002394 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002395 free_and_exp:
2396 free(str);
2397 goto exp;
2398 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002399
2400 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002401 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002402 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002403 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002404 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002405 strcpy(cur->varstr, str);
2406 goto free_and_exp;
2407 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002408 /* Can't reuse */
2409 cur->max_len = 0;
2410 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002411 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002412 /* max_len == 0 signifies "malloced" var, which we can
2413 * (and have to) free. But we can't free(cur->varstr) here:
2414 * if cur->flg_export is 1, it is in the environment.
2415 * We should either unsetenv+free, or wait until putenv,
2416 * then putenv(new)+free(old).
2417 */
2418 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002419 goto set_str_and_exp;
2420 }
2421
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002422 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002423 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002424 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002425 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002426 cur->next = *cur_pp;
2427 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002428
2429 set_str_and_exp:
2430 cur->varstr = str;
2431 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002432#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002433 if (flags & SETFLAG_MAKE_RO) {
2434 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002435 }
2436#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002437 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002438 cur->flg_export = 1;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002439 retval = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002440 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002441 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002442 cur->flg_export = 0;
2443 /* unsetenv was already done */
2444 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002445 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002446 retval = putenv(cur->varstr);
2447 /* fall through to "free(free_me)" -
2448 * only now we can free old exported malloced string
2449 */
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002450 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002451 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002452 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002453
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002454 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002455
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002456 return retval;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002457}
2458
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002459static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2460{
2461 char *var = xasprintf("%s=%s", name, val);
2462 set_local_var(var, /*flag:*/ 0);
2463}
2464
Denys Vlasenko6db47842009-09-05 20:15:17 +02002465/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002466static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002467{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002468 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002469}
2470
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002471#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002472static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002473{
2474 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002475 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002476
Denys Vlasenko61407802018-04-04 21:14:28 +02002477 cur_pp = &G.top_var;
2478 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002479 if (strncmp(cur->varstr, name, name_len) == 0
2480 && cur->varstr[name_len] == '='
2481 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002482 if (cur->flg_read_only) {
2483 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002484 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002485 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002486
Denys Vlasenko61407802018-04-04 21:14:28 +02002487 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002488 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2489 bb_unsetenv(cur->varstr);
2490 if (!cur->max_len)
2491 free(cur->varstr);
2492 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002493
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002494 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002495 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002496 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002497 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002498
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002499 /* Handle "unset LINENO" et al even if did not find the variable to unset */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002500 handle_changed_special_names(name, name_len);
2501
Mike Frysingerd690f682009-03-30 06:50:54 +00002502 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002503}
2504
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002505static int unset_local_var(const char *name)
2506{
2507 return unset_local_var_len(name, strlen(name));
2508}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002509#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002510
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002511
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002512/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002513 * Helpers for "var1=val1 var2=val2 cmd" feature
2514 */
2515static void add_vars(struct variable *var)
2516{
2517 struct variable *next;
2518
2519 while (var) {
2520 next = var->next;
2521 var->next = G.top_var;
2522 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002523 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002524 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002525 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002526 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002527 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002528 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002529 var = next;
2530 }
2531}
2532
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002533/* We put strings[i] into variable table and possibly putenv them.
2534 * If variable is read only, we can free the strings[i]
2535 * which attempts to overwrite it.
2536 * The strings[] vector itself is freed.
2537 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002538static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002539{
2540 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002541
2542 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002543 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002544
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002545 s = strings;
2546 while (*s) {
2547 struct variable *var_p;
2548 struct variable **var_pp;
2549 char *eq;
2550
2551 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002552 if (HUSH_DEBUG && !eq)
James Byrne69374872019-07-02 11:35:03 +02002553 bb_simple_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002554 var_pp = get_ptr_to_local_var(*s, eq - *s);
2555 if (var_pp) {
2556 var_p = *var_pp;
2557 if (var_p->flg_read_only) {
2558 char **p;
2559 bb_error_msg("%s: readonly variable", *s);
2560 /*
2561 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2562 * If VAR is readonly, leaving it in the list
2563 * after asssignment error (msg above)
2564 * causes doubled error message later, on unset.
2565 */
2566 debug_printf_env("removing/freeing '%s' element\n", *s);
2567 free(*s);
2568 p = s;
2569 do { *p = p[1]; p++; } while (*p);
2570 goto next;
2571 }
2572 /* below, set_local_var() with nest level will
2573 * "shadow" (remove) this variable from
2574 * global linked list.
2575 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002576 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002577 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2578 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002579 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002580 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002581 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002582 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002583}
2584
2585
2586/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002587 * Unicode helper
2588 */
2589static void reinit_unicode_for_hush(void)
2590{
2591 /* Unicode support should be activated even if LANG is set
2592 * _during_ shell execution, not only if it was set when
2593 * shell was started. Therefore, re-check LANG every time:
2594 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002595 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2596 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002597 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002598 const char *s = get_local_var_value("LC_ALL");
2599 if (!s) s = get_local_var_value("LC_CTYPE");
2600 if (!s) s = get_local_var_value("LANG");
2601 reinit_unicode(s);
2602 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002603}
2604
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002605/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002606 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002607 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002608
2609#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002610/* To test correct lineedit/interactive behavior, type from command line:
2611 * echo $P\
2612 * \
2613 * AT\
2614 * H\
2615 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002616 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002617 */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002618static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002619{
2620 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002621
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002622 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002623
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002624# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2625 prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
2626 if (!prompt_str)
2627 prompt_str = "";
2628# else
2629 prompt_str = "> "; /* if PS2, else... */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002630 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002631 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2632 free(G.PS1);
2633 /* bash uses $PWD value, even if it is set by user.
2634 * It uses current dir only if PWD is unset.
2635 * We always use current dir. */
Denys Vlasenko649acb92020-12-23 15:29:13 +01002636 prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002637 }
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002638# endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002639 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002640 return prompt_str;
2641}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002642static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002643{
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002644# if ENABLE_FEATURE_EDITING
2645 /* In EDITING case, this function reads next input line,
2646 * saves it in i->p, then returns 1st char of it.
2647 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002648 int r;
2649 const char *prompt_str;
2650
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002651 prompt_str = setup_prompt_string();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002652 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002653 reinit_unicode_for_hush();
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002654 G.flag_SIGINT = 0;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002655 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002656 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002657 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002658 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002659 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002660 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002661 if (r == 0) {
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002662 raise(SIGINT);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002663 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002664 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002665 if (r != 0 && !G.flag_SIGINT)
2666 break;
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01002667 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002668 /* bash prints ^C even on real SIGINT (non-kbd generated) */
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002669 write(STDOUT_FILENO, "^C\n", 3);
Denys Vlasenko93e2a222020-12-23 12:23:21 +01002670 G.last_exitcode = 128 | SIGINT;
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002671 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002672 if (r < 0) {
2673 /* EOF/error detected */
Denys Vlasenkof0c0c562021-04-13 16:42:17 +02002674 /* ^D on interactive input goes to next line before exiting: */
2675 write(STDOUT_FILENO, "\n", 1);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002676 i->p = NULL;
2677 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002678 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002679 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002680 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002681 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002682# else
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002683 /* In !EDITING case, this function gets called for every char.
2684 * Buffering happens deeper in the call chain, in hfgetc(i->file).
2685 */
2686 int r;
2687
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002688 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002689 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002690 if (i->last_char == '\0' || i->last_char == '\n') {
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002691 const char *prompt_str = setup_prompt_string();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002692 /* Why check_and_run_traps here? Try this interactively:
2693 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2694 * $ <[enter], repeatedly...>
2695 * Without check_and_run_traps, handler never runs.
2696 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002697 check_and_run_traps();
Ron Yorstoncad3fc72021-02-03 20:47:14 +01002698 fputs_stdout(prompt_str);
Denys Vlasenko521220e2020-12-23 23:44:55 +01002699 fflush_all();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002700 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002701 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002702 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2703 * no ^C masking happens during fgetc, no special code for ^C:
2704 * it generates SIGINT as usual.
2705 */
2706 check_and_run_traps();
Denys Vlasenko521220e2020-12-23 23:44:55 +01002707 if (r != '\0' && !G.flag_SIGINT)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002708 break;
Denys Vlasenko521220e2020-12-23 23:44:55 +01002709 if (G.flag_SIGINT) {
2710 /* ^C or SIGINT: repeat */
2711 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2712 /* kernel prints "^C" itself, just print newline: */
2713 write(STDOUT_FILENO, "\n", 1);
2714 G.last_exitcode = 128 | SIGINT;
2715 }
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002716 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002717 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002718# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002719}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002720/* This is the magic location that prints prompts
2721 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002722static int fgetc_interactive(struct in_str *i)
2723{
2724 int ch;
2725 /* If it's interactive stdin, get new line. */
Denys Vlasenko21806562019-11-01 14:16:07 +01002726 if (G_interactive_fd && i->file == G.HFILE_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002727 /* Returns first char (or EOF), the rest is in i->p[] */
2728 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002729 G.promptmode = 1; /* PS2 */
2730 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002731 } else {
2732 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002733 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002734 }
2735 return ch;
2736}
Denys Vlasenko649acb92020-12-23 15:29:13 +01002737#else /* !INTERACTIVE */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002738static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002739{
2740 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002741 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002742 return ch;
2743}
Denys Vlasenko649acb92020-12-23 15:29:13 +01002744#endif /* !INTERACTIVE */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002745
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002746static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002747{
2748 int ch;
2749
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002750 if (!i->file) {
2751 /* string-based in_str */
2752 ch = (unsigned char)*i->p;
2753 if (ch != '\0') {
2754 i->p++;
2755 i->last_char = ch;
Denys Vlasenko574b9c42021-09-07 21:44:44 +02002756#if ENABLE_HUSH_LINENO_VAR
2757 if (ch == '\n') {
2758 G.parse_lineno++;
2759 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
2760 }
2761#endif
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002762 return ch;
2763 }
2764 return EOF;
2765 }
2766
2767 /* FILE-based in_str */
2768
Denys Vlasenko4074d492016-09-30 01:49:53 +02002769#if ENABLE_FEATURE_EDITING
2770 /* This can be stdin, check line editing char[] buffer */
2771 if (i->p && *i->p != '\0') {
2772 ch = (unsigned char)*i->p++;
2773 goto out;
2774 }
2775#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002776 /* peek_buf[] is an int array, not char. Can contain EOF. */
2777 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002778 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002779 int ch2 = i->peek_buf[1];
2780 i->peek_buf[0] = ch2;
2781 if (ch2 == 0) /* very likely, avoid redundant write */
2782 goto out;
2783 i->peek_buf[1] = 0;
2784 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002785 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002786
Denys Vlasenko4074d492016-09-30 01:49:53 +02002787 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002788 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002789 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002790 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002791#if ENABLE_HUSH_LINENO_VAR
2792 if (ch == '\n') {
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002793 G.parse_lineno++;
2794 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
Denys Vlasenko5807e182018-02-08 19:19:04 +01002795 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002796#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002797 return ch;
2798}
2799
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002800static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002801{
2802 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002803
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002804 if (!i->file) {
2805 /* string-based in_str */
2806 /* Doesn't report EOF on NUL. None of the callers care. */
2807 return (unsigned char)*i->p;
2808 }
2809
2810 /* FILE-based in_str */
2811
Denys Vlasenko4074d492016-09-30 01:49:53 +02002812#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002813 /* This can be stdin, check line editing char[] buffer */
2814 if (i->p && *i->p != '\0')
2815 return (unsigned char)*i->p;
2816#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002817 /* peek_buf[] is an int array, not char. Can contain EOF. */
2818 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002819 if (ch != 0)
2820 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002821
Denys Vlasenko4074d492016-09-30 01:49:53 +02002822 /* Need to get a new char */
2823 ch = fgetc_interactive(i);
2824 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2825
2826 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2827#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2828 if (i->p) {
2829 i->p -= 1;
2830 return ch;
2831 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002832#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002833 i->peek_buf[0] = ch;
2834 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002835 return ch;
2836}
2837
Denys Vlasenko4074d492016-09-30 01:49:53 +02002838/* Only ever called if i_peek() was called, and did not return EOF.
2839 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2840 * not end-of-line. Therefore we never need to read a new editing line here.
2841 */
2842static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002843{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002844 int ch;
2845
2846 /* There are two cases when i->p[] buffer exists.
2847 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002848 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002849 * In both cases, we know that i->p[0] exists and not NUL, and
2850 * the peek2 result is in i->p[1].
2851 */
2852 if (i->p)
2853 return (unsigned char)i->p[1];
2854
2855 /* Now we know it is a file-based in_str. */
2856
2857 /* peek_buf[] is an int array, not char. Can contain EOF. */
2858 /* Is there 2nd char? */
2859 ch = i->peek_buf[1];
2860 if (ch == 0) {
2861 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002862 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002863 i->peek_buf[1] = ch;
2864 }
2865
2866 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2867 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002868}
2869
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002870static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2871{
2872 for (;;) {
2873 int ch, ch2;
2874
2875 ch = i_getch(input);
2876 if (ch != '\\')
2877 return ch;
2878 ch2 = i_peek(input);
2879 if (ch2 != '\n')
2880 return ch;
2881 /* backslash+newline, skip it */
2882 i_getch(input);
2883 }
2884}
2885
2886/* Note: this function _eats_ \<newline> pairs, safe to use plain
2887 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2888 */
2889static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2890{
2891 for (;;) {
2892 int ch, ch2;
2893
2894 ch = i_peek(input);
2895 if (ch != '\\')
2896 return ch;
2897 ch2 = i_peek2(input);
2898 if (ch2 != '\n')
2899 return ch;
2900 /* backslash+newline, skip it */
2901 i_getch(input);
2902 i_getch(input);
2903 }
2904}
2905
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002906static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002907{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002908 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002909 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002910 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002911}
2912
2913static void setup_string_in_str(struct in_str *i, const char *s)
2914{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002915 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002916 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002917 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002918}
2919
2920
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002921/*
2922 * o_string support
2923 */
2924#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002925
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002926static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002927{
2928 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002929 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002930 if (o->data)
2931 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002932}
2933
Denys Vlasenko18567402018-07-20 17:51:31 +02002934static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002935{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002936 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002937 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002938}
2939
Denys Vlasenko18567402018-07-20 17:51:31 +02002940static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002941{
2942 free(o->data);
2943}
2944
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002945static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002946{
2947 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002948 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002949 o->data = xrealloc(o->data, 1 + o->maxlen);
2950 }
2951}
2952
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002953static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002954{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002955 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002956 if (o->length < o->maxlen) {
2957 /* likely. avoid o_grow_by() call */
2958 add:
2959 o->data[o->length] = ch;
2960 o->length++;
2961 o->data[o->length] = '\0';
2962 return;
2963 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002964 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002965 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002966}
2967
Denys Vlasenko657086a2016-09-29 18:07:42 +02002968#if 0
2969/* Valid only if we know o_string is not empty */
2970static void o_delchr(o_string *o)
2971{
2972 o->length--;
2973 o->data[o->length] = '\0';
2974}
2975#endif
2976
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002977static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002978{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002979 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002980 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002981 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002982}
2983
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002984static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002985{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002986 o_addblock(o, str, strlen(str));
2987}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002988
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002989static void o_addstr_with_NUL(o_string *o, const char *str)
2990{
2991 o_addblock(o, str, strlen(str) + 1);
2992}
2993
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002994#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002995static void nommu_addchr(o_string *o, int ch)
2996{
2997 if (o)
2998 o_addchr(o, ch);
2999}
3000#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003001# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003002#endif
3003
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003004#if ENABLE_HUSH_MODE_X
3005static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003006{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003007 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00003008}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003009static void x_mode_addstr(const char *str)
3010{
3011 o_addstr(&G.x_mode_buf, str);
3012}
3013static void x_mode_addblock(const char *str, int len)
3014{
3015 o_addblock(&G.x_mode_buf, str, len);
3016}
3017static void x_mode_prefix(void)
3018{
3019 int n = G.x_mode_depth;
3020 do x_mode_addchr('+'); while (--n >= 0);
3021}
3022static void x_mode_flush(void)
3023{
3024 int len = G.x_mode_buf.length;
3025 if (len <= 0)
3026 return;
3027 if (G.x_mode_fd > 0) {
3028 G.x_mode_buf.data[len] = '\n';
3029 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
3030 }
3031 G.x_mode_buf.length = 0;
3032}
3033#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00003034
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003035/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02003036 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003037 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
3038 * Apparently, on unquoted $v bash still does globbing
3039 * ("v='*.txt'; echo $v" prints all .txt files),
3040 * but NOT brace expansion! Thus, there should be TWO independent
3041 * quoting mechanisms on $v expansion side: one protects
3042 * $v from brace expansion, and other additionally protects "$v" against globbing.
3043 * We have only second one.
3044 */
3045
Denys Vlasenko9e800222010-10-03 14:28:04 +02003046#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003047# define MAYBE_BRACES "{}"
3048#else
3049# define MAYBE_BRACES ""
3050#endif
3051
Eric Andersen25f27032001-04-26 23:22:31 +00003052/* My analysis of quoting semantics tells me that state information
3053 * is associated with a destination, not a source.
3054 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003055static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00003056{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003057 int sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003058 /* '-' is included because of this case:
3059 * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
3060 */
3061 char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003062 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003063 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003064 o_grow_by(o, sz);
3065 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003066 o->data[o->length] = '\\';
3067 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003068 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003069 o->data[o->length] = ch;
3070 o->length++;
3071 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003072}
3073
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003074static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003075{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003076 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003077 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003078 && strchr("*?[-\\" MAYBE_BRACES, ch)
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003079 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003080 sz++;
3081 o->data[o->length] = '\\';
3082 o->length++;
3083 }
3084 o_grow_by(o, sz);
3085 o->data[o->length] = ch;
3086 o->length++;
3087 o->data[o->length] = '\0';
3088}
3089
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003090static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003091{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003092 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003093 char ch;
3094 int sz;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003095 int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003096 if (ordinary_cnt > len) /* paranoia */
3097 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003098 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003099 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003100 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003101 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003102 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003103
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003104 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003105 sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003106 if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003107 sz++;
3108 o->data[o->length] = '\\';
3109 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003110 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003111 o_grow_by(o, sz);
3112 o->data[o->length] = ch;
3113 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003114 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003115 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003116}
3117
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003118static void o_addQblock(o_string *o, const char *str, int len)
3119{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003120 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003121 o_addblock(o, str, len);
3122 return;
3123 }
3124 o_addqblock(o, str, len);
3125}
3126
Denys Vlasenko38292b62010-09-05 14:49:40 +02003127static void o_addQstr(o_string *o, const char *str)
3128{
3129 o_addQblock(o, str, strlen(str));
3130}
3131
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003132/* A special kind of o_string for $VAR and `cmd` expansion.
3133 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003134 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003135 * list[i] contains an INDEX (int!) into this string data.
3136 * It means that if list[] needs to grow, data needs to be moved higher up
3137 * but list[i]'s need not be modified.
3138 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003139 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003140 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3141 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003142#if DEBUG_EXPAND || DEBUG_GLOB
3143static void debug_print_list(const char *prefix, o_string *o, int n)
3144{
3145 char **list = (char**)o->data;
3146 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3147 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003148
3149 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003150 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 +02003151 prefix, list, n, string_start, o->length, o->maxlen,
3152 !!(o->o_expflags & EXP_FLAG_GLOB),
3153 o->has_quoted_part,
3154 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003155 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003156 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003157 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3158 o->data + (int)(uintptr_t)list[i] + string_start,
3159 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003160 i++;
3161 }
3162 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003163 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003164 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003165 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003166 }
3167}
3168#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003169# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003170#endif
3171
3172/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3173 * in list[n] so that it points past last stored byte so far.
3174 * It returns n+1. */
3175static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003176{
3177 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003178 int string_start;
3179 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003180
3181 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003182 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3183 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003184 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003185 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003186 /* list[n] points to string_start, make space for 16 more pointers */
3187 o->maxlen += 0x10 * sizeof(list[0]);
3188 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003189 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003190 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003191 /*
3192 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3193 * check. (grep for -prev-ifs-check-).
3194 * Ensure that argv[-1][last] is not garbage
3195 * but zero bytes, to save index check there.
3196 */
3197 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003198 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003199 } else {
3200 debug_printf_list("list[%d]=%d string_start=%d\n",
3201 n, string_len, string_start);
3202 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003203 } else {
3204 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003205 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3206 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003207 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3208 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003209 o->has_empty_slot = 0;
3210 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003211 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003212 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003213 return n + 1;
3214}
3215
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003216/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003217static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003218{
3219 char **list = (char**)o->data;
3220 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3221
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003222 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003223}
3224
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003225/*
3226 * Globbing routines.
3227 *
3228 * Most words in commands need to be globbed, even ones which are
3229 * (single or double) quoted. This stems from the possiblity of
3230 * constructs like "abc"* and 'abc'* - these should be globbed.
3231 * Having a different code path for fully-quoted strings ("abc",
3232 * 'abc') would only help performance-wise, but we still need
3233 * code for partially-quoted strings.
3234 *
3235 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003236 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003237 * to a string, then globbed, and if globbing does not match anything,
3238 * it is used verbatim". Here are two examples where it fails:
3239 *
3240 * echo 'b\*'?
3241 *
3242 * The globbing can't be avoided (because of '?' at the end).
3243 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3244 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003245 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003246 * Now, look at this:
3247 *
3248 * v='\\\*'; echo b$v?
3249 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003250 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003251 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003252 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003253 *
3254 * ash implements this by having an encoded representation of the word
3255 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3256 * Glob pattern is derived from it. If glob fails, the decision what result
3257 * should be is made using that encoded representation. Not glob pattern.
3258 */
3259
Denys Vlasenko9e800222010-10-03 14:28:04 +02003260#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003261/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3262 * first, it processes even {a} (no commas), second,
3263 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003264 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003265 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003266
3267/* Helper */
3268static int glob_needed(const char *s)
3269{
3270 while (*s) {
3271 if (*s == '\\') {
3272 if (!s[1])
3273 return 0;
3274 s += 2;
3275 continue;
3276 }
3277 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3278 return 1;
3279 s++;
3280 }
3281 return 0;
3282}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003283/* Return pointer to next closing brace or to comma */
3284static const char *next_brace_sub(const char *cp)
3285{
3286 unsigned depth = 0;
3287 cp++;
3288 while (*cp != '\0') {
3289 if (*cp == '\\') {
3290 if (*++cp == '\0')
3291 break;
3292 cp++;
3293 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003294 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003295 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003296 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003297 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003298 depth++;
3299 }
3300
3301 return *cp != '\0' ? cp : NULL;
3302}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003303/* Recursive brace globber. Note: may garble pattern[]. */
3304static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003305{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003306 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003307 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003308 const char *next;
3309 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003310 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003311 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003312
3313 debug_printf_glob("glob_brace('%s')\n", pattern);
3314
3315 begin = pattern;
3316 while (1) {
3317 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003318 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003319 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003320 /* Find the first sub-pattern and at the same time
3321 * find the rest after the closing brace */
3322 next = next_brace_sub(begin);
3323 if (next == NULL) {
3324 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003325 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003326 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003327 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003328 /* "{abc}" with no commas - illegal
3329 * brace expr, disregard and skip it */
3330 begin = next + 1;
3331 continue;
3332 }
3333 break;
3334 }
3335 if (*begin == '\\' && begin[1] != '\0')
3336 begin++;
3337 begin++;
3338 }
3339 debug_printf_glob("begin:%s\n", begin);
3340 debug_printf_glob("next:%s\n", next);
3341
3342 /* Now find the end of the whole brace expression */
3343 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003344 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003345 rest = next_brace_sub(rest);
3346 if (rest == NULL) {
3347 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003348 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003349 }
3350 debug_printf_glob("rest:%s\n", rest);
3351 }
3352 rest_len = strlen(++rest) + 1;
3353
3354 /* We are sure the brace expression is well-formed */
3355
3356 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003357 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003358
3359 /* We have a brace expression. BEGIN points to the opening {,
3360 * NEXT points past the terminator of the first element, and REST
3361 * points past the final }. We will accumulate result names from
3362 * recursive runs for each brace alternative in the buffer using
3363 * GLOB_APPEND. */
3364
3365 p = begin + 1;
3366 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003367 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003368 memcpy(
3369 mempcpy(
3370 mempcpy(new_pattern_buf,
3371 /* We know the prefix for all sub-patterns */
3372 pattern, begin - pattern),
3373 p, next - p),
3374 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003375
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003376 /* Note: glob_brace() may garble new_pattern_buf[].
3377 * That's why we re-copy prefix every time (1st memcpy above).
3378 */
3379 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003380 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003381 /* We saw the last entry */
3382 break;
3383 }
3384 p = next + 1;
3385 next = next_brace_sub(next);
3386 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003387 free(new_pattern_buf);
3388 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003389
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003390 simple_glob:
3391 {
3392 int gr;
3393 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003394
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003395 memset(&globdata, 0, sizeof(globdata));
3396 gr = glob(pattern, 0, NULL, &globdata);
3397 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3398 if (gr != 0) {
3399 if (gr == GLOB_NOMATCH) {
3400 globfree(&globdata);
3401 /* NB: garbles parameter */
3402 unbackslash(pattern);
3403 o_addstr_with_NUL(o, pattern);
3404 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3405 return o_save_ptr_helper(o, n);
3406 }
3407 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003408 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003409 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3410 * but we didn't specify it. Paranoia again. */
3411 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3412 }
3413 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3414 char **argv = globdata.gl_pathv;
3415 while (1) {
3416 o_addstr_with_NUL(o, *argv);
3417 n = o_save_ptr_helper(o, n);
3418 argv++;
3419 if (!*argv)
3420 break;
3421 }
3422 }
3423 globfree(&globdata);
3424 }
3425 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003426}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003427/* Performs globbing on last list[],
3428 * saving each result as a new list[].
3429 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003430static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003431{
3432 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003433
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003434 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003435 if (!o->data)
3436 return o_save_ptr_helper(o, n);
3437 pattern = o->data + o_get_last_ptr(o, n);
3438 debug_printf_glob("glob pattern '%s'\n", pattern);
3439 if (!glob_needed(pattern)) {
3440 /* unbackslash last string in o in place, fix length */
3441 o->length = unbackslash(pattern) - o->data;
3442 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3443 return o_save_ptr_helper(o, n);
3444 }
3445
3446 copy = xstrdup(pattern);
3447 /* "forget" pattern in o */
3448 o->length = pattern - o->data;
3449 n = glob_brace(copy, o, n);
3450 free(copy);
3451 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003452 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003453 return n;
3454}
3455
Denys Vlasenko238081f2010-10-03 14:26:26 +02003456#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003457
3458/* Helper */
3459static int glob_needed(const char *s)
3460{
3461 while (*s) {
3462 if (*s == '\\') {
3463 if (!s[1])
3464 return 0;
3465 s += 2;
3466 continue;
3467 }
3468 if (*s == '*' || *s == '[' || *s == '?')
3469 return 1;
3470 s++;
3471 }
3472 return 0;
3473}
3474/* Performs globbing on last list[],
3475 * saving each result as a new list[].
3476 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003477static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003478{
3479 glob_t globdata;
3480 int gr;
3481 char *pattern;
3482
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003483 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003484 if (!o->data)
3485 return o_save_ptr_helper(o, n);
3486 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003487 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003488 if (!glob_needed(pattern)) {
3489 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003490 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003491 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003492 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003493 return o_save_ptr_helper(o, n);
3494 }
3495
3496 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003497 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3498 * If we glob "*.\*" and don't find anything, we need
3499 * to fall back to using literal "*.*", but GLOB_NOCHECK
3500 * will return "*.\*"!
3501 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003502 gr = glob(pattern, 0, NULL, &globdata);
3503 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003504 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003505 if (gr == GLOB_NOMATCH) {
3506 globfree(&globdata);
3507 goto literal;
3508 }
3509 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003510 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003511 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3512 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003513 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003514 }
3515 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3516 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003517 /* "forget" pattern in o */
3518 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003519 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003520 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003521 n = o_save_ptr_helper(o, n);
3522 argv++;
3523 if (!*argv)
3524 break;
3525 }
3526 }
3527 globfree(&globdata);
3528 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003529 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003530 return n;
3531}
3532
Denys Vlasenko238081f2010-10-03 14:26:26 +02003533#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003534
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003535/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003536 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003537static int o_save_ptr(o_string *o, int n)
3538{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003539 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003540 /* If o->has_empty_slot, list[n] was already globbed
3541 * (if it was requested back then when it was filled)
3542 * so don't do that again! */
3543 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003544 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003545 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003546 return o_save_ptr_helper(o, n);
3547}
3548
3549/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003550static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003551{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003552 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003553 int string_start;
3554
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003555 if (DEBUG_EXPAND)
3556 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003557 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003558 list = (char**)o->data;
3559 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3560 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003561 while (n) {
3562 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003563 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003564 }
3565 return list;
3566}
3567
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003568static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003569
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003570/* Returns pi->next - next pipe in the list */
3571static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003572{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003573 struct pipe *next;
3574 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003575
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003576 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003577 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003578 struct command *command;
3579 struct redir_struct *r, *rnext;
3580
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003581 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003582 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003583 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003584 if (DEBUG_CLEAN) {
3585 int a;
3586 char **p;
3587 for (a = 0, p = command->argv; *p; a++, p++) {
3588 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3589 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003590 }
3591 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003592 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003593 }
3594 /* not "else if": on syntax error, we may have both! */
3595 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003596 debug_printf_clean(" begin group (cmd_type:%d)\n",
3597 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003598 free_pipe_list(command->group);
3599 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003600 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003601 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003602 /* else is crucial here.
3603 * If group != NULL, child_func is meaningless */
3604#if ENABLE_HUSH_FUNCTIONS
3605 else if (command->child_func) {
3606 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3607 command->child_func->parent_cmd = NULL;
3608 }
3609#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003610#if !BB_MMU
3611 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003612 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003613#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003614 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003615 debug_printf_clean(" redirect %d%s",
3616 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003617 /* guard against the case >$FOO, where foo is unset or blank */
3618 if (r->rd_filename) {
3619 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3620 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003621 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003622 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003623 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003624 rnext = r->next;
3625 free(r);
3626 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003627 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003628 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003629 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003630 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003631#if ENABLE_HUSH_JOB
3632 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003633 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003634#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003635
3636 next = pi->next;
3637 free(pi);
3638 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003639}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003640
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003641static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003642{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003643 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003644#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003645 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003646#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003647 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003648 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003649 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003650}
3651
3652
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003653/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003654
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003655#ifndef debug_print_tree
3656static void debug_print_tree(struct pipe *pi, int lvl)
3657{
3658 static const char *const PIPE[] = {
3659 [PIPE_SEQ] = "SEQ",
3660 [PIPE_AND] = "AND",
3661 [PIPE_OR ] = "OR" ,
3662 [PIPE_BG ] = "BG" ,
3663 };
3664 static const char *RES[] = {
3665 [RES_NONE ] = "NONE" ,
3666# if ENABLE_HUSH_IF
3667 [RES_IF ] = "IF" ,
3668 [RES_THEN ] = "THEN" ,
3669 [RES_ELIF ] = "ELIF" ,
3670 [RES_ELSE ] = "ELSE" ,
3671 [RES_FI ] = "FI" ,
3672# endif
3673# if ENABLE_HUSH_LOOPS
3674 [RES_FOR ] = "FOR" ,
3675 [RES_WHILE] = "WHILE",
3676 [RES_UNTIL] = "UNTIL",
3677 [RES_DO ] = "DO" ,
3678 [RES_DONE ] = "DONE" ,
3679# endif
3680# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3681 [RES_IN ] = "IN" ,
3682# endif
3683# if ENABLE_HUSH_CASE
3684 [RES_CASE ] = "CASE" ,
3685 [RES_CASE_IN ] = "CASE_IN" ,
3686 [RES_MATCH] = "MATCH",
3687 [RES_CASE_BODY] = "CASE_BODY",
3688 [RES_ESAC ] = "ESAC" ,
3689# endif
3690 [RES_XXXX ] = "XXXX" ,
3691 [RES_SNTX ] = "SNTX" ,
3692 };
3693 static const char *const CMDTYPE[] = {
3694 "{}",
3695 "()",
3696 "[noglob]",
3697# if ENABLE_HUSH_FUNCTIONS
3698 "func()",
3699# endif
3700 };
3701
3702 int pin, prn;
3703
3704 pin = 0;
3705 while (pi) {
Denys Vlasenko83a49672021-06-15 18:12:13 +02003706 fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
Denys Vlasenko5807e182018-02-08 19:19:04 +01003707 lvl*2, "",
3708 pin,
Denys Vlasenko83a49672021-06-15 18:12:13 +02003709 pi->num_cmds,
Denys Vlasenko5807e182018-02-08 19:19:04 +01003710 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3711 RES[pi->res_word],
3712 pi->followup, PIPE[pi->followup]
3713 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003714 prn = 0;
3715 while (prn < pi->num_cmds) {
3716 struct command *command = &pi->cmds[prn];
3717 char **argv = command->argv;
3718
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003719 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003720 lvl*2, "", prn,
3721 command->assignment_cnt);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003722# if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko5807e182018-02-08 19:19:04 +01003723 fdprintf(2, " LINENO:%u", command->lineno);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003724# endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003725 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003726 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003727 CMDTYPE[command->cmd_type],
3728 argv
3729# if !BB_MMU
3730 , " group_as_string:", command->group_as_string
3731# else
3732 , "", ""
3733# endif
3734 );
3735 debug_print_tree(command->group, lvl+1);
3736 prn++;
3737 continue;
3738 }
3739 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003740 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003741 argv++;
3742 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003743 if (command->redirects)
3744 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003745 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003746 prn++;
3747 }
3748 pi = pi->next;
3749 pin++;
3750 }
3751}
3752#endif /* debug_print_tree */
3753
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003754static struct pipe *new_pipe(void)
3755{
Eric Andersen25f27032001-04-26 23:22:31 +00003756 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003757 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003758 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003759 return pi;
3760}
3761
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003762/* Command (member of a pipe) is complete, or we start a new pipe
3763 * if ctx->command is NULL.
3764 * No errors possible here.
3765 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003766static int done_command(struct parse_context *ctx)
3767{
3768 /* The command is really already in the pipe structure, so
3769 * advance the pipe counter and make a new, null command. */
3770 struct pipe *pi = ctx->pipe;
3771 struct command *command = ctx->command;
3772
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003773#if 0 /* Instead we emit error message at run time */
3774 if (ctx->pending_redirect) {
3775 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003776 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003777 ctx->pending_redirect = NULL;
3778 }
3779#endif
3780
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003781 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003782 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003783 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003784 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003785 }
3786 pi->num_cmds++;
3787 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003788 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003789 } else {
3790 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3791 }
3792
3793 /* Only real trickiness here is that the uncommitted
3794 * command structure is not counted in pi->num_cmds. */
3795 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003796 ctx->command = command = &pi->cmds[pi->num_cmds];
3797 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003798 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003799#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02003800 command->lineno = G.parse_lineno;
3801 debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003802#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003803 return pi->num_cmds; /* used only for 0/nonzero check */
3804}
3805
3806static void done_pipe(struct parse_context *ctx, pipe_style type)
3807{
3808 int not_null;
3809
3810 debug_printf_parse("done_pipe entered, followup %d\n", type);
3811 /* Close previous command */
3812 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003813#if HAS_KEYWORDS
3814 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3815 ctx->ctx_inverted = 0;
3816 ctx->pipe->res_word = ctx->ctx_res_w;
3817#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003818 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3819 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003820 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3821 * in a backgrounded subshell.
3822 */
3823 struct pipe *pi;
3824 struct command *command;
3825
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003826 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003827 pi = ctx->list_head;
3828 while (pi != ctx->pipe) {
3829 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3830 goto no_conv;
3831 pi = pi->next;
3832 }
3833
3834 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3835 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3836 pi = xzalloc(sizeof(*pi));
3837 pi->followup = PIPE_BG;
3838 pi->num_cmds = 1;
3839 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3840 command = &pi->cmds[0];
3841 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3842 command->cmd_type = CMD_NORMAL;
3843 command->group = ctx->list_head;
3844#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003845 command->group_as_string = xstrndup(
3846 ctx->as_string.data,
3847 ctx->as_string.length - 1 /* do not copy last char, "&" */
3848 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003849#endif
3850 /* Replace all pipes in ctx with one newly created */
3851 ctx->list_head = ctx->pipe = pi;
Denys Vlasenko83a49672021-06-15 18:12:13 +02003852 /* for cases like "cmd && &", do not be tricked by last command
3853 * being null - the entire {...} & is NOT null! */
3854 not_null = 1;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003855 } else {
3856 no_conv:
3857 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003858 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003859
3860 /* Without this check, even just <enter> on command line generates
3861 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003862 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003863 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003864#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003865 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003866#endif
3867#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003868 || ctx->ctx_res_w == RES_DONE
3869 || ctx->ctx_res_w == RES_FOR
3870 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003871#endif
3872#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003873 || ctx->ctx_res_w == RES_ESAC
3874#endif
3875 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003876 struct pipe *new_p;
3877 debug_printf_parse("done_pipe: adding new pipe: "
3878 "not_null:%d ctx->ctx_res_w:%d\n",
3879 not_null, ctx->ctx_res_w);
3880 new_p = new_pipe();
3881 ctx->pipe->next = new_p;
3882 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003883 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003884 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003885 * This is used to control execution.
3886 * RES_FOR and RES_IN are NOT sticky (needed to support
3887 * cases where variable or value happens to match a keyword):
3888 */
3889#if ENABLE_HUSH_LOOPS
3890 if (ctx->ctx_res_w == RES_FOR
3891 || ctx->ctx_res_w == RES_IN)
3892 ctx->ctx_res_w = RES_NONE;
3893#endif
3894#if ENABLE_HUSH_CASE
3895 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003896 ctx->ctx_res_w = RES_CASE_BODY;
3897 if (ctx->ctx_res_w == RES_CASE)
3898 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003899#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003900 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003901 /* Create the memory for command, roughly:
3902 * ctx->pipe->cmds = new struct command;
3903 * ctx->command = &ctx->pipe->cmds[0];
3904 */
3905 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003906 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003907 }
3908 debug_printf_parse("done_pipe return\n");
3909}
3910
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003911static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003912{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003913 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003914 if (MAYBE_ASSIGNMENT != 0)
3915 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003916 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003917 /* Create the memory for command, roughly:
3918 * ctx->pipe->cmds = new struct command;
3919 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003920 */
3921 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003922}
3923
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003924/* If a reserved word is found and processed, parse context is modified
3925 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003926 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003927#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003928struct reserved_combo {
3929 char literal[6];
3930 unsigned char res;
3931 unsigned char assignment_flag;
Denys Vlasenko965b7952020-11-30 13:03:03 +01003932 uint32_t flag;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003933};
3934enum {
3935 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003936# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003937 FLAG_IF = (1 << RES_IF ),
3938 FLAG_THEN = (1 << RES_THEN ),
3939 FLAG_ELIF = (1 << RES_ELIF ),
3940 FLAG_ELSE = (1 << RES_ELSE ),
3941 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003942# endif
3943# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003944 FLAG_FOR = (1 << RES_FOR ),
3945 FLAG_WHILE = (1 << RES_WHILE),
3946 FLAG_UNTIL = (1 << RES_UNTIL),
3947 FLAG_DO = (1 << RES_DO ),
3948 FLAG_DONE = (1 << RES_DONE ),
3949 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003950# endif
3951# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003952 FLAG_MATCH = (1 << RES_MATCH),
3953 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003954# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003955 FLAG_START = (1 << RES_XXXX ),
3956};
3957
3958static const struct reserved_combo* match_reserved_word(o_string *word)
3959{
Eric Andersen25f27032001-04-26 23:22:31 +00003960 /* Mostly a list of accepted follow-up reserved words.
3961 * FLAG_END means we are done with the sequence, and are ready
3962 * to turn the compound list into a command.
3963 * FLAG_START means the word must start a new compound list.
3964 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01003965 static const struct reserved_combo reserved_list[] ALIGN4 = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003966# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003967 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3968 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3969 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3970 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3971 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3972 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003973# endif
3974# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003975 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3976 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3977 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3978 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3979 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3980 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003981# endif
3982# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003983 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3984 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003985# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003986 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003987 const struct reserved_combo *r;
3988
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003989 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003990 if (strcmp(word->data, r->literal) == 0)
3991 return r;
3992 }
3993 return NULL;
3994}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003995/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003996 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003997static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003998{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003999# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004000 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004001 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004002 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004003# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004004 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004005
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004006 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004007 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004008 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004009 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01004010 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004011
4012 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004013# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004014 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4015 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004016 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004017 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004018# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004019 if (r->flag == 0) { /* '!' */
4020 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004021 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004022 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004023 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004024 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01004025 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004026 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004027 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004028 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004029
Denys Vlasenko9e55a152017-07-10 10:01:12 +02004030 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004031 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004032 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004033 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004034 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004035 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004036 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01004037 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004038 } else {
4039 /* "{...} fi" is ok. "{...} if" is not
4040 * Example:
4041 * if { echo foo; } then { echo bar; } fi */
4042 if (ctx->command->group)
4043 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004044 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004045
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004046 ctx->ctx_res_w = r->res;
4047 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004048 ctx->is_assignment = r->assignment_flag;
4049 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004050
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004051 if (ctx->old_flag & FLAG_END) {
4052 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004053
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004054 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004055 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004056 old = ctx->stack;
4057 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004058 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004059# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004060 /* At this point, the compound command's string is in
4061 * ctx->as_string... except for the leading keyword!
4062 * Consider this example: "echo a | if true; then echo a; fi"
4063 * ctx->as_string will contain "true; then echo a; fi",
4064 * with "if " remaining in old->as_string!
4065 */
4066 {
4067 char *str;
4068 int len = old->as_string.length;
4069 /* Concatenate halves */
4070 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004071 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004072 /* Find where leading keyword starts in first half */
4073 str = old->as_string.data + len;
4074 if (str > old->as_string.data)
4075 str--; /* skip whitespace after keyword */
4076 while (str > old->as_string.data && isalpha(str[-1]))
4077 str--;
4078 /* Ugh, we're done with this horrid hack */
4079 old->command->group_as_string = xstrdup(str);
4080 debug_printf_parse("pop, remembering as:'%s'\n",
4081 old->command->group_as_string);
4082 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004083# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004084 *ctx = *old; /* physical copy */
4085 free(old);
4086 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004087 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004088}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004089#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004090
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004091/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004092 * Normal return is 0. Syntax errors return 1.
4093 * Note: on return, word is reset, but not o_free'd!
4094 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004095static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004096{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004097 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004098
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004099 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4100 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004101 debug_printf_parse("done_word return 0: true null, ignored\n");
4102 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004103 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004104
Eric Andersen25f27032001-04-26 23:22:31 +00004105 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004106 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4107 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004108 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004109 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004110 * If the redirection operator is "<<" or "<<-", the word
4111 * that follows the redirection operator shall be
4112 * subjected to quote removal; it is unspecified whether
4113 * any of the other expansions occur. For the other
4114 * redirection operators, the word that follows the
4115 * redirection operator shall be subjected to tilde
4116 * expansion, parameter expansion, command substitution,
4117 * arithmetic expansion, and quote removal.
4118 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004119 * on the word by a non-interactive shell; an interactive
4120 * shell may perform it, but shall do so only when
4121 * the expansion would result in one word."
4122 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004123//bash does not do parameter/command substitution or arithmetic expansion
4124//for _heredoc_ redirection word: these constructs look for exact eof marker
4125// as written:
4126// <<EOF$t
4127// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004128// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4129
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004130 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004131 /* Cater for >\file case:
4132 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4133 * Same with heredocs:
4134 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4135 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004136 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4137 unbackslash(ctx->pending_redirect->rd_filename);
4138 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004139 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004140 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4141 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004142 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004143 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004144 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004145 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004146#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004147# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004148 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004149 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004150 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004151 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004152 /* ctx->ctx_res_w = RES_MATCH; */
4153 ctx->ctx_dsemicolon = 0;
4154 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004155# endif
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004156# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4157 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
4158 && strcmp(ctx->word.data, "]]") == 0
4159 ) {
4160 /* allow "[[ ]] >file" etc */
4161 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4162 } else
4163# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004164 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004165# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004166 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4167 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004168# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004169# if ENABLE_HUSH_CASE
4170 && ctx->ctx_res_w != RES_CASE
4171# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004172 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004173 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004174 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004175 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004176 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004177# if ENABLE_HUSH_LINENO_VAR
4178/* Case:
4179 * "while ...; do
4180 * cmd ..."
4181 * If we don't close the pipe _now_, immediately after "do", lineno logic
4182 * sees "cmd" as starting at "do" - i.e., at the previous line.
4183 */
4184 if (0
4185 IF_HUSH_IF(|| reserved->res == RES_THEN)
4186 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4187 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4188 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4189 ) {
4190 done_pipe(ctx, PIPE_SEQ);
4191 }
4192# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004193 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004194 debug_printf_parse("done_word return %d\n",
4195 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004196 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004197 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004198# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4199 if (strcmp(ctx->word.data, "[[") == 0) {
4200 command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
4201 } else
4202# endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02004203# if defined(CMD_SINGLEWORD_NOGLOB)
4204 if (0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004205 /* In bash, local/export/readonly are special, args
4206 * are assignments and therefore expansion of them
4207 * should be "one-word" expansion:
4208 * $ export i=`echo 'a b'` # one arg: "i=a b"
4209 * compare with:
4210 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4211 * ls: cannot access i=a: No such file or directory
4212 * ls: cannot access b: No such file or directory
4213 * Note: bash 3.2.33(1) does this only if export word
4214 * itself is not quoted:
4215 * $ export i=`echo 'aaa bbb'`; echo "$i"
4216 * aaa bbb
4217 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4218 * aaa
4219 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004220 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4221 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4222 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004223 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004224 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4225 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004226# else
4227 { /* empty block to pair "if ... else" */ }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004228# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004229 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004230#endif /* HAS_KEYWORDS */
4231
Denis Vlasenkobb929512009-04-16 10:59:40 +00004232 if (command->group) {
4233 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004234 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004235 debug_printf_parse("done_word return 1: syntax error, "
4236 "groups and arglists don't mix\n");
4237 return 1;
4238 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004239
4240 /* If this word wasn't an assignment, next ones definitely
4241 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004242 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4243 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004244 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004245 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004246 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004247 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004248 command->assignment_cnt++;
4249 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4250 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004251 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4252 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004253 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004254 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4255 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004256 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004257 }
Eric Andersen25f27032001-04-26 23:22:31 +00004258
Denis Vlasenko06810332007-05-21 23:30:54 +00004259#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004260 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004261 if (ctx->word.has_quoted_part
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02004262 || endofname(command->argv[0])[0] != '\0'
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004263 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004264 /* bash says just "not a valid identifier" */
Denys Vlasenko457825f2021-06-06 12:07:11 +02004265 syntax_error("bad variable name in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004266 return 1;
4267 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004268 /* Force FOR to have just one word (variable name) */
4269 /* NB: basically, this makes hush see "for v in ..."
4270 * syntax as if it is "for v; in ...". FOR and IN become
4271 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004272 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004273 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004274#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004275#if ENABLE_HUSH_CASE
4276 /* Force CASE to have just one word */
4277 if (ctx->ctx_res_w == RES_CASE) {
4278 done_pipe(ctx, PIPE_SEQ);
4279 }
4280#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004281
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004282 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004283
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004284 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004285 return 0;
4286}
4287
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004288
4289/* Peek ahead in the input to find out if we have a "&n" construct,
4290 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004291 * Return:
4292 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4293 * REDIRFD_SYNTAX_ERR if syntax error,
4294 * REDIRFD_TO_FILE if no & was seen,
4295 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004296 */
4297#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004298#define parse_redir_right_fd(as_string, input) \
4299 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004300#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004301static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004302{
4303 int ch, d, ok;
4304
4305 ch = i_peek(input);
4306 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004307 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004308
4309 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004310 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004311 ch = i_peek(input);
4312 if (ch == '-') {
4313 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004314 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004315 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004316 }
4317 d = 0;
4318 ok = 0;
4319 while (ch != EOF && isdigit(ch)) {
4320 d = d*10 + (ch-'0');
4321 ok = 1;
4322 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004323 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004324 ch = i_peek(input);
4325 }
4326 if (ok) return d;
4327
4328//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4329
James Byrne69374872019-07-02 11:35:03 +02004330 bb_simple_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004331 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004332}
4333
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004334/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004335 */
4336static int parse_redirect(struct parse_context *ctx,
4337 int fd,
4338 redir_type style,
4339 struct in_str *input)
4340{
4341 struct command *command = ctx->command;
4342 struct redir_struct *redir;
4343 struct redir_struct **redirp;
4344 int dup_num;
4345
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004346 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004347 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004348 /* Check for a '>&1' type redirect */
4349 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4350 if (dup_num == REDIRFD_SYNTAX_ERR)
4351 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004352 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004353 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004354 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004355 if (dup_num) { /* <<-... */
4356 ch = i_getch(input);
4357 nommu_addchr(&ctx->as_string, ch);
4358 ch = i_peek(input);
4359 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004360 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004361
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004362 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004363 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004364 if (ch == '|') {
4365 /* >|FILE redirect ("clobbering" >).
4366 * Since we do not support "set -o noclobber" yet,
4367 * >| and > are the same for now. Just eat |.
4368 */
4369 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004370 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004371 }
4372 }
4373
4374 /* Create a new redir_struct and append it to the linked list */
4375 redirp = &command->redirects;
4376 while ((redir = *redirp) != NULL) {
4377 redirp = &(redir->next);
4378 }
4379 *redirp = redir = xzalloc(sizeof(*redir));
4380 /* redir->next = NULL; */
4381 /* redir->rd_filename = NULL; */
4382 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004383 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004384
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004385 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4386 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004387
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004388 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004389 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004390 /* Erik had a check here that the file descriptor in question
4391 * is legit; I postpone that to "run time"
4392 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004393 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4394 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004395 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004396#if 0 /* Instead we emit error message at run time */
4397 if (ctx->pending_redirect) {
4398 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004399 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004400 }
4401#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004402 /* Set ctx->pending_redirect, so we know what to do at the
4403 * end of the next parsed word. */
4404 ctx->pending_redirect = redir;
4405 }
4406 return 0;
4407}
4408
Eric Andersen25f27032001-04-26 23:22:31 +00004409/* If a redirect is immediately preceded by a number, that number is
4410 * supposed to tell which file descriptor to redirect. This routine
4411 * looks for such preceding numbers. In an ideal world this routine
4412 * needs to handle all the following classes of redirects...
4413 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4414 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4415 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4416 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004417 *
4418 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4419 * "2.7 Redirection
4420 * ... If n is quoted, the number shall not be recognized as part of
4421 * the redirection expression. For example:
4422 * echo \2>a
4423 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004424 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004425 *
4426 * A -1 return means no valid number was found,
4427 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004428 */
4429static int redirect_opt_num(o_string *o)
4430{
4431 int num;
4432
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004433 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004434 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004435 num = bb_strtou(o->data, NULL, 10);
4436 if (errno || num < 0)
4437 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004438 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004439 return num;
4440}
4441
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004442#if BB_MMU
4443#define fetch_till_str(as_string, input, word, skip_tabs) \
4444 fetch_till_str(input, word, skip_tabs)
4445#endif
4446static char *fetch_till_str(o_string *as_string,
4447 struct in_str *input,
4448 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004449 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004450{
4451 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004452 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004453 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004454 int ch;
4455
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004456 /* Starting with "" is necessary for this case:
4457 * cat <<EOF
4458 *
4459 * xxx
4460 * EOF
4461 */
4462 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4463
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004464 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004465
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004466 while (1) {
4467 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004468 if (ch != EOF)
4469 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004470 if (ch == '\n' || ch == EOF) {
4471 check_heredoc_end:
4472 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004473 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004474 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4475 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004476 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004477 return heredoc.data;
4478 }
4479 if (ch == '\n') {
4480 /* This is a new line.
4481 * Remember position and backslash-escaping status.
4482 */
4483 o_addchr(&heredoc, ch);
4484 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004485 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004486 past_EOL = heredoc.length;
4487 /* Get 1st char of next line, possibly skipping leading tabs */
4488 do {
4489 ch = i_getch(input);
4490 if (ch != EOF)
4491 nommu_addchr(as_string, ch);
4492 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4493 /* If this immediately ended the line,
4494 * go back to end-of-line checks.
4495 */
4496 if (ch == '\n')
4497 goto check_heredoc_end;
4498 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004499 } else {
4500 /* Backslash-line continuation in an unquoted
4501 * heredoc. This does not need special handling
4502 * for heredoc body (unquoted heredocs are
4503 * expanded on "execution" and that would take
4504 * care of this case too), but not the case
4505 * of line continuation *in terminator*:
4506 * cat <<EOF
4507 * Ok1
4508 * EO\
4509 * F
4510 */
4511 heredoc.data[--heredoc.length] = '\0';
4512 prev = 0; /* not '\' */
4513 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004514 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004515 }
4516 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004517 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004518 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004519 }
4520 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004521 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004522 if (prev == '\\' && ch == '\\')
4523 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004524 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004525 else
4526 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004527 }
4528}
4529
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004530/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4531 * and load them all. There should be exactly heredoc_cnt of them.
4532 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004533#if BB_MMU
4534#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4535 fetch_heredocs(pi, heredoc_cnt, input)
4536#endif
4537static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004538{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004539 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004540 int i;
4541 struct command *cmd = pi->cmds;
4542
Denys Vlasenko3675c372018-07-23 16:31:21 +02004543 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004544 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004545 cmd->argv ? cmd->argv[0] : "NONE"
4546 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004547 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004548 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004549
Denys Vlasenko3675c372018-07-23 16:31:21 +02004550 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004551 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004552 while (redir) {
4553 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004554 char *p;
4555
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004556 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004557 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004558 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004559 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004560 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004561 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004562 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004563 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004564 free(redir->rd_filename);
4565 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004566 heredoc_cnt--;
4567 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004568 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004569 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004570 if (cmd->group) {
4571 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4572 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4573 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4574 if (heredoc_cnt < 0)
4575 return heredoc_cnt; /* error */
4576 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004577 cmd++;
4578 }
4579 pi = pi->next;
4580 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004581 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004582}
4583
4584
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004585static int run_list(struct pipe *pi);
4586#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004587#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4588 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004589#endif
4590static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004591 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004592 struct in_str *input,
4593 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004594
Denys Vlasenko474cb202018-07-24 13:03:03 +02004595/* Returns number of heredocs not yet consumed,
4596 * or -1 on error.
4597 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004598static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004599 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004600{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004601 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004602 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004603 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004604#if BB_MMU
4605# define as_string NULL
4606#else
4607 char *as_string = NULL;
4608#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004609 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004610 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004611 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004612 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004613
4614 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004615#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004616 if (ch == '(' && !ctx->word.has_quoted_part) {
4617 if (ctx->word.length)
4618 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004619 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004620 if (!command->argv)
4621 goto skip; /* (... */
4622 if (command->argv[1]) { /* word word ... (... */
4623 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004624 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004625 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004626 /* it is "word(..." or "word (..." */
4627 do
4628 ch = i_getch(input);
4629 while (ch == ' ' || ch == '\t');
4630 if (ch != ')') {
4631 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004632 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004633 }
4634 nommu_addchr(&ctx->as_string, ch);
4635 do
4636 ch = i_getch(input);
4637 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004638 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004639 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004640 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004641 }
4642 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004643 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004644 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004645 }
4646#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004647
4648#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004649 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004650 || ctx->word.length /* word{... */
4651 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004652 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004653 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004654 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004655 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004656 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004657 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004658#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004659
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004660 IF_HUSH_FUNCTIONS(skip:)
4661
Denis Vlasenko240c2552009-04-03 03:45:05 +00004662 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004663 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004664 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004665 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4666 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004667 } else {
4668 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004669 ch = i_peek(input);
4670 if (ch != ' ' && ch != '\t' && ch != '\n'
4671 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4672 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004673 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004674 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004675 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004676 if (ch != '(') {
4677 ch = i_getch(input);
4678 nommu_addchr(&ctx->as_string, ch);
4679 }
Eric Andersen25f27032001-04-26 23:22:31 +00004680 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004681
Denys Vlasenko474cb202018-07-24 13:03:03 +02004682 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4683 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4684 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004685#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004686 if (as_string)
4687 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004688#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004689
4690 /* empty ()/{} or parse error? */
4691 if (!pipe_list || pipe_list == ERR_PTR) {
4692 /* parse_stream already emitted error msg */
4693 if (!BB_MMU)
4694 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004695 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004696 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004697 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004698 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004699#if !BB_MMU
4700 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4701 command->group_as_string = as_string;
4702 debug_printf_parse("end of group, remembering as:'%s'\n",
4703 command->group_as_string);
4704#endif
4705
4706#if ENABLE_HUSH_FUNCTIONS
4707 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4708 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4709 struct command *cmd2;
4710
4711 cmd2 = xzalloc(sizeof(*cmd2));
4712 cmd2->cmd_type = CMD_SUBSHELL;
4713 cmd2->group = pipe_list;
4714# if !BB_MMU
4715//UNTESTED!
4716 cmd2->group_as_string = command->group_as_string;
4717 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4718# endif
4719
4720 pipe_list = new_pipe();
4721 pipe_list->cmds = cmd2;
4722 pipe_list->num_cmds = 1;
4723 }
4724#endif
4725
4726 command->group = pipe_list;
4727
Denys Vlasenko474cb202018-07-24 13:03:03 +02004728 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4729 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004730 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004731#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004732}
4733
Denys Vlasenko0b883582016-12-23 16:49:07 +01004734#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004735/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004736/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004737static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004738{
4739 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004740 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004741 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004742 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004743 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004744 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004745 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004746 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004747 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004748 }
4749}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004750static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4751{
4752 while (1) {
4753 int ch = i_getch(input);
4754 if (ch == EOF) {
4755 syntax_error_unterm_ch('\'');
4756 return 0;
4757 }
4758 if (ch == '\'')
4759 return 1;
4760 o_addqchr(dest, ch);
4761 }
4762}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004763/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004764static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004765static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004766{
4767 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004768 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004769 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004770 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004771 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004772 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004773 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004774 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004775 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004776 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004777 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004778 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004779 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004780 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004781 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4782 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004783 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004784 continue;
4785 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004786 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004787 }
4788}
4789/* Process `cmd` - copy contents until "`" is seen. Complicated by
4790 * \` quoting.
4791 * "Within the backquoted style of command substitution, backslash
4792 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4793 * The search for the matching backquote shall be satisfied by the first
4794 * backquote found without a preceding backslash; during this search,
4795 * if a non-escaped backquote is encountered within a shell comment,
4796 * a here-document, an embedded command substitution of the $(command)
4797 * form, or a quoted string, undefined results occur. A single-quoted
4798 * or double-quoted string that begins, but does not end, within the
4799 * "`...`" sequence produces undefined results."
4800 * Example Output
4801 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4802 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004803static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004804{
4805 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004806 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004807 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004808 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004809 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004810 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4811 ch = i_getch(input);
4812 if (ch != '`'
4813 && ch != '$'
4814 && ch != '\\'
4815 && (!in_dquote || ch != '"')
4816 ) {
4817 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004818 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004819 }
4820 if (ch == EOF) {
4821 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004822 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004823 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004824 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004825 }
4826}
4827/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4828 * quoting and nested ()s.
4829 * "With the $(command) style of command substitution, all characters
4830 * following the open parenthesis to the matching closing parenthesis
4831 * constitute the command. Any valid shell script can be used for command,
4832 * except a script consisting solely of redirections which produces
4833 * unspecified results."
4834 * Example Output
4835 * echo $(echo '(TEST)' BEST) (TEST) BEST
4836 * echo $(echo 'TEST)' BEST) TEST) BEST
4837 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004838 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004839 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004840 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004841 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4842 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004843 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004844#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004845static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004846{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004847 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004848 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004849# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004850 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004851# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004852 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4853
Denys Vlasenko259747c2019-11-28 10:28:14 +01004854# if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004855 G.promptmode = 1; /* PS2 */
Denys Vlasenko259747c2019-11-28 10:28:14 +01004856# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004857 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4858
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004859 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004860 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004861 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004862 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004863 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004864 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004865 if (ch == end_ch
4866# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004867 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004868# endif
4869 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004870 if (!dbl)
4871 break;
4872 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004873 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004874 i_getch(input); /* eat second ')' */
4875 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004876 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004877 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004878 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004879 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004880 if (ch == '(' || ch == '{') {
4881 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004882 if (!add_till_closing_bracket(dest, input, ch))
4883 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004884 o_addchr(dest, ch);
4885 continue;
4886 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004887 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004888 if (!add_till_single_quote(dest, input))
4889 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004890 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004891 continue;
4892 }
4893 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004894 if (!add_till_double_quote(dest, input))
4895 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004896 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004897 continue;
4898 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004899 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004900 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4901 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004902 o_addchr(dest, ch);
4903 continue;
4904 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004905 if (ch == '\\') {
4906 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004907 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004908 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004909 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004910 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004911 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004912# if 0
Denys Vlasenko657086a2016-09-29 18:07:42 +02004913 if (ch == '\n') {
4914 /* "backslash+newline", ignore both */
4915 o_delchr(dest); /* undo insertion of '\' */
4916 continue;
4917 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004918# endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004919 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004920 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004921 continue;
4922 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004923 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004924 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004925 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004926}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004927#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004928
Denys Vlasenkob278d822021-07-26 15:29:13 +02004929#if BASH_DOLLAR_SQUOTE
4930/* Return code: 1 for "found and parsed", 0 for "seen something else" */
Denys Vlasenko8dd676c2021-07-27 04:09:45 +02004931# if BB_MMU
Denys Vlasenkob278d822021-07-26 15:29:13 +02004932#define parse_dollar_squote(as_string, dest, input) \
4933 parse_dollar_squote(dest, input)
4934#define as_string NULL
Denys Vlasenko8dd676c2021-07-27 04:09:45 +02004935# endif
Denys Vlasenkob278d822021-07-26 15:29:13 +02004936static int parse_dollar_squote(o_string *as_string, o_string *dest, struct in_str *input)
4937{
4938 int start;
4939 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4940 debug_printf_parse("parse_dollar_squote entered: ch='%c'\n", ch);
4941 if (ch != '\'')
4942 return 0;
4943
4944 dest->has_quoted_part = 1;
4945 start = dest->length;
4946
4947 ch = i_getch(input); /* eat ' */
4948 nommu_addchr(as_string, ch);
4949 while (1) {
4950 ch = i_getch(input);
4951 nommu_addchr(as_string, ch);
4952 if (ch == EOF) {
4953 syntax_error_unterm_ch('\'');
4954 return 0;
4955 }
4956 if (ch == '\'')
4957 break;
4958 if (ch == SPECIAL_VAR_SYMBOL) {
4959 /* Convert raw ^C to corresponding special variable reference */
4960 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4961 o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
4962 /* will addchr() another SPECIAL_VAR_SYMBOL (see after the if() block) */
4963 } else if (ch == '\\') {
4964 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
4965
4966 ch = i_getch(input);
4967 nommu_addchr(as_string, ch);
4968 if (strchr(C_escapes, ch)) {
4969 char buf[4];
4970 char *p = buf;
4971 int cnt = 2;
4972
4973 buf[0] = ch;
4974 if ((unsigned char)(ch - '0') <= 7) { /* \ooo */
4975 do {
4976 ch = i_peek(input);
4977 if ((unsigned char)(ch - '0') > 7)
4978 break;
4979 *++p = ch = i_getch(input);
4980 nommu_addchr(as_string, ch);
4981 } while (--cnt != 0);
4982 } else if (ch == 'x') { /* \xHH */
4983 do {
4984 ch = i_peek(input);
4985 if (!isxdigit(ch))
4986 break;
4987 *++p = ch = i_getch(input);
4988 nommu_addchr(as_string, ch);
4989 } while (--cnt != 0);
4990 if (cnt == 2) { /* \x but next char is "bad" */
4991 ch = 'x';
4992 goto unrecognized;
4993 }
4994 } /* else simple seq like \\ or \t */
4995 *++p = '\0';
4996 p = buf;
4997 ch = bb_process_escape_sequence((void*)&p);
4998 //bb_error_msg("buf:'%s' ch:%x", buf, ch);
4999 if (ch == '\0')
5000 continue; /* bash compat: $'...\0...' emits nothing */
5001 } else { /* unrecognized "\z": encode both chars unless ' or " */
5002 if (ch != '\'' && ch != '"') {
5003 unrecognized:
5004 o_addqchr(dest, '\\');
5005 }
5006 }
5007 } /* if (\...) */
5008 o_addqchr(dest, ch);
5009 }
5010
5011 if (dest->length == start) {
5012 /* $'', $'\0', $'\000\x00' and the like */
5013 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5014 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5015 }
5016
5017 return 1;
Denys Vlasenko8dd676c2021-07-27 04:09:45 +02005018# undef as_string
Denys Vlasenkob278d822021-07-26 15:29:13 +02005019}
5020#else
Denys Vlasenko21afdde2021-08-15 20:08:53 +02005021# define parse_dollar_squote(as_string, dest, input) 0
Denys Vlasenkob278d822021-07-26 15:29:13 +02005022#endif /* BASH_DOLLAR_SQUOTE */
5023
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005024/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005025#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005026#define parse_dollar(as_string, dest, input, quote_mask) \
5027 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005028#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005029#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005030static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005031 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005032 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00005033{
Denys Vlasenko657086a2016-09-29 18:07:42 +02005034 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005035
Denys Vlasenkob278d822021-07-26 15:29:13 +02005036 debug_printf_parse("parse_dollar entered: ch='%c' quote_mask:0x%x\n", ch, quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005037 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005038 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005039 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005040 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005041 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005042 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005043 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005044 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005045 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005046 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02005047 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02005048 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02005049 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005050 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02005051 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005052 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005053 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005054 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005055 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005056 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005057 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005058 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005059 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005060 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005061 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005062 o_addchr(dest, ch | quote_mask);
5063 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005064 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005065 case '$': /* pid */
5066 case '!': /* last bg pid */
5067 case '?': /* last exit code */
5068 case '#': /* number of args */
5069 case '*': /* args */
5070 case '@': /* args */
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005071 case '-': /* $- option flags set by set builtin or shell options (-i etc) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005072 goto make_one_char_var;
5073 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005074 char len_single_ch;
5075
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005076 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5077
Denys Vlasenko74369502010-05-21 19:52:01 +02005078 ch = i_getch(input); /* eat '{' */
5079 nommu_addchr(as_string, ch);
5080
Denys Vlasenko46e64982016-09-29 19:50:55 +02005081 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02005082 /* It should be ${?}, or ${#var},
5083 * or even ${?+subst} - operator acting on a special variable,
5084 * or the beginning of variable name.
5085 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005086 if (ch == EOF
5087 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
5088 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02005089 bad_dollar_syntax:
5090 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005091 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
5092 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02005093 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005094 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005095 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02005096 ch |= quote_mask;
5097
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005098 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02005099 * However, this regresses some of our testsuite cases
5100 * which check invalid constructs like ${%}.
5101 * Oh well... let's check that the var name part is fine... */
5102
Denys Vlasenko97c3b5e2021-06-19 15:28:10 +02005103 if (isdigit(len_single_ch)
5104 || (len_single_ch == '#' && isdigit(i_peek_and_eat_bkslash_nl(input)))
5105 ) {
5106 /* Execution engine uses plain xatoi_positive()
5107 * to interpret ${NNN} and {#NNN},
5108 * check syntax here in the parser.
5109 * (bash does not support expressions in ${#NN},
5110 * e.g. ${#$var} and {#1:+WORD} are not supported).
5111 */
5112 unsigned cnt = 9; /* max 9 digits for ${NN} and 8 for {#NN} */
5113 while (1) {
5114 o_addchr(dest, ch);
5115 debug_printf_parse(": '%c'\n", ch);
5116 ch = i_getch_and_eat_bkslash_nl(input);
5117 nommu_addchr(as_string, ch);
5118 if (ch == '}')
5119 break;
5120 if (--cnt == 0)
5121 goto bad_dollar_syntax;
5122 if (len_single_ch != '#' && strchr(VAR_SUBST_OPS, ch))
5123 /* ${NN<op>...} is valid */
5124 goto eat_until_closing;
5125 if (!isdigit(ch))
5126 goto bad_dollar_syntax;
5127 }
5128 } else
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005129 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005130 unsigned pos;
5131
Denys Vlasenko74369502010-05-21 19:52:01 +02005132 o_addchr(dest, ch);
5133 debug_printf_parse(": '%c'\n", ch);
5134
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005135 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005136 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02005137 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00005138 break;
Denys Vlasenko74369502010-05-21 19:52:01 +02005139 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005140 unsigned end_ch;
5141 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005142 /* handle parameter expansions
5143 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5144 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005145 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
5146 if (len_single_ch != '#'
5147 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
5148 || i_peek(input) != '}'
5149 ) {
5150 goto bad_dollar_syntax;
5151 }
5152 /* else: it's "length of C" ${#C} op,
5153 * where C is a single char
5154 * special var name, e.g. ${#!}.
5155 */
5156 }
Denys Vlasenko97c3b5e2021-06-19 15:28:10 +02005157 eat_until_closing:
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005158 /* Eat everything until closing '}' (or ':') */
5159 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005160 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005161 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005162 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005163 ) {
5164 /* It's ${var:N[:M]} thing */
5165 end_ch = '}' * 0x100 + ':';
5166 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005167 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005168 && ch == '/'
5169 ) {
5170 /* It's ${var/[/]pattern[/repl]} thing */
5171 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
5172 i_getch(input);
5173 nommu_addchr(as_string, '/');
5174 ch = '\\';
5175 }
5176 end_ch = '}' * 0x100 + '/';
5177 }
5178 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02005179 /* The pattern can't be empty.
5180 * IOW: if the first char after "${v//" is a slash,
5181 * it does not terminate the pattern - it's the first char of the pattern:
5182 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
5183 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
5184 */
5185 if (i_peek(input) == '/') {
5186 o_addchr(dest, i_getch(input));
5187 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005188 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005189 if (!BB_MMU)
5190 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005191#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005192 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005193 if (last_ch == 0) /* error? */
5194 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005195#else
Denys Vlasenko259747c2019-11-28 10:28:14 +01005196# error Simple code to only allow ${var} is not implemented
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005197#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005198 if (as_string) {
5199 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005200 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005201 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005202
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005203 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5204 && (end_ch & 0xff00)
5205 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005206 /* close the first block: */
5207 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005208 /* while parsing N from ${var:N[:M]}
5209 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005210 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005211 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005212 end_ch = '}';
5213 goto again;
5214 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005215 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005216 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005217 /* it's ${var:N} - emulate :999999999 */
5218 o_addstr(dest, "999999999");
5219 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005220 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005221 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005222 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005223 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005224 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005225 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5226 break;
5227 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005228#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005229 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005230 unsigned pos;
5231
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005232 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005233 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005234# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005235 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005236 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005237 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005238 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01005239 o_addchr(dest, quote_mask | '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005240 if (!BB_MMU)
5241 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005242 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5243 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005244 if (as_string) {
5245 o_addstr(as_string, dest->data + pos);
5246 o_addchr(as_string, ')');
5247 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005248 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005249 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005250 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005251 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005252# endif
5253# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005254 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5255 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005256 if (!BB_MMU)
5257 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005258 if (!add_till_closing_bracket(dest, input, ')'))
5259 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005260 if (as_string) {
5261 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005262 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005263 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005264 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005265# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005266 break;
5267 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005268#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005269 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005270 goto make_var;
5271#if 0
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005272 /* TODO: $_: */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005273 /* $_ Shell or shell script name; or last argument of last command
5274 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5275 * but in command's env, set to full pathname used to invoke it */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005276 ch = i_getch(input);
5277 nommu_addchr(as_string, ch);
5278 ch = i_peek_and_eat_bkslash_nl(input);
5279 if (isalnum(ch)) { /* it's $_name or $_123 */
5280 ch = '_';
5281 goto make_var1;
5282 }
5283 /* else: it's $_ */
5284#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005285 default:
5286 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005287 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005288 debug_printf_parse("parse_dollar return 1 (ok)\n");
5289 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005290#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005291}
5292
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005293#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005294#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005295 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005296#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005297#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005298static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005299 o_string *dest,
5300 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005301 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005302{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005303 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005304 int next;
5305
5306 again:
5307 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005308 if (ch != EOF)
5309 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005310 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005311 debug_printf_parse("encode_string return 1 (ok)\n");
5312 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005313 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005314 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005315 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005316 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005317 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005318 }
5319 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005320 if (ch != '\n') {
5321 next = i_peek(input);
5322 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005323 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005324 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005325 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005326 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005327 /* Testcase: in interactive shell a file with
5328 * echo "unterminated string\<eof>
5329 * is sourced.
5330 */
5331 syntax_error_unterm_ch('"');
5332 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005333 }
5334 /* bash:
5335 * "The backslash retains its special meaning [in "..."]
5336 * only when followed by one of the following characters:
5337 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005338 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005339 * NB: in (unquoted) heredoc, above does not apply to ",
5340 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005341 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005342 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005343 ch = i_getch(input); /* eat next */
5344 if (ch == '\n')
5345 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005346 } /* else: ch remains == '\\', and we double it below: */
5347 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005348 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005349 goto again;
5350 }
5351 if (ch == '$') {
Denys Vlasenkob278d822021-07-26 15:29:13 +02005352 //if (parse_dollar_squote(as_string, dest, input))
5353 // goto again;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005354 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5355 debug_printf_parse("encode_string return 0: "
5356 "parse_dollar returned 0 (error)\n");
5357 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005358 }
5359 goto again;
5360 }
5361#if ENABLE_HUSH_TICK
5362 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005363 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005364 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5365 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005366 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5367 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005368 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5369 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005370 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005371 }
5372#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005373 o_addQchr(dest, ch);
Denys Vlasenko1b7a9b62021-06-15 16:05:57 +02005374 if (ch == SPECIAL_VAR_SYMBOL) {
5375 /* Convert "^C" to corresponding special variable reference */
5376 o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
5377 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5378 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005379 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005380#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005381}
5382
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005383/*
5384 * Scan input until EOF or end_trigger char.
5385 * Return a list of pipes to execute, or NULL on EOF
5386 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005387 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005388 * reset parsing machinery and start parsing anew,
5389 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005390 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005391static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005392 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005393 struct in_str *input,
5394 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005395{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005396 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005397 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005398
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005399 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005400 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005401 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005402 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005403 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005404 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005405
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005406 initialize_context(&ctx);
5407
5408 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5409 * Preventing this:
5410 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005411 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005412
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005413 /* We used to separate words on $IFS here. This was wrong.
5414 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005415 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005416 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005417
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005418 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005419 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005420 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005421 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005422 int ch;
5423 int next;
5424 int redir_fd;
5425 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005426
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005427 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005428 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005429 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005430 if (ch == EOF) {
5431 struct pipe *pi;
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01005432
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005433 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005434 syntax_error_unterm_str("here document");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005435 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005436 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005437 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005438 syntax_error_unterm_ch('(');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005439 goto parse_error_exitcode1;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005440 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005441 if (end_trigger == '}') {
5442 syntax_error_unterm_ch('{');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005443 goto parse_error_exitcode1;
Denys Vlasenko42246472016-11-07 16:22:35 +01005444 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005445
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005446 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005447 goto parse_error_exitcode1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005448 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005449 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005450 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005451 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005452 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005453 /* (this makes bare "&" cmd a no-op.
5454 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005455 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005456 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005457 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005458 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005459 pi = NULL;
5460 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005461#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005462 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005463 if (pstring)
5464 *pstring = ctx.as_string.data;
5465 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005466 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005467#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005468 // heredoc_cnt must be 0 here anyway
5469 //if (heredoc_cnt_ptr)
5470 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005471 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005472 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005473 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005474 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005475 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005476
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005477 /* Handle "'" and "\" first, as they won't play nice with
5478 * i_peek_and_eat_bkslash_nl() anyway:
5479 * echo z\\
5480 * and
5481 * echo '\
5482 * '
5483 * would break.
5484 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005485 if (ch == '\\') {
5486 ch = i_getch(input);
5487 if (ch == '\n')
5488 continue; /* drop \<newline>, get next char */
5489 nommu_addchr(&ctx.as_string, '\\');
Denys Vlasenko1b7a9b62021-06-15 16:05:57 +02005490 if (ch == SPECIAL_VAR_SYMBOL) {
5491 nommu_addchr(&ctx.as_string, ch);
5492 /* Convert \^C to corresponding special variable reference */
5493 goto case_SPECIAL_VAR_SYMBOL;
5494 }
Denys Vlasenkof693b602018-04-11 20:00:43 +02005495 o_addchr(&ctx.word, '\\');
5496 if (ch == EOF) {
5497 /* Testcase: eval 'echo Ok\' */
5498 /* bash-4.3.43 was removing backslash,
5499 * but 4.4.19 retains it, most other shells too
5500 */
5501 continue; /* get next char */
5502 }
5503 /* Example: echo Hello \2>file
5504 * we need to know that word 2 is quoted
5505 */
5506 ctx.word.has_quoted_part = 1;
5507 nommu_addchr(&ctx.as_string, ch);
5508 o_addchr(&ctx.word, ch);
5509 continue; /* get next char */
5510 }
5511 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005512 if (ch == '\'') {
5513 ctx.word.has_quoted_part = 1;
5514 next = i_getch(input);
5515 if (next == '\'' && !ctx.pending_redirect)
5516 goto insert_empty_quoted_str_marker;
5517
5518 ch = next;
5519 while (1) {
5520 if (ch == EOF) {
5521 syntax_error_unterm_ch('\'');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005522 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005523 }
5524 nommu_addchr(&ctx.as_string, ch);
5525 if (ch == '\'')
5526 break;
5527 if (ch == SPECIAL_VAR_SYMBOL) {
5528 /* Convert raw ^C to corresponding special variable reference */
5529 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5530 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5531 }
5532 o_addqchr(&ctx.word, ch);
5533 ch = i_getch(input);
5534 }
5535 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005536 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005537
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005538 next = '\0';
5539 if (ch != '\n')
5540 next = i_peek_and_eat_bkslash_nl(input);
5541
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005542 is_special = "{}<>&|();#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005543 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005544 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005545#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
5546 if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
5547 /* In [[ ]], {}<>&|() are not special */
5548 is_special += 8;
5549 } else
5550#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005551 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005552 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005553 || ctx.word.length /* word{... - non-special */
5554 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005555 || (next != ';' /* }; - special */
5556 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005557 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005558 && next != '&' /* }& and }&& ... - special */
5559 && next != '|' /* }|| ... - special */
5560 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005561 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005562 ) {
5563 /* They are not special, skip "{}" */
5564 is_special += 2;
5565 }
5566 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005567 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005568
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005569 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005570 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005571 o_addQchr(&ctx.word, ch);
5572 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5573 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005574 && ch == '='
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02005575 && endofname(ctx.word.data)[0] == '='
Denis Vlasenko55789c62008-06-18 16:30:42 +00005576 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005577 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5578 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005579 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005580 continue;
5581 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005582
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005583 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005584#if ENABLE_HUSH_LINENO_VAR
5585/* Case:
5586 * "while ...; do<whitespace><newline>
5587 * cmd ..."
5588 * would think that "cmd" starts in <whitespace> -
5589 * i.e., at the previous line.
5590 * We need to skip all whitespace before newlines.
5591 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005592 while (ch != '\n') {
5593 next = i_peek(input);
5594 if (next != ' ' && next != '\t' && next != '\n')
5595 break; /* next char is not ws */
5596 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005597 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005598 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005599#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005600 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005601 goto parse_error_exitcode1;
Eric Andersenaac75e52001-04-30 18:18:45 +00005602 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005603 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005604 /* Is this a case when newline is simply ignored?
5605 * Some examples:
5606 * "cmd | <newline> cmd ..."
5607 * "case ... in <newline> word) ..."
5608 */
5609 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005610 && ctx.word.length == 0
5611 && !ctx.word.has_quoted_part
5612 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005613 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005614 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005615 * Without check #1, interactive shell
5616 * ignores even bare <newline>,
5617 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005618 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005619 * ps2> _ <=== wrong, should be ps1
5620 * Without check #2, "cmd & <newline>"
5621 * is similarly mistreated.
5622 * (BTW, this makes "cmd & cmd"
5623 * and "cmd && cmd" non-orthogonal.
5624 * Really, ask yourself, why
5625 * "cmd && <newline>" doesn't start
5626 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005627 * The only reason is that it might be
5628 * a "cmd1 && <nl> cmd2 &" construct,
5629 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005630 */
5631 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005632 if (pi->num_cmds != 0 /* check #1 */
5633 && pi->followup != PIPE_BG /* check #2 */
5634 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005635 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005636 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005637 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005638 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005639 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005640 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005641 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005642 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5643 if (heredoc_cnt != 0)
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005644 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005645 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005646 ctx.is_assignment = MAYBE_ASSIGNMENT;
5647 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005648 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005649 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005650 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005651 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005652 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005653
5654 /* "cmd}" or "cmd }..." without semicolon or &:
5655 * } is an ordinary char in this case, even inside { cmd; }
5656 * Pathological example: { ""}; } should exec "}" cmd
5657 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005658 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005659 if (ctx.word.length != 0 /* word} */
5660 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005661 ) {
5662 goto ordinary_char;
5663 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005664 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5665 /* Generally, there should be semicolon: "cmd; }"
5666 * However, bash allows to omit it if "cmd" is
5667 * a group. Examples:
5668 * { { echo 1; } }
5669 * {(echo 1)}
5670 * { echo 0 >&2 | { echo 1; } }
5671 * { while false; do :; done }
5672 * { case a in b) ;; esac }
5673 */
5674 if (ctx.command->group)
5675 goto term_group;
5676 goto ordinary_char;
5677 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005678 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005679 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005680 goto skip_end_trigger;
5681 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005682 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005683 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005684 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005685 && (ch != ';' || heredoc_cnt == 0)
5686#if ENABLE_HUSH_CASE
5687 && (ch != ')'
5688 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005689 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005690 )
5691#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005692 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005693 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005694 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005695 }
5696 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005697 ctx.is_assignment = MAYBE_ASSIGNMENT;
5698 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005699 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005700 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005701 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005702 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005703 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005704#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005705 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005706 if (pstring)
5707 *pstring = ctx.as_string.data;
5708 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005709 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005710#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005711 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5712 /* Example: bare "{ }", "()" */
5713 G.last_exitcode = 2; /* bash compat */
5714 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005715 goto parse_error;
Denys Vlasenko39701202017-08-02 19:44:05 +02005716 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005717 if (heredoc_cnt_ptr)
5718 *heredoc_cnt_ptr = heredoc_cnt;
5719 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005720 debug_printf_parse("parse_stream return %p: "
5721 "end_trigger char found\n",
5722 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005723 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005724 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005725 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005726 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005727
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005728 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005729 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005730
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005731 /* Catch <, > before deciding whether this word is
5732 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5733 switch (ch) {
5734 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005735 redir_fd = redirect_opt_num(&ctx.word);
5736 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005737 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005738 }
5739 redir_style = REDIRECT_OVERWRITE;
5740 if (next == '>') {
5741 redir_style = REDIRECT_APPEND;
5742 ch = i_getch(input);
5743 nommu_addchr(&ctx.as_string, ch);
5744 }
5745#if 0
5746 else if (next == '(') {
5747 syntax_error(">(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005748 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005749 }
5750#endif
5751 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005752 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005753 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005754 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005755 redir_fd = redirect_opt_num(&ctx.word);
5756 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005757 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005758 }
5759 redir_style = REDIRECT_INPUT;
5760 if (next == '<') {
5761 redir_style = REDIRECT_HEREDOC;
5762 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005763 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005764 ch = i_getch(input);
5765 nommu_addchr(&ctx.as_string, ch);
5766 } else if (next == '>') {
5767 redir_style = REDIRECT_IO;
5768 ch = i_getch(input);
5769 nommu_addchr(&ctx.as_string, ch);
5770 }
5771#if 0
5772 else if (next == '(') {
5773 syntax_error("<(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005774 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005775 }
5776#endif
5777 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005778 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005779 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005780 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005781 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005782 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005783 /* note: we do not add it to &ctx.as_string */
5784/* TODO: in bash:
5785 * comment inside $() goes to the next \n, even inside quoted string (!):
5786 * cmd "$(cmd2 #comment)" - syntax error
5787 * cmd "`cmd2 #comment`" - ok
5788 * We accept both (comment ends where command subst ends, in both cases).
5789 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005790 while (1) {
5791 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005792 if (ch == '\n') {
5793 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005794 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005795 }
5796 ch = i_getch(input);
5797 if (ch == EOF)
5798 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005799 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005800 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005801 }
5802 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005803 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005804 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005805
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005806 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005807 /* check that we are not in word in "a=1 2>word b=1": */
5808 && !ctx.pending_redirect
5809 ) {
5810 /* ch is a special char and thus this word
5811 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005812 ctx.is_assignment = NOT_ASSIGNMENT;
5813 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005814 }
5815
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005816 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5817
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005818 switch (ch) {
Denys Vlasenko1b7a9b62021-06-15 16:05:57 +02005819 case_SPECIAL_VAR_SYMBOL:
Denys Vlasenko932b9972018-01-11 12:39:48 +01005820 case SPECIAL_VAR_SYMBOL:
5821 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005822 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5823 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005824 /* fall through */
5825 case '#':
5826 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005827 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005828 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005829 case '$':
Denys Vlasenkob278d822021-07-26 15:29:13 +02005830 if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
5831 continue; /* get next char */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005832 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005833 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005834 "parse_dollar returned 0 (error)\n");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005835 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005836 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005837 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005838 case '"':
5839 ctx.word.has_quoted_part = 1;
5840 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005841 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005842 insert_empty_quoted_str_marker:
5843 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005844 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5845 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005846 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005847 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005848 if (ctx.is_assignment == NOT_ASSIGNMENT)
5849 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005850 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005851 goto parse_error_exitcode1;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005852 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005853 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005854#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005855 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005856 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005857
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005858 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5859 o_addchr(&ctx.word, '`');
5860 USE_FOR_NOMMU(pos = ctx.word.length;)
5861 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005862 goto parse_error_exitcode1;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005863# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005864 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005865 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005866# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005867 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5868 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005869 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005870 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005871#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005872 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005873#if ENABLE_HUSH_CASE
5874 case_semi:
5875#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005876 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005877 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005878 }
5879 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005880#if ENABLE_HUSH_CASE
5881 /* Eat multiple semicolons, detect
5882 * whether it means something special */
5883 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005884 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005885 if (ch != ';')
5886 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005887 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005888 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005889 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005890 ctx.ctx_dsemicolon = 1;
5891 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005892 break;
5893 }
5894 }
5895#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005896 new_cmd:
5897 /* We just finished a cmd. New one may start
5898 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005899 ctx.is_assignment = MAYBE_ASSIGNMENT;
5900 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005901 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005902 case '&':
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 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005906 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005907 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005908 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005909 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005910 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005911 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005912 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005913 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005914 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005915 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005916 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005917 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005918#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005919 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005920 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005921#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005922 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005923 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005924 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005925 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005926 } else {
5927 /* we could pick up a file descriptor choice here
5928 * with redirect_opt_num(), but bash doesn't do it.
5929 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005930 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005931 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005932 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005933 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005934#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005935 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005936 if (ctx.ctx_res_w == RES_MATCH
5937 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005938 && ctx.word.length == 0 /* not word(... */
5939 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005940 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005941 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005942 }
5943#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005944 /* fall through */
5945 case '{': {
5946 int n = parse_group(&ctx, input, ch);
5947 if (n < 0) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005948 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005949 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005950 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5951 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005952 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005953 }
Eric Andersen25f27032001-04-26 23:22:31 +00005954 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005955#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005956 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005957 goto case_semi;
5958#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005959 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005960 /* proper use of this character is caught by end_trigger:
5961 * if we see {, we call parse_group(..., end_trigger='}')
5962 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005963 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005964 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005965 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005966 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005967 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005968 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005969 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005970 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005971
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005972 parse_error_exitcode1:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005973 G.last_exitcode = 1;
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005974 parse_error:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005975 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005976 struct parse_context *pctx;
5977 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005978
5979 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005980 * Sample for finding leaks on syntax error recovery path.
5981 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005982 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005983 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005984 * while if (true | { true;}); then echo ok; fi; do break; done
5985 * 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 +00005986 */
5987 pctx = &ctx;
5988 do {
5989 /* Update pipe/command counts,
5990 * otherwise freeing may miss some */
5991 done_pipe(pctx, PIPE_SEQ);
5992 debug_printf_clean("freeing list %p from ctx %p\n",
5993 pctx->list_head, pctx);
5994 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005995 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005996 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005997#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005998 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005999#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006000 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006001 if (pctx != &ctx) {
6002 free(pctx);
6003 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006004 IF_HAS_KEYWORDS(pctx = p2;)
6005 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006006
Denys Vlasenko474cb202018-07-24 13:03:03 +02006007 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006008#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006009 if (pstring)
6010 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006011#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006012 debug_leave();
6013 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006014 }
Eric Andersen25f27032001-04-26 23:22:31 +00006015}
6016
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006017
6018/*** Execution routines ***/
6019
6020/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02006021#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02006022#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006023 expand_string_to_string(str)
6024#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02006025static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006026#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006027static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006028#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006029static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006030
6031/* expand_strvec_to_strvec() takes a list of strings, expands
6032 * all variable references within and returns a pointer to
6033 * a list of expanded strings, possibly with larger number
6034 * of strings. (Think VAR="a b"; echo $VAR).
6035 * This new list is allocated as a single malloc block.
6036 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006037 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006038 * Caller can deallocate entire list by single free(list). */
6039
Denys Vlasenko238081f2010-10-03 14:26:26 +02006040/* A horde of its helpers come first: */
6041
6042static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
6043{
6044 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02006045 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02006046
Denys Vlasenko9e800222010-10-03 14:28:04 +02006047#if ENABLE_HUSH_BRACE_EXPANSION
6048 if (c == '{' || c == '}') {
6049 /* { -> \{, } -> \} */
6050 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02006051 /* And now we want to add { or } and continue:
6052 * o_addchr(o, c);
6053 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006054 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02006055 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02006056 }
6057#endif
6058 o_addchr(o, c);
6059 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02006060 /* \z -> \\\z; \<eol> -> \\<eol> */
6061 o_addchr(o, '\\');
6062 if (len) {
6063 len--;
6064 o_addchr(o, '\\');
6065 o_addchr(o, *str++);
6066 }
6067 }
6068 }
6069}
6070
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006071/* Store given string, finalizing the word and starting new one whenever
6072 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006073 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02006074 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006075 * 1 - ended with IFS char, else 0 (this includes case of empty str).
6076 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006077static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006078{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006079 int last_is_ifs = 0;
6080
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006081 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006082 int word_len;
6083
6084 if (!*str) /* EOL - do not finalize word */
6085 break;
6086 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006087 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006088 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02006089 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006090 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02006091 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006092 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02006093 * Example: "v='\*'; echo b$v" prints "b\*"
6094 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006095 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006096 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006097 /*/ Why can't we do it easier? */
6098 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
6099 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
6100 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006101 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006102 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006103 if (!*str) /* EOL - do not finalize word */
6104 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006105 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006106
6107 /* We know str here points to at least one IFS char */
6108 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02006109 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006110 if (!*str) /* EOL - do not finalize word */
6111 break;
6112
Denys Vlasenko96786362018-04-11 16:02:58 +02006113 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
6114 && strchr(G.ifs, *str) /* the second check would fail */
6115 ) {
6116 /* This is a non-whitespace $IFS char */
6117 /* Skip it and IFS whitespace chars, start new word */
6118 str++;
6119 str += strspn(str, G.ifs_whitespace);
6120 goto new_word;
6121 }
6122
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006123 /* Start new word... but not always! */
6124 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006125 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02006126 /*
6127 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006128 * here nothing precedes the space in $v expansion,
6129 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006130 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02006131 * It's okay if this accesses the byte before first argv[]:
6132 * past call to o_save_ptr() cleared it to zero byte
6133 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006134 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02006135 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006136 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02006137 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006138 o_addchr(output, '\0');
6139 debug_print_list("expand_on_ifs", output, n);
6140 n = o_save_ptr(output, n);
6141 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006142 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006143
Denys Vlasenko168579a2018-07-19 13:45:54 +02006144 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006145 debug_print_list("expand_on_ifs[1]", output, n);
6146 return n;
6147}
6148
6149/* Helper to expand $((...)) and heredoc body. These act as if
6150 * they are in double quotes, with the exception that they are not :).
6151 * Just the rules are similar: "expand only $var and `cmd`"
6152 *
6153 * Returns malloced string.
6154 * As an optimization, we return NULL if expansion is not needed.
6155 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006156static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006157{
6158 char *exp_str;
6159 struct in_str input;
6160 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006161 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006162
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006163 cp = str;
6164 for (;;) {
6165 if (!*cp) return NULL; /* string has no special chars */
6166 if (*cp == '$') break;
6167 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006168#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006169 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006170#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006171 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006172 }
6173
6174 /* We need to expand. Example:
6175 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
6176 */
6177 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006178 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01006179//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006180 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02006181 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02006182 EXP_FLAG_ESC_GLOB_CHARS,
6183 /*unbackslash:*/ 1
6184 );
6185 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006186 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006187 return exp_str;
6188}
6189
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006190static const char *first_special_char_in_vararg(const char *cp)
6191{
6192 for (;;) {
6193 if (!*cp) return NULL; /* string has no special chars */
6194 if (*cp == '$') return cp;
6195 if (*cp == '\\') return cp;
6196 if (*cp == '\'') return cp;
6197 if (*cp == '"') return cp;
6198#if ENABLE_HUSH_TICK
6199 if (*cp == '`') return cp;
6200#endif
6201 /* dquoted "${x:+ARG}" should not glob, therefore
6202 * '*' et al require some non-literal processing: */
6203 if (*cp == '*') return cp;
6204 if (*cp == '?') return cp;
6205 if (*cp == '[') return cp;
6206 cp++;
6207 }
6208}
6209
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006210/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
6211 * These can contain single- and double-quoted strings,
6212 * and treated as if the ARG string is initially unquoted. IOW:
6213 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
6214 * a dquoted string: "${var#"zz"}"), the difference only comes later
6215 * (word splitting and globbing of the ${var...} result).
6216 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006217#if !BASH_PATTERN_SUBST
6218#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
6219 encode_then_expand_vararg(str, handle_squotes)
6220#endif
6221static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6222{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006223#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006224 const int do_unbackslash = 0;
6225#endif
6226 char *exp_str;
6227 struct in_str input;
6228 o_string dest = NULL_O_STRING;
6229
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006230 if (!first_special_char_in_vararg(str)) {
6231 /* string has no special chars */
6232 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006233 }
6234
Denys Vlasenkob762c782018-07-17 14:21:38 +02006235 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006236 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006237 exp_str = NULL;
6238
6239 for (;;) {
6240 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006241
6242 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006243 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6244 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006245
6246 if (!dest.o_expflags) {
6247 if (ch == EOF)
6248 break;
6249 if (handle_squotes && ch == '\'') {
6250 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006251 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006252 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006253 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006254 }
6255 if (ch == EOF) {
6256 syntax_error_unterm_ch('"');
6257 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006258 }
6259 if (ch == '"') {
6260 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6261 continue;
6262 }
6263 if (ch == '\\') {
6264 ch = i_getch(&input);
6265 if (ch == EOF) {
6266//example? error message? syntax_error_unterm_ch('"');
6267 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6268 goto ret;
6269 }
6270 o_addqchr(&dest, ch);
6271 continue;
6272 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006273 if (ch == '$') {
Denys Vlasenkob278d822021-07-26 15:29:13 +02006274 if (parse_dollar_squote(NULL, &dest, &input))
6275 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006276 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6277 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6278 goto ret;
6279 }
6280 continue;
6281 }
6282#if ENABLE_HUSH_TICK
6283 if (ch == '`') {
6284 //unsigned pos = dest->length;
6285 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6286 o_addchr(&dest, 0x80 | '`');
6287 if (!add_till_backquote(&dest, &input,
6288 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6289 )
6290 ) {
6291 goto ret; /* error */
6292 }
6293 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6294 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6295 continue;
6296 }
6297#endif
6298 o_addQchr(&dest, ch);
6299 } /* for (;;) */
6300
6301 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6302 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006303 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6304 do_unbackslash
6305 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006306 ret:
6307 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006308 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006309 return exp_str;
6310}
6311
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006312/* Expanding ARG in ${var+ARG}, ${var-ARG}
6313 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006314static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006315 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006316{
6317 struct in_str input;
6318 o_string dest = NULL_O_STRING;
6319
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006320 if (!first_special_char_in_vararg(str)
6321 && '\0' == str[strcspn(str, G.ifs)]
6322 ) {
6323 /* string has no special chars
6324 * && string has no $IFS chars
6325 */
Denys Vlasenko9e0adb92019-05-15 13:39:19 +02006326 if (dquoted) {
6327 /* Prints 1 (quoted expansion is a "" word, not nothing):
6328 * set -- "${notexist-}"; echo $#
6329 */
6330 output->has_quoted_part = 1;
6331 }
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006332 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006333 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006334
Denys Vlasenko294eb462018-07-20 16:18:59 +02006335 setup_string_in_str(&input, str);
6336
6337 for (;;) {
6338 int ch;
6339
6340 ch = i_getch(&input);
6341 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6342 __func__, ch, ch, dest.o_expflags);
6343
6344 if (!dest.o_expflags) {
6345 if (ch == EOF)
6346 break;
6347 if (!dquoted && strchr(G.ifs, ch)) {
6348 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6349 * do not assume we are at the start of the word (PREFIX above).
6350 */
6351 if (dest.data) {
6352 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006353 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006354 o_addchr(output, '\0');
6355 n = o_save_ptr(output, n); /* create next word */
6356 } else
6357 if (output->length != o_get_last_ptr(output, n)
6358 || output->has_quoted_part
6359 ) {
6360 /* For these cases:
6361 * f() { for i; do echo "|$i|"; done; }; x=x
6362 * f a${x:+ }b # 1st condition
6363 * |a|
6364 * |b|
6365 * f ""${x:+ }b # 2nd condition
6366 * ||
6367 * |b|
6368 */
6369 o_addchr(output, '\0');
6370 n = o_save_ptr(output, n); /* create next word */
6371 }
6372 continue;
6373 }
6374 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006375 if (!add_till_single_quote_dquoted(&dest, &input))
6376 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006377 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6378 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006379 continue;
6380 }
6381 }
6382 if (ch == EOF) {
6383 syntax_error_unterm_ch('"');
6384 goto ret; /* error */
6385 }
6386 if (ch == '"') {
6387 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006388 if (dest.o_expflags) {
6389 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6390 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6391 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006392 continue;
6393 }
6394 if (ch == '\\') {
6395 ch = i_getch(&input);
6396 if (ch == EOF) {
6397//example? error message? syntax_error_unterm_ch('"');
6398 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6399 goto ret;
6400 }
6401 o_addqchr(&dest, ch);
6402 continue;
6403 }
6404 if (ch == '$') {
6405 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6406 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6407 goto ret;
6408 }
6409 continue;
6410 }
6411#if ENABLE_HUSH_TICK
6412 if (ch == '`') {
6413 //unsigned pos = dest->length;
6414 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6415 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6416 if (!add_till_backquote(&dest, &input,
6417 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6418 )
6419 ) {
6420 goto ret; /* error */
6421 }
6422 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6423 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6424 continue;
6425 }
6426#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006427 if (dquoted) {
6428 /* Always glob-protect if in dquotes:
6429 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6430 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6431 */
6432 o_addqchr(&dest, ch);
6433 } else {
6434 /* Glob-protect only if char is quoted:
6435 * x=x; echo ${x:+/bin/c*} - prints many filenames
6436 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6437 */
6438 o_addQchr(&dest, ch);
6439 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006440 } /* for (;;) */
6441
6442 if (dest.data) {
6443 n = expand_vars_to_list(output, n, dest.data);
6444 }
6445 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006446 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006447 return n;
6448}
6449
Denys Vlasenko0b883582016-12-23 16:49:07 +01006450#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006451static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006452{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006453 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006454 arith_t res;
6455 char *exp_str;
6456
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006457 math_state.lookupvar = get_local_var_value;
6458 math_state.setvar = set_local_var_from_halves;
6459 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006460 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006461 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006462 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006463 if (errmsg_p)
6464 *errmsg_p = math_state.errmsg;
6465 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006466 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006467 return res;
6468}
6469#endif
6470
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006471#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006472/* ${var/[/]pattern[/repl]} helpers */
6473static char *strstr_pattern(char *val, const char *pattern, int *size)
6474{
Denys Vlasenko37460f52021-07-27 18:13:11 +02006475 int sz = strcspn(pattern, "*?[\\");
6476 if (pattern[sz] == '\0') {
Denys Vlasenko49cc3ca2021-07-27 17:53:55 +02006477 /* Optimization for trivial patterns.
6478 * Testcase for very slow replace (performs about 22k replaces):
6479 * x=::::::::::::::::::::::
6480 * 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}
6481 * echo "${x//:/|}"
6482 */
Denys Vlasenko37460f52021-07-27 18:13:11 +02006483 *size = sz;
6484 return strstr(val, pattern);
Denys Vlasenko49cc3ca2021-07-27 17:53:55 +02006485 }
6486
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006487 while (1) {
6488 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6489 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6490 if (end) {
6491 *size = end - val;
6492 return val;
6493 }
6494 if (*val == '\0')
6495 return NULL;
6496 /* Optimization: if "*pat" did not match the start of "string",
6497 * we know that "tring", "ring" etc will not match too:
6498 */
6499 if (pattern[0] == '*')
6500 return NULL;
6501 val++;
6502 }
6503}
6504static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6505{
6506 char *result = NULL;
6507 unsigned res_len = 0;
6508 unsigned repl_len = strlen(repl);
6509
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006510 /* Null pattern never matches, including if "var" is empty */
6511 if (!pattern[0])
6512 return result; /* NULL, no replaces happened */
6513
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006514 while (1) {
6515 int size;
6516 char *s = strstr_pattern(val, pattern, &size);
6517 if (!s)
6518 break;
6519
6520 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006521 strcpy(mempcpy(result + res_len, val, s - val), repl);
6522 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006523 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6524
6525 val = s + size;
6526 if (exp_op == '/')
6527 break;
6528 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006529 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006530 result = xrealloc(result, res_len + strlen(val) + 1);
6531 strcpy(result + res_len, val);
6532 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6533 }
6534 debug_printf_varexp("result:'%s'\n", result);
6535 return result;
6536}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006537#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006538
Denys Vlasenko168579a2018-07-19 13:45:54 +02006539static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006540 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006541{
6542 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6543 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6544 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6545 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006546 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006547 } else { /* quoted "$VAR" */
6548 output->has_quoted_part = 1;
6549 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6550 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6551 if (val && val[0])
6552 o_addQstr(output, val);
6553 }
6554 return n;
6555}
6556
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006557/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006558 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006559static NOINLINE int expand_one_var(o_string *output, int n,
6560 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006561{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006562 const char *val;
6563 char *to_be_freed;
6564 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006565 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006566 char exp_op;
6567 char exp_save = exp_save; /* for compiler */
6568 char *exp_saveptr; /* points to expansion operator */
6569 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006570 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006571
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006572 val = NULL;
6573 to_be_freed = NULL;
6574 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006575 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006576 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006577 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006578 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006579 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006580 exp_op = 0;
6581
Denys Vlasenkob762c782018-07-17 14:21:38 +02006582 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006583 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6584 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6585 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006586 ) {
6587 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006588 var++;
6589 exp_op = 'L';
6590 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006591 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006592 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006593 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006594 ) {
6595 /* ${?:0}, ${#[:]%0} etc */
6596 exp_saveptr = var + 1;
6597 } else {
6598 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6599 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6600 }
6601 exp_op = exp_save = *exp_saveptr;
6602 if (exp_op) {
6603 exp_word = exp_saveptr + 1;
6604 if (exp_op == ':') {
6605 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006606//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006607 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006608 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006609 ) {
6610 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6611 exp_op = ':';
6612 exp_word--;
6613 }
6614 }
6615 *exp_saveptr = '\0';
6616 } /* else: it's not an expansion op, but bare ${var} */
6617 }
6618
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006619 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006620 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006621 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006622 int nn = xatoi_positive(var);
6623 if (nn < G.global_argc)
6624 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006625 /* else val remains NULL: $N with too big N */
6626 } else {
6627 switch (var[0]) {
6628 case '$': /* pid */
6629 val = utoa(G.root_pid);
6630 break;
6631 case '!': /* bg pid */
6632 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6633 break;
6634 case '?': /* exitcode */
6635 val = utoa(G.last_exitcode);
6636 break;
6637 case '#': /* argc */
6638 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6639 break;
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006640 case '-': { /* active options */
6641 /* Check set_mode() to see what option chars we support */
6642 char *cp;
6643 val = cp = G.optstring_buf;
6644 if (G.o_opt[OPT_O_ERREXIT])
6645 *cp++ = 'e';
6646 if (G_interactive_fd)
6647 *cp++ = 'i';
6648 if (G_x_mode)
6649 *cp++ = 'x';
6650 /* If G.o_opt[OPT_O_NOEXEC] is true,
6651 * commands read but are not executed,
6652 * so $- can not execute too, 'n' is never seen in $-.
6653 */
Denys Vlasenkof3634582019-06-03 12:21:04 +02006654 if (G.opt_c)
6655 *cp++ = 'c';
Denys Vlasenkod8740b22019-05-19 19:11:21 +02006656 if (G.opt_s)
6657 *cp++ = 's';
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006658 *cp = '\0';
6659 break;
6660 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006661 default:
6662 val = get_local_var_value(var);
6663 }
6664 }
6665
6666 /* Handle any expansions */
6667 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006668 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006669 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006670 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006671 debug_printf_expand("%s\n", val);
6672 } else if (exp_op) {
6673 if (exp_op == '%' || exp_op == '#') {
6674 /* Standard-mandated substring removal ops:
6675 * ${parameter%word} - remove smallest suffix pattern
6676 * ${parameter%%word} - remove largest suffix pattern
6677 * ${parameter#word} - remove smallest prefix pattern
6678 * ${parameter##word} - remove largest prefix pattern
6679 *
6680 * Word is expanded to produce a glob pattern.
6681 * Then var's value is matched to it and matching part removed.
6682 */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006683 /* bash compat: if x is "" and no shrinking of it is possible,
6684 * inner ${...} is not evaluated. Example:
6685 * unset b; : ${a%${b=B}}; echo $b
6686 * assignment b=B only happens if $a is not "".
6687 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006688 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006689 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006690 char *exp_exp_word;
6691 char *loc;
6692 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006693 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006694 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006695 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006696 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006697 if (exp_exp_word)
6698 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006699 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6700 /*
6701 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006702 * G.global_argv and results of utoa and get_local_var_value
6703 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006704 * scan_and_match momentarily stores NULs there.
6705 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006706 t = (char*)val;
6707 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006708 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 +02006709 free(exp_exp_word);
6710 if (loc) { /* match was found */
6711 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006712 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006713 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006714 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006715 }
6716 }
6717 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006718#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006719 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006720 /* It's ${var/[/]pattern[/repl]} thing.
6721 * Note that in encoded form it has TWO parts:
6722 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006723 * and if // is used, it is encoded as \:
6724 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006725 */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006726 /* bash compat: if var is "", both pattern and repl
6727 * are still evaluated, if it is unset, then not:
6728 * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
6729 * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
6730 */
6731 if (val /*&& val[0]*/) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006732 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006733 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006734 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006735 * >az >bz
6736 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6737 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6738 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6739 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006740 * (note that a*z _pattern_ is never globbed!)
6741 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006742 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006743 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006744 if (!pattern)
6745 pattern = xstrdup(exp_word);
6746 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6747 *p++ = SPECIAL_VAR_SYMBOL;
6748 exp_word = p;
6749 p = strchr(p, SPECIAL_VAR_SYMBOL);
6750 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006751 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006752 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6753 /* HACK ALERT. We depend here on the fact that
6754 * G.global_argv and results of utoa and get_local_var_value
6755 * are actually in writable memory:
6756 * replace_pattern momentarily stores NULs there. */
6757 t = (char*)val;
6758 to_be_freed = replace_pattern(t,
6759 pattern,
6760 (repl ? repl : exp_word),
6761 exp_op);
6762 if (to_be_freed) /* at least one replace happened */
6763 val = to_be_freed;
6764 free(pattern);
6765 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006766 } else {
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006767 /* Unset variable always gives nothing */
6768 // a=; echo ${a/*/w} # "w"
6769 // unset a; echo ${a/*/w} # ""
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006770 /* Just skip "replace" part */
6771 *p++ = SPECIAL_VAR_SYMBOL;
6772 p = strchr(p, SPECIAL_VAR_SYMBOL);
6773 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006774 }
6775 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006776#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006777 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006778#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006779 /* It's ${var:N[:M]} bashism.
6780 * Note that in encoded form it has TWO parts:
6781 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6782 */
6783 arith_t beg, len;
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006784 unsigned vallen;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006785 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006786
Denys Vlasenko063847d2010-09-15 13:33:02 +02006787 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6788 if (errmsg)
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006789 goto empty_result;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006790 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6791 *p++ = SPECIAL_VAR_SYMBOL;
6792 exp_word = p;
6793 p = strchr(p, SPECIAL_VAR_SYMBOL);
6794 *p = '\0';
Denys Vlasenkoa7b52d22020-12-23 12:38:03 +01006795 vallen = val ? strlen(val) : 0;
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006796 if (beg < 0) {
6797 /* negative beg counts from the end */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006798 beg = (arith_t)vallen + beg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006799 }
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006800 /* If expansion will be empty, do not even evaluate len */
6801 if (!val || beg < 0 || beg > vallen) {
6802 /* Why > vallen, not >=? bash:
6803 * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
6804 * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
6805 */
6806 goto empty_result;
6807 }
6808 len = expand_and_evaluate_arith(exp_word, &errmsg);
6809 if (errmsg)
6810 goto empty_result;
6811 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006812 debug_printf_varexp("from val:'%s'\n", val);
6813 if (len < 0) {
6814 /* in bash, len=-n means strlen()-n */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006815 len = (arith_t)vallen - beg + len;
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006816 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006817 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006818 }
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006819 if (len <= 0 || !val /*|| beg >= vallen*/) {
6820 empty_result:
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006821 val = NULL;
6822 } else {
6823 /* Paranoia. What if user entered 9999999999999
6824 * which fits in arith_t but not int? */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006825 if (len > INT_MAX)
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006826 len = INT_MAX;
6827 val = to_be_freed = xstrndup(val + beg, len);
6828 }
6829 debug_printf_varexp("val:'%s'\n", val);
6830#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006831 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006832 val = NULL;
6833#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006834 } else { /* one of "-=+?" */
6835 /* Standard-mandated substitution ops:
6836 * ${var?word} - indicate error if unset
6837 * If var is unset, word (or a message indicating it is unset
6838 * if word is null) is written to standard error
6839 * and the shell exits with a non-zero exit status.
6840 * Otherwise, the value of var is substituted.
6841 * ${var-word} - use default value
6842 * If var is unset, word is substituted.
6843 * ${var=word} - assign and use default value
6844 * If var is unset, word is assigned to var.
6845 * In all cases, final value of var is substituted.
6846 * ${var+word} - use alternative value
6847 * If var is unset, null is substituted.
6848 * Otherwise, word is substituted.
6849 *
6850 * Word is subjected to tilde expansion, parameter expansion,
6851 * command substitution, and arithmetic expansion.
6852 * If word is not needed, it is not expanded.
6853 *
6854 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6855 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006856 *
6857 * Word-splitting and single quote behavior:
6858 *
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006859 * $ f() { for i; do echo "|$i|"; done; }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006860 *
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006861 * $ x=; f ${x:?'x y' z}; echo $?
6862 * bash: x: x y z # neither f nor "echo $?" executes
6863 * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006864 * $ x=; f "${x:?'x y' z}"
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006865 * bash: x: x y z # dash prints: dash: x: 'x y' z
Denys Vlasenko294eb462018-07-20 16:18:59 +02006866 *
6867 * $ x=; f ${x:='x y' z}
6868 * |x|
6869 * |y|
6870 * |z|
6871 * $ x=; f "${x:='x y' z}"
6872 * |'x y' z|
6873 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006874 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006875 * |x y|
6876 * |z|
6877 * $ x=x; f "${x:+'x y' z}"
6878 * |'x y' z|
6879 *
6880 * $ x=; f ${x:-'x y' z}
6881 * |x y|
6882 * |z|
6883 * $ x=; f "${x:-'x y' z}"
6884 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006885 */
6886 int use_word = (!val || ((exp_save == ':') && !val[0]));
6887 if (exp_op == '+')
6888 use_word = !use_word;
6889 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6890 (exp_save == ':') ? "true" : "false", use_word);
6891 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006892 if (exp_op == '+' || exp_op == '-') {
6893 /* ${var+word} - use alternative value */
6894 /* ${var-word} - use default value */
6895 n = encode_then_append_var_plusminus(output, n, exp_word,
6896 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006897 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006898 val = NULL;
6899 } else {
6900 /* ${var?word} - indicate error if unset */
6901 /* ${var=word} - assign and use default value */
6902 to_be_freed = encode_then_expand_vararg(exp_word,
6903 /*handle_squotes:*/ !(arg0 & 0x80),
6904 /*unbackslash:*/ 0
6905 );
6906 if (to_be_freed)
6907 exp_word = to_be_freed;
6908 if (exp_op == '?') {
6909 /* mimic bash message */
6910 msg_and_die_if_script("%s: %s",
6911 var,
6912 exp_word[0]
6913 ? exp_word
6914 : "parameter null or not set"
6915 /* ash has more specific messages, a-la: */
6916 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6917 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006918//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006919//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006920// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6921// bash: x: x y z
6922// $
6923// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006924 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006925 val = exp_word;
6926 }
6927 if (exp_op == '=') {
6928 /* ${var=[word]} or ${var:=[word]} */
6929 if (isdigit(var[0]) || var[0] == '#') {
6930 /* mimic bash message */
6931 msg_and_die_if_script("$%s: cannot assign in this way", var);
6932 val = NULL;
6933 } else {
6934 char *new_var = xasprintf("%s=%s", var, val);
6935 set_local_var(new_var, /*flag:*/ 0);
6936 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006937 }
6938 }
6939 }
6940 } /* one of "-=+?" */
6941
6942 *exp_saveptr = exp_save;
6943 } /* if (exp_op) */
6944
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006945 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006946 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006947
Denys Vlasenko168579a2018-07-19 13:45:54 +02006948 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006949
6950 free(to_be_freed);
6951 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006952}
6953
6954/* Expand all variable references in given string, adding words to list[]
6955 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6956 * to be filled). This routine is extremely tricky: has to deal with
6957 * variables/parameters with whitespace, $* and $@, and constructs like
6958 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006959static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006960{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006961 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006962 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006963 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006964 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006965 char *p;
6966
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006967 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6968 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006969 debug_print_list("expand_vars_to_list[0]", output, n);
6970
6971 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6972 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006973#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006974 char arith_buf[sizeof(arith_t)*3 + 2];
6975#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006976
Denys Vlasenko168579a2018-07-19 13:45:54 +02006977 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006978 o_addchr(output, '\0');
6979 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006980 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006981 }
6982
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006983 o_addblock(output, arg, p - arg);
6984 debug_print_list("expand_vars_to_list[1]", output, n);
6985 arg = ++p;
6986 p = strchr(p, SPECIAL_VAR_SYMBOL);
6987
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006988 /* Fetch special var name (if it is indeed one of them)
6989 * and quote bit, force the bit on if singleword expansion -
6990 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006991 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006992
6993 /* Is this variable quoted and thus expansion can't be null?
6994 * "$@" is special. Even if quoted, it can still
6995 * expand to nothing (not even an empty string),
6996 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006997 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006998 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006999
7000 switch (first_ch & 0x7f) {
7001 /* Highest bit in first_ch indicates that var is double-quoted */
7002 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02007003 case '@': {
7004 int i;
7005 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007006 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02007007 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007008 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007009 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007010 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02007011 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007012 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
7013 if (G.global_argv[i++][0] && G.global_argv[i]) {
7014 /* this argv[] is not empty and not last:
7015 * put terminating NUL, start new word */
7016 o_addchr(output, '\0');
7017 debug_print_list("expand_vars_to_list[2]", output, n);
7018 n = o_save_ptr(output, n);
7019 debug_print_list("expand_vars_to_list[3]", output, n);
7020 }
7021 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007022 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007023 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007024 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02007025 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007026 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007027 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007028 while (1) {
7029 o_addQstr(output, G.global_argv[i]);
7030 if (++i >= G.global_argc)
7031 break;
7032 o_addchr(output, '\0');
7033 debug_print_list("expand_vars_to_list[4]", output, n);
7034 n = o_save_ptr(output, n);
7035 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007036 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007037 while (1) {
7038 o_addQstr(output, G.global_argv[i]);
7039 if (!G.global_argv[++i])
7040 break;
7041 if (G.ifs[0])
7042 o_addchr(output, G.ifs[0]);
7043 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02007044 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007045 }
7046 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02007047 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007048 case SPECIAL_VAR_SYMBOL: {
7049 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007050 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02007051 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007052 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007053 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007054 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007055 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01007056 case SPECIAL_VAR_QUOTED_SVS:
7057 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007058 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02007059 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01007060 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01007061 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007062#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007063 case '`': {
7064 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02007065 o_string subst_result = NULL_O_STRING;
7066
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007067 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007068 arg++;
7069 /* Can't just stuff it into output o_string,
7070 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02007071 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007072 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
7073 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02007074 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007075 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02007076 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02007077 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007078 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02007079 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007080#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01007081#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007082 case '+': {
7083 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007084 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007085
7086 arg++; /* skip '+' */
7087 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
7088 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02007089 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02007090 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
7091 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01007092 if (res < 0
7093 && first_ch == (char)('+'|0x80)
7094 /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
7095 ) {
7096 /* Quoted negative ariths, like filename[0"$((-9))"],
7097 * should not be interpreted as glob ranges.
7098 * Convert leading '-' to '\-':
7099 */
7100 o_grow_by(output, 1);
7101 output->data[output->length++] = '\\';
7102 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007103 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007104 break;
7105 }
7106#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02007107 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007108 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02007109 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007110 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007111 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
7112
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007113 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
7114 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007115 if (*p != SPECIAL_VAR_SYMBOL)
7116 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007117 arg = ++p;
7118 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
7119
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02007120 if (*arg) {
7121 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02007122 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02007123 o_addchr(output, '\0');
7124 n = o_save_ptr(output, n);
7125 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007126 debug_print_list("expand_vars_to_list[a]", output, n);
7127 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02007128 * if needed (much earlier), do not use o_addQstr here!
7129 */
7130 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007131 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02007132 } else
7133 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02007134 && !(cant_be_null & 0x80) /* and all vars were not quoted */
7135 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007136 ) {
7137 n--;
7138 /* allow to reuse list[n] later without re-growth */
7139 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007140 }
7141
7142 return n;
7143}
7144
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007145static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007146{
7147 int n;
7148 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007149 o_string output = NULL_O_STRING;
7150
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007151 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007152
7153 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02007154 for (;;) {
7155 /* go to next list[n] */
7156 output.ended_in_ifs = 0;
7157 n = o_save_ptr(&output, n);
7158
7159 if (!*argv)
7160 break;
7161
7162 /* expand argv[i] */
7163 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02007164 /* if (!output->has_empty_slot) -- need this?? */
7165 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007166 }
7167 debug_print_list("expand_variables", &output, n);
7168
7169 /* output.data (malloced in one block) gets returned in "list" */
7170 list = o_finalize_list(&output, n);
7171 debug_print_strings("expand_variables[1]", list);
7172 return list;
7173}
7174
7175static char **expand_strvec_to_strvec(char **argv)
7176{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007177 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007178}
7179
Denys Vlasenkod2241f52020-10-31 03:34:07 +01007180#if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007181static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
7182{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007183 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007184}
7185#endif
7186
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007187/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007188 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007189 *
7190 * NB: should NOT do globbing!
7191 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
7192 */
Denys Vlasenko34179952018-04-11 13:47:59 +02007193static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007194{
Denys Vlasenko637982f2017-07-06 01:52:23 +02007195#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007196 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02007197 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007198#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007199 char *argv[2], **list;
7200
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007201 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007202 /* This is generally an optimization, but it also
7203 * handles "", which otherwise trips over !list[0] check below.
7204 * (is this ever happens that we actually get str="" here?)
7205 */
7206 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
7207 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007208 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007209 return xstrdup(str);
7210 }
7211
7212 argv[0] = (char*)str;
7213 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02007214 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02007215 if (!list[0]) {
7216 /* Example where it happens:
7217 * x=; echo ${x:-"$@"}
7218 */
7219 ((char*)list)[0] = '\0';
7220 } else {
7221 if (HUSH_DEBUG)
7222 if (list[1])
James Byrne69374872019-07-02 11:35:03 +02007223 bb_simple_error_msg_and_die("BUG in varexp2");
Denys Vlasenko2e711012018-07-18 16:02:25 +02007224 /* actually, just move string 2*sizeof(char*) bytes back */
7225 overlapping_strcpy((char*)list, list[0]);
7226 if (do_unbackslash)
7227 unbackslash((char*)list);
7228 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007229 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007230 return (char*)list;
7231}
7232
Denys Vlasenkoabf75562018-04-02 17:25:18 +02007233#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007234static char* expand_strvec_to_string(char **argv)
7235{
7236 char **list;
7237
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007238 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007239 /* Convert all NULs to spaces */
7240 if (list[0]) {
7241 int n = 1;
7242 while (list[n]) {
7243 if (HUSH_DEBUG)
7244 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
7245 bb_error_msg_and_die("BUG in varexp3");
7246 /* bash uses ' ' regardless of $IFS contents */
7247 list[n][-1] = ' ';
7248 n++;
7249 }
7250 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02007251 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007252 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
7253 return (char*)list;
7254}
Denys Vlasenko1f191122018-01-11 13:17:30 +01007255#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007256
7257static char **expand_assignments(char **argv, int count)
7258{
7259 int i;
7260 char **p;
7261
7262 G.expanded_assignments = p = NULL;
7263 /* Expand assignments into one string each */
7264 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02007265 p = add_string_to_strings(p,
7266 expand_string_to_string(argv[i],
7267 EXP_FLAG_ESC_GLOB_CHARS,
7268 /*unbackslash:*/ 1
7269 )
7270 );
7271 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007272 }
7273 G.expanded_assignments = NULL;
7274 return p;
7275}
7276
7277
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007278static void switch_off_special_sigs(unsigned mask)
7279{
7280 unsigned sig = 0;
7281 while ((mask >>= 1) != 0) {
7282 sig++;
7283 if (!(mask & 1))
7284 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007285#if ENABLE_HUSH_TRAP
7286 if (G_traps) {
7287 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007288 /* trap is '', has to remain SIG_IGN */
7289 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007290 free(G_traps[sig]);
7291 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007292 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007293#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007294 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007295 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007296 }
7297}
7298
Denys Vlasenkob347df92011-08-09 22:49:15 +02007299#if BB_MMU
7300/* never called */
7301void re_execute_shell(char ***to_free, const char *s,
7302 char *g_argv0, char **g_argv,
7303 char **builtin_argv) NORETURN;
7304
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007305static void reset_traps_to_defaults(void)
7306{
7307 /* This function is always called in a child shell
7308 * after fork (not vfork, NOMMU doesn't use this function).
7309 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007310 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007311 unsigned mask;
7312
7313 /* Child shells are not interactive.
7314 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7315 * Testcase: (while :; do :; done) + ^Z should background.
7316 * Same goes for SIGTERM, SIGHUP, SIGINT.
7317 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007318 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007319 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007320 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007321
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007322 /* Switch off special sigs */
7323 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007324# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007325 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007326# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007327 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007328 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7329 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007330
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007331# if ENABLE_HUSH_TRAP
7332 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007333 return;
7334
7335 /* Reset all sigs to default except ones with empty traps */
7336 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007337 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007338 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007339 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007340 continue; /* empty trap: has to remain SIG_IGN */
7341 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007342 free(G_traps[sig]);
7343 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007344 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007345 if (sig == 0)
7346 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007347 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007348 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007349# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007350}
7351
7352#else /* !BB_MMU */
7353
7354static void re_execute_shell(char ***to_free, const char *s,
7355 char *g_argv0, char **g_argv,
7356 char **builtin_argv) NORETURN;
7357static void re_execute_shell(char ***to_free, const char *s,
7358 char *g_argv0, char **g_argv,
7359 char **builtin_argv)
7360{
7361# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7362 /* delims + 2 * (number of bytes in printed hex numbers) */
7363 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7364 char *heredoc_argv[4];
7365 struct variable *cur;
7366# if ENABLE_HUSH_FUNCTIONS
7367 struct function *funcp;
7368# endif
7369 char **argv, **pp;
7370 unsigned cnt;
7371 unsigned long long empty_trap_mask;
7372
7373 if (!g_argv0) { /* heredoc */
7374 argv = heredoc_argv;
7375 argv[0] = (char *) G.argv0_for_re_execing;
7376 argv[1] = (char *) "-<";
7377 argv[2] = (char *) s;
7378 argv[3] = NULL;
7379 pp = &argv[3]; /* used as pointer to empty environment */
7380 goto do_exec;
7381 }
7382
7383 cnt = 0;
7384 pp = builtin_argv;
7385 if (pp) while (*pp++)
7386 cnt++;
7387
7388 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007389 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007390 int sig;
7391 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007392 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007393 empty_trap_mask |= 1LL << sig;
7394 }
7395 }
7396
7397 sprintf(param_buf, NOMMU_HACK_FMT
7398 , (unsigned) G.root_pid
7399 , (unsigned) G.root_ppid
7400 , (unsigned) G.last_bg_pid
7401 , (unsigned) G.last_exitcode
7402 , cnt
7403 , empty_trap_mask
7404 IF_HUSH_LOOPS(, G.depth_of_loop)
7405 );
7406# undef NOMMU_HACK_FMT
7407 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7408 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7409 */
7410 cnt += 6;
7411 for (cur = G.top_var; cur; cur = cur->next) {
7412 if (!cur->flg_export || cur->flg_read_only)
7413 cnt += 2;
7414 }
7415# if ENABLE_HUSH_FUNCTIONS
7416 for (funcp = G.top_func; funcp; funcp = funcp->next)
7417 cnt += 3;
7418# endif
7419 pp = g_argv;
7420 while (*pp++)
7421 cnt++;
7422 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7423 *pp++ = (char *) G.argv0_for_re_execing;
7424 *pp++ = param_buf;
7425 for (cur = G.top_var; cur; cur = cur->next) {
7426 if (strcmp(cur->varstr, hush_version_str) == 0)
7427 continue;
7428 if (cur->flg_read_only) {
7429 *pp++ = (char *) "-R";
7430 *pp++ = cur->varstr;
7431 } else if (!cur->flg_export) {
7432 *pp++ = (char *) "-V";
7433 *pp++ = cur->varstr;
7434 }
7435 }
7436# if ENABLE_HUSH_FUNCTIONS
7437 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7438 *pp++ = (char *) "-F";
7439 *pp++ = funcp->name;
7440 *pp++ = funcp->body_as_string;
7441 }
7442# endif
7443 /* We can pass activated traps here. Say, -Tnn:trap_string
7444 *
7445 * However, POSIX says that subshells reset signals with traps
7446 * to SIG_DFL.
7447 * I tested bash-3.2 and it not only does that with true subshells
7448 * of the form ( list ), but with any forked children shells.
7449 * I set trap "echo W" WINCH; and then tried:
7450 *
7451 * { echo 1; sleep 20; echo 2; } &
7452 * while true; do echo 1; sleep 20; echo 2; break; done &
7453 * true | { echo 1; sleep 20; echo 2; } | cat
7454 *
7455 * In all these cases sending SIGWINCH to the child shell
7456 * did not run the trap. If I add trap "echo V" WINCH;
7457 * _inside_ group (just before echo 1), it works.
7458 *
7459 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007460 */
7461 *pp++ = (char *) "-c";
7462 *pp++ = (char *) s;
7463 if (builtin_argv) {
7464 while (*++builtin_argv)
7465 *pp++ = *builtin_argv;
7466 *pp++ = (char *) "";
7467 }
7468 *pp++ = g_argv0;
7469 while (*g_argv)
7470 *pp++ = *g_argv++;
7471 /* *pp = NULL; - is already there */
7472 pp = environ;
7473
7474 do_exec:
7475 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007476 /* Don't propagate SIG_IGN to the child */
7477 if (SPECIAL_JOBSTOP_SIGS != 0)
7478 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007479 execve(bb_busybox_exec_path, argv, pp);
7480 /* Fallback. Useful for init=/bin/hush usage etc */
7481 if (argv[0][0] == '/')
7482 execve(argv[0], argv, pp);
7483 xfunc_error_retval = 127;
James Byrne69374872019-07-02 11:35:03 +02007484 bb_simple_error_msg_and_die("can't re-execute the shell");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007485}
7486#endif /* !BB_MMU */
7487
7488
7489static int run_and_free_list(struct pipe *pi);
7490
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007491/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007492 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7493 * end_trigger controls how often we stop parsing
7494 * NUL: parse all, execute, return
7495 * ';': parse till ';' or newline, execute, repeat till EOF
7496 */
7497static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007498{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007499 /* Why we need empty flag?
7500 * An obscure corner case "false; ``; echo $?":
7501 * empty command in `` should still set $? to 0.
7502 * But we can't just set $? to 0 at the start,
7503 * this breaks "false; echo `echo $?`" case.
7504 */
7505 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007506 while (1) {
7507 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007508
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007509#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007510 if (end_trigger == ';') {
7511 G.promptmode = 0; /* PS1 */
7512 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7513 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007514#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007515 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007516 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7517 /* If we are in "big" script
7518 * (not in `cmd` or something similar)...
7519 */
7520 if (pipe_list == ERR_PTR && end_trigger == ';') {
7521 /* Discard cached input (rest of line) */
7522 int ch = inp->last_char;
7523 while (ch != EOF && ch != '\n') {
7524 //bb_error_msg("Discarded:'%c'", ch);
7525 ch = i_getch(inp);
7526 }
7527 /* Force prompt */
7528 inp->p = NULL;
7529 /* This stream isn't empty */
7530 empty = 0;
7531 continue;
7532 }
7533 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007534 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007535 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007536 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007537 debug_print_tree(pipe_list, 0);
7538 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7539 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007540 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007541 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007542 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007543 }
Eric Andersen25f27032001-04-26 23:22:31 +00007544}
7545
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007546static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007547{
7548 struct in_str input;
Denys Vlasenko574b9c42021-09-07 21:44:44 +02007549 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007550
Eric Andersen25f27032001-04-26 23:22:31 +00007551 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007552 parse_and_run_stream(&input, '\0');
Denys Vlasenko574b9c42021-09-07 21:44:44 +02007553 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007554}
7555
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007556static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007557{
Eric Andersen25f27032001-04-26 23:22:31 +00007558 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007559 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007560
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007561 IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007562 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007563 parse_and_run_stream(&input, ';');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007564 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007565}
7566
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007567#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007568static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007569{
7570 pid_t pid;
7571 int channel[2];
7572# if !BB_MMU
7573 char **to_free = NULL;
7574# endif
7575
7576 xpipe(channel);
7577 pid = BB_MMU ? xfork() : xvfork();
7578 if (pid == 0) { /* child */
7579 disable_restore_tty_pgrp_on_exit();
7580 /* Process substitution is not considered to be usual
7581 * 'command execution'.
7582 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7583 */
7584 bb_signals(0
7585 + (1 << SIGTSTP)
7586 + (1 << SIGTTIN)
7587 + (1 << SIGTTOU)
7588 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007589 close(channel[0]); /* NB: close _first_, then move fd! */
7590 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007591# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007592 /* Awful hack for `trap` or $(trap).
7593 *
7594 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7595 * contains an example where "trap" is executed in a subshell:
7596 *
7597 * save_traps=$(trap)
7598 * ...
7599 * eval "$save_traps"
7600 *
7601 * Standard does not say that "trap" in subshell shall print
7602 * parent shell's traps. It only says that its output
7603 * must have suitable form, but then, in the above example
7604 * (which is not supposed to be normative), it implies that.
7605 *
7606 * bash (and probably other shell) does implement it
7607 * (traps are reset to defaults, but "trap" still shows them),
7608 * but as a result, "trap" logic is hopelessly messed up:
7609 *
7610 * # trap
7611 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7612 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7613 * # true | trap <--- trap is in subshell - no output (ditto)
7614 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7615 * trap -- 'echo Ho' SIGWINCH
7616 * # echo `(trap)` <--- in subshell in subshell - output
7617 * trap -- 'echo Ho' SIGWINCH
7618 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7619 * trap -- 'echo Ho' SIGWINCH
7620 *
7621 * The rules when to forget and when to not forget traps
7622 * get really complex and nonsensical.
7623 *
7624 * Our solution: ONLY bare $(trap) or `trap` is special.
7625 */
7626 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007627 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007628 && skip_whitespace(s + 4)[0] == '\0'
7629 ) {
7630 static const char *const argv[] = { NULL, NULL };
7631 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007632 fflush_all(); /* important */
7633 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007634 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007635# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007636# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007637 /* Prevent it from trying to handle ctrl-z etc */
7638 IF_HUSH_JOB(G.run_list_level = 1;)
7639 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007640 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007641 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007642 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007643 parse_and_run_string(s);
7644 _exit(G.last_exitcode);
7645# else
7646 /* We re-execute after vfork on NOMMU. This makes this script safe:
7647 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7648 * huge=`cat BIG` # was blocking here forever
7649 * echo OK
7650 */
7651 re_execute_shell(&to_free,
7652 s,
7653 G.global_argv[0],
7654 G.global_argv + 1,
7655 NULL);
7656# endif
7657 }
7658
7659 /* parent */
7660 *pid_p = pid;
7661# if ENABLE_HUSH_FAST
7662 G.count_SIGCHLD++;
7663//bb_error_msg("[%d] fork in generate_stream_from_string:"
7664// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7665// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7666# endif
7667 enable_restore_tty_pgrp_on_exit();
7668# if !BB_MMU
7669 free(to_free);
7670# endif
7671 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007672 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007673}
7674
7675/* Return code is exit status of the process that is run. */
7676static int process_command_subs(o_string *dest, const char *s)
7677{
7678 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007679 pid_t pid;
7680 int status, ch, eol_cnt;
7681
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007682 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007683
7684 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007685 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007686 while ((ch = getc(fp)) != EOF) {
7687 if (ch == '\0')
7688 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007689 if (ch == '\n') {
7690 eol_cnt++;
7691 continue;
7692 }
7693 while (eol_cnt) {
7694 o_addchr(dest, '\n');
7695 eol_cnt--;
7696 }
7697 o_addQchr(dest, ch);
7698 }
7699
7700 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007701 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007702 /* We need to extract exitcode. Test case
7703 * "true; echo `sleep 1; false` $?"
7704 * should print 1 */
7705 safe_waitpid(pid, &status, 0);
7706 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7707 return WEXITSTATUS(status);
7708}
7709#endif /* ENABLE_HUSH_TICK */
7710
7711
7712static void setup_heredoc(struct redir_struct *redir)
7713{
7714 struct fd_pair pair;
7715 pid_t pid;
7716 int len, written;
7717 /* the _body_ of heredoc (misleading field name) */
7718 const char *heredoc = redir->rd_filename;
7719 char *expanded;
7720#if !BB_MMU
7721 char **to_free;
7722#endif
7723
7724 expanded = NULL;
7725 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007726 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007727 if (expanded)
7728 heredoc = expanded;
7729 }
7730 len = strlen(heredoc);
7731
7732 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7733 xpiped_pair(pair);
7734 xmove_fd(pair.rd, redir->rd_fd);
7735
7736 /* Try writing without forking. Newer kernels have
7737 * dynamically growing pipes. Must use non-blocking write! */
7738 ndelay_on(pair.wr);
7739 while (1) {
7740 written = write(pair.wr, heredoc, len);
7741 if (written <= 0)
7742 break;
7743 len -= written;
7744 if (len == 0) {
7745 close(pair.wr);
7746 free(expanded);
7747 return;
7748 }
7749 heredoc += written;
7750 }
7751 ndelay_off(pair.wr);
7752
7753 /* Okay, pipe buffer was not big enough */
7754 /* Note: we must not create a stray child (bastard? :)
7755 * for the unsuspecting parent process. Child creates a grandchild
7756 * and exits before parent execs the process which consumes heredoc
7757 * (that exec happens after we return from this function) */
7758#if !BB_MMU
7759 to_free = NULL;
7760#endif
7761 pid = xvfork();
7762 if (pid == 0) {
7763 /* child */
7764 disable_restore_tty_pgrp_on_exit();
7765 pid = BB_MMU ? xfork() : xvfork();
7766 if (pid != 0)
7767 _exit(0);
7768 /* grandchild */
7769 close(redir->rd_fd); /* read side of the pipe */
7770#if BB_MMU
7771 full_write(pair.wr, heredoc, len); /* may loop or block */
7772 _exit(0);
7773#else
7774 /* Delegate blocking writes to another process */
7775 xmove_fd(pair.wr, STDOUT_FILENO);
7776 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7777#endif
7778 }
7779 /* parent */
7780#if ENABLE_HUSH_FAST
7781 G.count_SIGCHLD++;
7782//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7783#endif
7784 enable_restore_tty_pgrp_on_exit();
7785#if !BB_MMU
7786 free(to_free);
7787#endif
7788 close(pair.wr);
7789 free(expanded);
7790 wait(NULL); /* wait till child has died */
7791}
7792
Denys Vlasenko2db74612017-07-07 22:07:28 +02007793struct squirrel {
7794 int orig_fd;
7795 int moved_to;
7796 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7797 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7798};
7799
Denys Vlasenko621fc502017-07-24 12:42:17 +02007800static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7801{
7802 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7803 sq[i].orig_fd = orig;
7804 sq[i].moved_to = moved;
7805 sq[i+1].orig_fd = -1; /* end marker */
7806 return sq;
7807}
7808
Denys Vlasenko2db74612017-07-07 22:07:28 +02007809static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7810{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007811 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007812 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007813
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007814 i = 0;
7815 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007816 /* If we collide with an already moved fd... */
7817 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007818 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007819 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7820 if (sq[i].moved_to < 0) /* what? */
7821 xfunc_die();
7822 return sq;
7823 }
7824 if (fd == sq[i].orig_fd) {
7825 /* Example: echo Hello >/dev/null 1>&2 */
7826 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7827 return sq;
7828 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007829 }
7830
Denys Vlasenko2db74612017-07-07 22:07:28 +02007831 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007832 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007833 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7834 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007835 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007836 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007837}
7838
Denys Vlasenko657e9002017-07-30 23:34:04 +02007839static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7840{
7841 int i;
7842
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007843 i = 0;
7844 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007845 /* If we collide with an already moved fd... */
7846 if (fd == sq[i].orig_fd) {
7847 /* Examples:
7848 * "echo 3>FILE 3>&- 3>FILE"
7849 * "echo 3>&- 3>FILE"
7850 * No need for last redirect to insert
7851 * another "need to close 3" indicator.
7852 */
7853 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7854 return sq;
7855 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007856 }
7857
7858 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7859 return append_squirrel(sq, i, fd, -1);
7860}
7861
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007862/* fd: redirect wants this fd to be used (e.g. 3>file).
7863 * Move all conflicting internally used fds,
7864 * and remember them so that we can restore them later.
7865 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007866static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007867{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007868 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7869 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007870
7871#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko21806562019-11-01 14:16:07 +01007872 if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
7873 && fd == G_interactive_fd
7874 ) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007875 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007876 G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
7877 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 +02007878 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007879 }
7880#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007881 /* Are we called from setup_redirects(squirrel==NULL)
7882 * in redirect in a [v]forked child?
7883 */
7884 if (sqp == NULL) {
7885 /* No need to move script fds.
7886 * For NOMMU case, it's actively wrong: we'd change ->fd
7887 * fields in memory for the parent, but parent's fds
Denys Vlasenko21806562019-11-01 14:16:07 +01007888 * aren't moved, it would use wrong fd!
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007889 * Reproducer: "cmd 3>FILE" in script.
7890 * If we would call move_HFILEs_on_redirect(), child would:
7891 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7892 * close(3) = 0
7893 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7894 */
7895 //bb_error_msg("sqp == NULL: [v]forked child");
7896 return 0;
7897 }
7898
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007899 /* If this one of script's fds? */
7900 if (move_HFILEs_on_redirect(fd, avoid_fd))
7901 return 1; /* yes. "we closed fd" (actually moved it) */
7902
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007903 /* Are we called for "exec 3>FILE"? Came through
7904 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7905 * This case used to fail for this script:
7906 * exec 3>FILE
7907 * echo Ok
7908 * ...100000 more lines...
7909 * echo Ok
7910 * as follows:
7911 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7912 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7913 * dup2(4, 3) = 3
7914 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7915 * close(4) = 0
7916 * write(1, "Ok\n", 3) = 3
7917 * ... = 3
7918 * write(1, "Ok\n", 3) = 3
7919 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7920 * ^^^^^^^^ oops, wrong fd!!!
7921 * With this case separate from sqp == NULL and *after* move_HFILEs,
7922 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007923 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007924 if (sqp == ERR_PTR) {
7925 /* Don't preserve redirected fds: exec is _meant_ to change these */
7926 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007927 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007928 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007929
Denys Vlasenko2db74612017-07-07 22:07:28 +02007930 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7931 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7932 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007933}
7934
Denys Vlasenko2db74612017-07-07 22:07:28 +02007935static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007936{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007937 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007938 int i;
7939 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007940 if (sq[i].moved_to >= 0) {
7941 /* We simply die on error */
7942 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7943 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7944 } else {
7945 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7946 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7947 close(sq[i].orig_fd);
7948 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007949 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007950 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007951 }
Denys Vlasenko21806562019-11-01 14:16:07 +01007952 if (G.HFILE_stdin
Denys Vlasenko1237d622020-12-25 19:01:49 +01007953 && G.HFILE_stdin->fd > STDIN_FILENO
7954 /* we compare > STDIN, not == STDIN, since hfgetc()
7955 * closes fd and sets ->fd to -1 if EOF is reached.
7956 * Testcase: echo 'pwd' | hush
7957 */
Denys Vlasenko21806562019-11-01 14:16:07 +01007958 ) {
7959 /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
7960 * Redirect moves ->fd to e.g. 10,
7961 * and it is not restored above (we do not restore script fds
7962 * after redirects, we just use new, "moved" fds).
7963 * However for stdin, get_user_input() -> read_line_input(),
7964 * and read builtin, depend on fd == STDIN_FILENO.
7965 */
7966 debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
7967 xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
7968 G.HFILE_stdin->fd = STDIN_FILENO;
7969 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007970
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007971 /* If moved, G_interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007972}
7973
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007974#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007975static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007976{
7977 if (G_interactive_fd)
7978 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007979 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007980}
7981#endif
7982
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007983static int internally_opened_fd(int fd, struct squirrel *sq)
7984{
7985 int i;
7986
7987#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007988 if (fd == G_interactive_fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007989 return 1;
7990#endif
7991 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007992 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007993 return 1;
7994
7995 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7996 if (fd == sq[i].moved_to)
7997 return 1;
7998 }
7999 return 0;
8000}
8001
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008002/* squirrel != NULL means we squirrel away copies of stdin, stdout,
8003 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008004static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008005{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008006 struct redir_struct *redir;
8007
8008 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02008009 int newfd;
8010 int closed;
8011
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008012 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02008013 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02008014 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008015 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
8016 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008017 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008018 redir->rd_filename);
8019 setup_heredoc(redir);
8020 continue;
8021 }
8022
8023 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02008024 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008025 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02008026 int mode;
8027
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008028 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008029 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02008030 * "cmd >" (no filename)
8031 * "cmd > <file" (2nd redirect starts too early)
8032 */
Denys Vlasenko39701202017-08-02 19:44:05 +02008033 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008034 continue;
8035 }
8036 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02008037 p = expand_string_to_string(redir->rd_filename,
8038 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02008039 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008040 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02008041 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02008042 /* Error message from open_or_warn can be lost
8043 * if stderr has been redirected, but bash
8044 * and ash both lose it as well
8045 * (though zsh doesn't!)
8046 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008047 return 1;
8048 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02008049 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02008050 /* open() gave us precisely the fd we wanted.
8051 * This means that this fd was not busy
8052 * (not opened to anywhere).
8053 * Remember to close it on restore:
8054 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02008055 *sqp = add_squirrel_closed(*sqp, newfd);
8056 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02008057 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008058 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02008059 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
8060 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008061 }
8062
Denys Vlasenko657e9002017-07-30 23:34:04 +02008063 if (newfd == redir->rd_fd)
8064 continue;
8065
8066 /* if "N>FILE": move newfd to redir->rd_fd */
8067 /* if "N>&M": dup newfd to redir->rd_fd */
8068 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
8069
8070 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
8071 if (newfd == REDIRFD_CLOSE) {
8072 /* "N>&-" means "close me" */
8073 if (!closed) {
8074 /* ^^^ optimization: saving may already
8075 * have closed it. If not... */
8076 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008077 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02008078 /* Sometimes we do another close on restore, getting EBADF.
8079 * Consider "echo 3>FILE 3>&-"
8080 * first redirect remembers "need to close 3",
8081 * and second redirect closes 3! Restore code then closes 3 again.
8082 */
8083 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02008084 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008085 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02008086 //errno = EBADF;
8087 //bb_perror_msg_and_die("can't duplicate file descriptor");
8088 newfd = -1; /* same effect as code above */
8089 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02008090 xdup2(newfd, redir->rd_fd);
8091 if (redir->rd_dup == REDIRFD_TO_FILE)
8092 /* "rd_fd > FILE" */
8093 close(newfd);
8094 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008095 }
8096 }
8097 return 0;
8098}
8099
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008100static char *find_in_path(const char *arg)
8101{
8102 char *ret = NULL;
8103 const char *PATH = get_local_var_value("PATH");
8104
8105 if (!PATH)
8106 return NULL;
8107
8108 while (1) {
8109 const char *end = strchrnul(PATH, ':');
8110 int sz = end - PATH; /* must be int! */
8111
8112 free(ret);
8113 if (sz != 0) {
8114 ret = xasprintf("%.*s/%s", sz, PATH, arg);
8115 } else {
8116 /* We have xxx::yyyy in $PATH,
8117 * it means "use current dir" */
8118 ret = xstrdup(arg);
8119 }
8120 if (access(ret, F_OK) == 0)
8121 break;
8122
8123 if (*end == '\0') {
8124 free(ret);
8125 return NULL;
8126 }
8127 PATH = end + 1;
8128 }
8129
8130 return ret;
8131}
8132
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008133static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008134 const struct built_in_command *x,
8135 const struct built_in_command *end)
8136{
8137 while (x != end) {
8138 if (strcmp(name, x->b_cmd) != 0) {
8139 x++;
8140 continue;
8141 }
8142 debug_printf_exec("found builtin '%s'\n", name);
8143 return x;
8144 }
8145 return NULL;
8146}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008147static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008148{
8149 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
8150}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008151static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008152{
8153 const struct built_in_command *x = find_builtin1(name);
8154 if (x)
8155 return x;
8156 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
8157}
8158
Denys Vlasenkod5314e72020-06-24 09:31:30 +02008159#if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
Ron Yorston9e2a5662020-01-21 16:01:58 +00008160static const char * FAST_FUNC get_builtin_name(int i)
8161{
8162 if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
8163 return bltins1[i].b_cmd;
8164 }
8165 i -= ARRAY_SIZE(bltins1);
8166 if (i < ARRAY_SIZE(bltins2)) {
8167 return bltins2[i].b_cmd;
8168 }
8169 return NULL;
8170}
8171#endif
8172
Denys Vlasenko99496dc2018-06-26 15:36:58 +02008173static void remove_nested_vars(void)
8174{
8175 struct variable *cur;
8176 struct variable **cur_pp;
8177
8178 cur_pp = &G.top_var;
8179 while ((cur = *cur_pp) != NULL) {
8180 if (cur->var_nest_level <= G.var_nest_level) {
8181 cur_pp = &cur->next;
8182 continue;
8183 }
8184 /* Unexport */
8185 if (cur->flg_export) {
8186 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
8187 bb_unsetenv(cur->varstr);
8188 }
8189 /* Remove from global list */
8190 *cur_pp = cur->next;
8191 /* Free */
8192 if (!cur->max_len) {
8193 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
8194 free(cur->varstr);
8195 }
8196 free(cur);
8197 }
8198}
8199
8200static void enter_var_nest_level(void)
8201{
8202 G.var_nest_level++;
8203 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
8204
8205 /* Try: f() { echo -n .; f; }; f
8206 * struct variable::var_nest_level is uint16_t,
8207 * thus limiting recursion to < 2^16.
8208 * In any case, with 8 Mbyte stack SEGV happens
8209 * not too long after 2^16 recursions anyway.
8210 */
8211 if (G.var_nest_level > 0xff00)
8212 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
8213}
8214
8215static void leave_var_nest_level(void)
8216{
8217 G.var_nest_level--;
8218 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
8219 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
James Byrne69374872019-07-02 11:35:03 +02008220 bb_simple_error_msg_and_die("BUG: nesting underflow");
Denys Vlasenko99496dc2018-06-26 15:36:58 +02008221
8222 remove_nested_vars();
8223}
8224
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008225#if ENABLE_HUSH_FUNCTIONS
8226static struct function **find_function_slot(const char *name)
8227{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008228 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008229 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008230
8231 while ((funcp = *funcpp) != NULL) {
8232 if (strcmp(name, funcp->name) == 0) {
8233 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008234 break;
8235 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008236 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008237 }
8238 return funcpp;
8239}
8240
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008241static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008242{
8243 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008244 return funcp;
8245}
8246
8247/* Note: takes ownership on name ptr */
8248static struct function *new_function(char *name)
8249{
8250 struct function **funcpp = find_function_slot(name);
8251 struct function *funcp = *funcpp;
8252
8253 if (funcp != NULL) {
8254 struct command *cmd = funcp->parent_cmd;
8255 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
8256 if (!cmd) {
8257 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
8258 free(funcp->name);
8259 /* Note: if !funcp->body, do not free body_as_string!
8260 * This is a special case of "-F name body" function:
8261 * body_as_string was not malloced! */
8262 if (funcp->body) {
8263 free_pipe_list(funcp->body);
8264# if !BB_MMU
8265 free(funcp->body_as_string);
8266# endif
8267 }
8268 } else {
8269 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
8270 cmd->argv[0] = funcp->name;
8271 cmd->group = funcp->body;
8272# if !BB_MMU
8273 cmd->group_as_string = funcp->body_as_string;
8274# endif
8275 }
8276 } else {
8277 debug_printf_exec("remembering new function '%s'\n", name);
8278 funcp = *funcpp = xzalloc(sizeof(*funcp));
8279 /*funcp->next = NULL;*/
8280 }
8281
8282 funcp->name = name;
8283 return funcp;
8284}
8285
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008286# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008287static void unset_func(const char *name)
8288{
8289 struct function **funcpp = find_function_slot(name);
8290 struct function *funcp = *funcpp;
8291
8292 if (funcp != NULL) {
8293 debug_printf_exec("freeing function '%s'\n", funcp->name);
8294 *funcpp = funcp->next;
8295 /* funcp is unlinked now, deleting it.
8296 * Note: if !funcp->body, the function was created by
8297 * "-F name body", do not free ->body_as_string
8298 * and ->name as they were not malloced. */
8299 if (funcp->body) {
8300 free_pipe_list(funcp->body);
8301 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008302# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008303 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008304# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008305 }
8306 free(funcp);
8307 }
8308}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008309# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008310
8311# if BB_MMU
8312#define exec_function(to_free, funcp, argv) \
8313 exec_function(funcp, argv)
8314# endif
8315static void exec_function(char ***to_free,
8316 const struct function *funcp,
8317 char **argv) NORETURN;
8318static void exec_function(char ***to_free,
8319 const struct function *funcp,
8320 char **argv)
8321{
8322# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008323 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008324
8325 argv[0] = G.global_argv[0];
8326 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008327 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008328
8329// Example when we are here: "cmd | func"
8330// func will run with saved-redirect fds open.
8331// $ f() { echo /proc/self/fd/*; }
8332// $ true | f
8333// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8334// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8335// Same in script:
8336// $ . ./SCRIPT
8337// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8338// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8339// They are CLOEXEC so external programs won't see them, but
8340// for "more correctness" we might want to close those extra fds here:
8341//? close_saved_fds_and_FILE_fds();
8342
Denys Vlasenko332e4112018-04-04 22:32:59 +02008343 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008344 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008345 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008346 IF_HUSH_LOCAL(G.func_nest_level++;)
8347
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008348 /* On MMU, funcp->body is always non-NULL */
8349 n = run_list(funcp->body);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008350 _exit(n);
8351# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008352//? close_saved_fds_and_FILE_fds();
8353
8354//TODO: check whether "true | func_with_return" works
8355
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008356 re_execute_shell(to_free,
8357 funcp->body_as_string,
8358 G.global_argv[0],
8359 argv + 1,
8360 NULL);
8361# endif
8362}
8363
8364static int run_function(const struct function *funcp, char **argv)
8365{
8366 int rc;
8367 save_arg_t sv;
8368 smallint sv_flg;
8369
8370 save_and_replace_G_args(&sv, argv);
8371
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008372 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008373 sv_flg = G_flag_return_in_progress;
8374 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008375
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008376 /* Make "local" variables properly shadow previous ones */
8377 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008378 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008379
8380 /* On MMU, funcp->body is always non-NULL */
8381# if !BB_MMU
8382 if (!funcp->body) {
8383 /* Function defined by -F */
8384 parse_and_run_string(funcp->body_as_string);
8385 rc = G.last_exitcode;
8386 } else
8387# endif
8388 {
8389 rc = run_list(funcp->body);
8390 }
8391
Denys Vlasenko332e4112018-04-04 22:32:59 +02008392 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008393 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008394
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008395 G_flag_return_in_progress = sv_flg;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01008396# if ENABLE_HUSH_TRAP
8397 debug_printf_exec("G.return_exitcode=-1\n");
8398 G.return_exitcode = -1; /* invalidate stashed return value */
8399# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008400
8401 restore_G_args(&sv, argv);
8402
8403 return rc;
8404}
8405#endif /* ENABLE_HUSH_FUNCTIONS */
8406
8407
8408#if BB_MMU
8409#define exec_builtin(to_free, x, argv) \
8410 exec_builtin(x, argv)
8411#else
8412#define exec_builtin(to_free, x, argv) \
8413 exec_builtin(to_free, argv)
8414#endif
8415static void exec_builtin(char ***to_free,
8416 const struct built_in_command *x,
8417 char **argv) NORETURN;
8418static void exec_builtin(char ***to_free,
8419 const struct built_in_command *x,
8420 char **argv)
8421{
8422#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008423 int rcode;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008424//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008425 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008426 fflush_all();
8427 _exit(rcode);
8428#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008429 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008430 /* On NOMMU, we must never block!
8431 * Example: { sleep 99 | read line; } & echo Ok
8432 */
8433 re_execute_shell(to_free,
8434 argv[0],
8435 G.global_argv[0],
8436 G.global_argv + 1,
8437 argv);
8438#endif
8439}
8440
8441
8442static void execvp_or_die(char **argv) NORETURN;
8443static void execvp_or_die(char **argv)
8444{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008445 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008446 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008447 /* Don't propagate SIG_IGN to the child */
8448 if (SPECIAL_JOBSTOP_SIGS != 0)
8449 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008450 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008451 e = 2;
8452 if (errno == EACCES) e = 126;
8453 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008454 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008455 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008456}
8457
8458#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008459static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008460{
8461 unsigned len;
8462 const char *cp;
8463
8464 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008465
8466 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8467 /* test a char with: bash -c 'set -x; echo "CH"' */
8468 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8469 " " "\001\002\003\004\005\006\007"
8470 "\010\011\012\013\014\015\016\017"
8471 "\020\021\022\023\024\025\026\027"
8472 "\030\031\032\033\034\035\036\037"
8473 )
8474 ] == '\0'
8475 ) {
8476 /* string has no special chars */
8477 x_mode_addstr(str);
8478 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008479 }
8480
8481 cp = str;
8482 for (;;) {
8483 /* print '....' up to EOL or first squote */
8484 len = (int)(strchrnul(cp, '\'') - cp);
8485 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008486 x_mode_addchr('\'');
8487 x_mode_addblock(cp, len);
8488 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008489 cp += len;
8490 }
8491 if (*cp == '\0')
8492 break;
8493 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008494 x_mode_addchr('\\');
8495 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008496 cp++;
8497 }
8498}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008499static void dump_cmd_in_x_mode(char **argv)
8500{
8501 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008502 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008503
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008504 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008505 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008506 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008507 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008508 x_mode_addchr(' ');
8509 if (argv[n][0] == '\0') {
8510 x_mode_addchr('\'');
8511 x_mode_addchr('\'');
8512 } else {
8513 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008514 }
8515 n++;
8516 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008517 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008518 }
8519}
8520#else
8521# define dump_cmd_in_x_mode(argv) ((void)0)
8522#endif
8523
Denys Vlasenko57000292018-01-12 14:41:45 +01008524#if ENABLE_HUSH_COMMAND
8525static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8526{
8527 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008528
Denys Vlasenko57000292018-01-12 14:41:45 +01008529 if (!opt_vV)
8530 return;
8531
8532 to_free = NULL;
8533 if (!explanation) {
8534 char *path = getenv("PATH");
8535 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008536 if (!explanation)
8537 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008538 if (opt_vV != 'V')
8539 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8540 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008541 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008542 free(to_free);
8543 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008544 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008545}
8546#else
8547# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8548#endif
8549
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008550#if BB_MMU
8551#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8552 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8553#define pseudo_exec(nommu_save, command, argv_expanded) \
8554 pseudo_exec(command, argv_expanded)
8555#endif
8556
8557/* Called after [v]fork() in run_pipe, or from builtin_exec.
8558 * Never returns.
8559 * Don't exit() here. If you don't exec, use _exit instead.
8560 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008561 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008562 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008563static void pseudo_exec_argv(nommu_save_t *nommu_save,
8564 char **argv, int assignment_cnt,
8565 char **argv_expanded) NORETURN;
8566static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8567 char **argv, int assignment_cnt,
8568 char **argv_expanded)
8569{
Denys Vlasenko57000292018-01-12 14:41:45 +01008570 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008571 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008572 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008573 IF_HUSH_COMMAND(char opt_vV = 0;)
8574 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008575
8576 new_env = expand_assignments(argv, assignment_cnt);
8577 dump_cmd_in_x_mode(new_env);
8578
8579 if (!argv[assignment_cnt]) {
8580 /* Case when we are here: ... | var=val | ...
8581 * (note that we do not exit early, i.e., do not optimize out
8582 * expand_assignments(): think about ... | var=`sleep 1` | ...
8583 */
8584 free_strings(new_env);
8585 _exit(EXIT_SUCCESS);
8586 }
8587
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008588 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008589#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008590 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008591#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008592 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008593 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008594#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008595 set_vars_and_save_old(new_env);
8596 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008597
8598 if (argv_expanded) {
8599 argv = argv_expanded;
8600 } else {
8601 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8602#if !BB_MMU
8603 nommu_save->argv = argv;
8604#endif
8605 }
8606 dump_cmd_in_x_mode(argv);
8607
8608#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8609 if (strchr(argv[0], '/') != NULL)
8610 goto skip;
8611#endif
8612
Denys Vlasenko75481d32017-07-31 05:27:09 +02008613#if ENABLE_HUSH_FUNCTIONS
8614 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008615 funcp = find_function(argv[0]);
8616 if (funcp)
8617 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008618#endif
8619
Denys Vlasenko57000292018-01-12 14:41:45 +01008620#if ENABLE_HUSH_COMMAND
8621 /* "command BAR": run BAR without looking it up among functions
8622 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8623 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8624 */
8625 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8626 char *p;
8627
8628 argv++;
8629 p = *argv;
8630 if (p[0] != '-' || !p[1])
8631 continue; /* bash allows "command command command [-OPT] BAR" */
8632
8633 for (;;) {
8634 p++;
8635 switch (*p) {
8636 case '\0':
8637 argv++;
8638 p = *argv;
8639 if (p[0] != '-' || !p[1])
8640 goto after_opts;
8641 continue; /* next arg is also -opts, process it too */
8642 case 'v':
8643 case 'V':
8644 opt_vV = *p;
8645 continue;
8646 default:
8647 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8648 }
8649 }
8650 }
8651 after_opts:
8652# if ENABLE_HUSH_FUNCTIONS
8653 if (opt_vV && find_function(argv[0]))
8654 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8655# endif
8656#endif
8657
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008658 /* Check if the command matches any of the builtins.
8659 * Depending on context, this might be redundant. But it's
8660 * easier to waste a few CPU cycles than it is to figure out
8661 * if this is one of those cases.
8662 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008663 /* Why "BB_MMU ? :" difference in logic? -
8664 * On NOMMU, it is more expensive to re-execute shell
8665 * just in order to run echo or test builtin.
8666 * It's better to skip it here and run corresponding
8667 * non-builtin later. */
8668 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8669 if (x) {
8670 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8671 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008672 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008673
8674#if ENABLE_FEATURE_SH_STANDALONE
8675 /* Check if the command matches any busybox applets */
8676 {
8677 int a = find_applet_by_name(argv[0]);
8678 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008679 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008680# if BB_MMU /* see above why on NOMMU it is not allowed */
8681 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008682 /* Do not leak open fds from opened script files etc.
8683 * Testcase: interactive "ls -l /proc/self/fd"
8684 * should not show tty fd open.
8685 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008686 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008687//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008688//This casuses test failures in
8689//redir_children_should_not_see_saved_fd_2.tests
8690//redir_children_should_not_see_saved_fd_3.tests
8691//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008692 /* Without this, "rm -i FILE" can't be ^C'ed: */
8693 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008694 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008695 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008696 }
8697# endif
8698 /* Re-exec ourselves */
8699 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008700 /* Don't propagate SIG_IGN to the child */
8701 if (SPECIAL_JOBSTOP_SIGS != 0)
8702 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008703 execv(bb_busybox_exec_path, argv);
8704 /* If they called chroot or otherwise made the binary no longer
8705 * executable, fall through */
8706 }
8707 }
8708#endif
8709
8710#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8711 skip:
8712#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008713 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008714 execvp_or_die(argv);
8715}
8716
8717/* Called after [v]fork() in run_pipe
8718 */
8719static void pseudo_exec(nommu_save_t *nommu_save,
8720 struct command *command,
8721 char **argv_expanded) NORETURN;
8722static void pseudo_exec(nommu_save_t *nommu_save,
8723 struct command *command,
8724 char **argv_expanded)
8725{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008726#if ENABLE_HUSH_FUNCTIONS
8727 if (command->cmd_type == CMD_FUNCDEF) {
8728 /* Ignore funcdefs in pipes:
8729 * true | f() { cmd }
8730 */
8731 _exit(0);
8732 }
8733#endif
8734
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008735 if (command->argv) {
8736 pseudo_exec_argv(nommu_save, command->argv,
8737 command->assignment_cnt, argv_expanded);
8738 }
8739
8740 if (command->group) {
8741 /* Cases when we are here:
8742 * ( list )
8743 * { list } &
8744 * ... | ( list ) | ...
8745 * ... | { list } | ...
8746 */
8747#if BB_MMU
8748 int rcode;
8749 debug_printf_exec("pseudo_exec: run_list\n");
8750 reset_traps_to_defaults();
8751 rcode = run_list(command->group);
8752 /* OK to leak memory by not calling free_pipe_list,
8753 * since this process is about to exit */
8754 _exit(rcode);
8755#else
8756 re_execute_shell(&nommu_save->argv_from_re_execing,
8757 command->group_as_string,
8758 G.global_argv[0],
8759 G.global_argv + 1,
8760 NULL);
8761#endif
8762 }
8763
8764 /* Case when we are here: ... | >file */
8765 debug_printf_exec("pseudo_exec'ed null command\n");
8766 _exit(EXIT_SUCCESS);
8767}
8768
8769#if ENABLE_HUSH_JOB
8770static const char *get_cmdtext(struct pipe *pi)
8771{
8772 char **argv;
8773 char *p;
8774 int len;
8775
8776 /* This is subtle. ->cmdtext is created only on first backgrounding.
8777 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8778 * On subsequent bg argv is trashed, but we won't use it */
8779 if (pi->cmdtext)
8780 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008781
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008782 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008783 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008784 pi->cmdtext = xzalloc(1);
8785 return pi->cmdtext;
8786 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008787 len = 0;
8788 do {
8789 len += strlen(*argv) + 1;
8790 } while (*++argv);
8791 p = xmalloc(len);
8792 pi->cmdtext = p;
8793 argv = pi->cmds[0].argv;
8794 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008795 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008796 *p++ = ' ';
8797 } while (*++argv);
8798 p[-1] = '\0';
8799 return pi->cmdtext;
8800}
8801
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008802static void remove_job_from_table(struct pipe *pi)
8803{
8804 struct pipe *prev_pipe;
8805
8806 if (pi == G.job_list) {
8807 G.job_list = pi->next;
8808 } else {
8809 prev_pipe = G.job_list;
8810 while (prev_pipe->next != pi)
8811 prev_pipe = prev_pipe->next;
8812 prev_pipe->next = pi->next;
8813 }
8814 G.last_jobid = 0;
8815 if (G.job_list)
8816 G.last_jobid = G.job_list->jobid;
8817}
8818
8819static void delete_finished_job(struct pipe *pi)
8820{
8821 remove_job_from_table(pi);
8822 free_pipe(pi);
8823}
8824
8825static void clean_up_last_dead_job(void)
8826{
8827 if (G.job_list && !G.job_list->alive_cmds)
8828 delete_finished_job(G.job_list);
8829}
8830
Denys Vlasenko16096292017-07-10 10:00:28 +02008831static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008832{
8833 struct pipe *job, **jobp;
8834 int i;
8835
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008836 clean_up_last_dead_job();
8837
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008838 /* Find the end of the list, and find next job ID to use */
8839 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008840 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008841 while ((job = *jobp) != NULL) {
8842 if (job->jobid > i)
8843 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008844 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008845 }
8846 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008847
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008848 /* Create a new job struct at the end */
8849 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008850 job->next = NULL;
8851 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8852 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8853 for (i = 0; i < pi->num_cmds; i++) {
8854 job->cmds[i].pid = pi->cmds[i].pid;
8855 /* all other fields are not used and stay zero */
8856 }
8857 job->cmdtext = xstrdup(get_cmdtext(pi));
8858
8859 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008860 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008861 G.last_jobid = job->jobid;
8862}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008863#endif /* JOB */
8864
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008865static int job_exited_or_stopped(struct pipe *pi)
8866{
8867 int rcode, i;
8868
8869 if (pi->alive_cmds != pi->stopped_cmds)
8870 return -1;
8871
8872 /* All processes in fg pipe have exited or stopped */
8873 rcode = 0;
8874 i = pi->num_cmds;
8875 while (--i >= 0) {
8876 rcode = pi->cmds[i].cmd_exitcode;
8877 /* usually last process gives overall exitstatus,
8878 * but with "set -o pipefail", last *failed* process does */
8879 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8880 break;
8881 }
8882 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8883 return rcode;
8884}
8885
Denys Vlasenko7e675362016-10-28 21:57:31 +02008886static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008887{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008888#if ENABLE_HUSH_JOB
8889 struct pipe *pi;
8890#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008891 int i, dead;
8892
8893 dead = WIFEXITED(status) || WIFSIGNALED(status);
8894
8895#if DEBUG_JOBS
8896 if (WIFSTOPPED(status))
8897 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8898 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8899 if (WIFSIGNALED(status))
8900 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8901 childpid, WTERMSIG(status), WEXITSTATUS(status));
8902 if (WIFEXITED(status))
8903 debug_printf_jobs("pid %d exited, exitcode %d\n",
8904 childpid, WEXITSTATUS(status));
8905#endif
8906 /* Were we asked to wait for a fg pipe? */
8907 if (fg_pipe) {
8908 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008909
Denys Vlasenko7e675362016-10-28 21:57:31 +02008910 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008911 int rcode;
8912
Denys Vlasenko7e675362016-10-28 21:57:31 +02008913 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8914 if (fg_pipe->cmds[i].pid != childpid)
8915 continue;
8916 if (dead) {
8917 int ex;
8918 fg_pipe->cmds[i].pid = 0;
8919 fg_pipe->alive_cmds--;
8920 ex = WEXITSTATUS(status);
8921 /* bash prints killer signal's name for *last*
8922 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8923 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8924 */
8925 if (WIFSIGNALED(status)) {
8926 int sig = WTERMSIG(status);
Denys Vlasenko77a51a22020-12-29 16:53:11 +01008927#if ENABLE_HUSH_JOB
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008928 if (G.run_list_level == 1
8929 /* ^^^^^ Do not print in nested contexts, example:
8930 * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
8931 */
8932 && i == fg_pipe->num_cmds-1
8933 ) {
Denys Vlasenkoe16f7eb2020-10-24 04:26:43 +02008934 /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
8935 puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008936 }
Denys Vlasenko77a51a22020-12-29 16:53:11 +01008937#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008938 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko93e2a222020-12-23 12:23:21 +01008939 /* MIPS has 128 sigs (1..128), if sig==128,
8940 * 128 + sig would result in exitcode 256 -> 0!
8941 */
8942 ex = 128 | sig;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008943 }
8944 fg_pipe->cmds[i].cmd_exitcode = ex;
8945 } else {
8946 fg_pipe->stopped_cmds++;
8947 }
8948 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8949 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008950 rcode = job_exited_or_stopped(fg_pipe);
8951 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008952/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8953 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8954 * and "killall -STOP cat" */
8955 if (G_interactive_fd) {
8956#if ENABLE_HUSH_JOB
8957 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008958 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008959#endif
8960 return rcode;
8961 }
8962 if (fg_pipe->alive_cmds == 0)
8963 return rcode;
8964 }
8965 /* There are still running processes in the fg_pipe */
8966 return -1;
8967 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008968 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008969 }
8970
8971#if ENABLE_HUSH_JOB
8972 /* We were asked to wait for bg or orphaned children */
8973 /* No need to remember exitcode in this case */
8974 for (pi = G.job_list; pi; pi = pi->next) {
8975 for (i = 0; i < pi->num_cmds; i++) {
8976 if (pi->cmds[i].pid == childpid)
8977 goto found_pi_and_prognum;
8978 }
8979 }
8980 /* Happens when shell is used as init process (init=/bin/sh) */
8981 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8982 return -1; /* this wasn't a process from fg_pipe */
8983
8984 found_pi_and_prognum:
8985 if (dead) {
8986 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008987 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008988 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01008989 /* NB: not 128 + sig, MIPS has sig 128 */
8990 rcode = 128 | WTERMSIG(status);
Denys Vlasenko840a4352017-07-07 22:56:02 +02008991 pi->cmds[i].cmd_exitcode = rcode;
8992 if (G.last_bg_pid == pi->cmds[i].pid)
8993 G.last_bg_pid_exitcode = rcode;
8994 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008995 pi->alive_cmds--;
8996 if (!pi->alive_cmds) {
Denys Vlasenko259747c2019-11-28 10:28:14 +01008997# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008998 G.dead_job_exitcode = job_exited_or_stopped(pi);
Denys Vlasenko259747c2019-11-28 10:28:14 +01008999# endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02009000 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009001 printf(JOB_STATUS_FORMAT, pi->jobid,
9002 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02009003 delete_finished_job(pi);
9004 } else {
9005/*
9006 * bash deletes finished jobs from job table only in interactive mode,
9007 * after "jobs" cmd, or if pid of a new process matches one of the old ones
9008 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
9009 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
9010 * We only retain one "dead" job, if it's the single job on the list.
9011 * This covers most of real-world scenarios where this is useful.
9012 */
9013 if (pi != G.job_list)
9014 delete_finished_job(pi);
9015 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009016 }
9017 } else {
9018 /* child stopped */
9019 pi->stopped_cmds++;
9020 }
9021#endif
9022 return -1; /* this wasn't a process from fg_pipe */
9023}
9024
9025/* Check to see if any processes have exited -- if they have,
9026 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009027 *
9028 * If non-NULL fg_pipe: wait for its completion or stop.
9029 * Return its exitcode or zero if stopped.
9030 *
9031 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
9032 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
9033 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
9034 * or 0 if no children changed status.
9035 *
9036 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
9037 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
9038 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02009039 */
9040static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
9041{
9042 int attributes;
9043 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009044 int rcode = 0;
9045
9046 debug_printf_jobs("checkjobs %p\n", fg_pipe);
9047
9048 attributes = WUNTRACED;
9049 if (fg_pipe == NULL)
9050 attributes |= WNOHANG;
9051
9052 errno = 0;
9053#if ENABLE_HUSH_FAST
9054 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
9055//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
9056//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
9057 /* There was neither fork nor SIGCHLD since last waitpid */
9058 /* Avoid doing waitpid syscall if possible */
9059 if (!G.we_have_children) {
9060 errno = ECHILD;
9061 return -1;
9062 }
9063 if (fg_pipe == NULL) { /* is WNOHANG set? */
9064 /* We have children, but they did not exit
9065 * or stop yet (we saw no SIGCHLD) */
9066 return 0;
9067 }
9068 /* else: !WNOHANG, waitpid will block, can't short-circuit */
9069 }
9070#endif
9071
9072/* Do we do this right?
9073 * bash-3.00# sleep 20 | false
9074 * <ctrl-Z pressed>
9075 * [3]+ Stopped sleep 20 | false
9076 * bash-3.00# echo $?
9077 * 1 <========== bg pipe is not fully done, but exitcode is already known!
9078 * [hush 1.14.0: yes we do it right]
9079 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009080 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009081 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009082#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02009083 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009084 i = G.count_SIGCHLD;
9085#endif
9086 childpid = waitpid(-1, &status, attributes);
9087 if (childpid <= 0) {
9088 if (childpid && errno != ECHILD)
James Byrne69374872019-07-02 11:35:03 +02009089 bb_simple_perror_msg("waitpid");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009090#if ENABLE_HUSH_FAST
9091 else { /* Until next SIGCHLD, waitpid's are useless */
9092 G.we_have_children = (childpid == 0);
9093 G.handled_SIGCHLD = i;
9094//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9095 }
9096#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009097 /* ECHILD (no children), or 0 (no change in children status) */
9098 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009099 break;
9100 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009101 rcode = process_wait_result(fg_pipe, childpid, status);
9102 if (rcode >= 0) {
9103 /* fg_pipe exited or stopped */
9104 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009105 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01009106 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009107 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009108 rcode = WEXITSTATUS(status);
9109 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009110 rcode = 128 | WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009111 if (WIFSTOPPED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009112 /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
9113 rcode = 128 | WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009114 rcode++;
9115 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009116 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01009117#if ENABLE_HUSH_BASH_COMPAT
9118 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
9119 && G.dead_job_exitcode >= 0 /* some job did finish */
9120 ) {
9121 debug_printf_exec("waitfor_pid:-1\n");
9122 rcode = G.dead_job_exitcode + 1;
9123 break;
9124 }
9125#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009126 /* This wasn't one of our processes, or */
9127 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009128 } /* while (waitpid succeeds)... */
9129
9130 return rcode;
9131}
9132
9133#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02009134static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009135{
9136 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02009137 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009138 if (G_saved_tty_pgrp) {
9139 /* Job finished, move the shell to the foreground */
9140 p = getpgrp(); /* our process group id */
9141 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
9142 tcsetpgrp(G_interactive_fd, p);
9143 }
9144 return rcode;
9145}
9146#endif
9147
9148/* Start all the jobs, but don't wait for anything to finish.
9149 * See checkjobs().
9150 *
9151 * Return code is normally -1, when the caller has to wait for children
9152 * to finish to determine the exit status of the pipe. If the pipe
9153 * is a simple builtin command, however, the action is done by the
9154 * time run_pipe returns, and the exit code is provided as the
9155 * return value.
9156 *
9157 * Returns -1 only if started some children. IOW: we have to
9158 * mask out retvals of builtins etc with 0xff!
9159 *
9160 * The only case when we do not need to [v]fork is when the pipe
9161 * is single, non-backgrounded, non-subshell command. Examples:
9162 * cmd ; ... { list } ; ...
9163 * cmd && ... { list } && ...
9164 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01009165 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009166 * or (if SH_STANDALONE) an applet, and we can run the { list }
9167 * with run_list. If it isn't one of these, we fork and exec cmd.
9168 *
9169 * Cases when we must fork:
9170 * non-single: cmd | cmd
9171 * backgrounded: cmd & { list } &
9172 * subshell: ( list ) [&]
9173 */
9174#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009175#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
9176 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009177#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009178static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009179 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02009180 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009181 char **argv_expanded)
9182{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009183 /* Assignments occur before redirects. Try:
9184 * a=`sleep 1` sleep 2 3>/qwe/rty
9185 */
9186
9187 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
9188 dump_cmd_in_x_mode(new_env);
9189 dump_cmd_in_x_mode(argv_expanded);
9190 /* this takes ownership of new_env[i] elements, and frees new_env: */
9191 set_vars_and_save_old(new_env);
9192
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009193 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009194}
9195static NOINLINE int run_pipe(struct pipe *pi)
9196{
9197 static const char *const null_ptr = NULL;
9198
9199 int cmd_no;
9200 int next_infd;
9201 struct command *command;
9202 char **argv_expanded;
9203 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02009204 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009205 int rcode;
9206
9207 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
9208 debug_enter();
9209
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009210 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
9211 * Result should be 3 lines: q w e, qwe, q w e
9212 */
Denys Vlasenko96786362018-04-11 16:02:58 +02009213 if (G.ifs_whitespace != G.ifs)
9214 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009215 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02009216 if (G.ifs) {
9217 char *p;
9218 G.ifs_whitespace = (char*)G.ifs;
9219 p = skip_whitespace(G.ifs);
9220 if (*p) {
9221 /* Not all $IFS is whitespace */
9222 char *d;
9223 int len = p - G.ifs;
9224 p = skip_non_whitespace(p);
9225 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
9226 d = mempcpy(G.ifs_whitespace, G.ifs, len);
9227 while (*p) {
9228 if (isspace(*p))
9229 *d++ = *p;
9230 p++;
9231 }
9232 *d = '\0';
9233 }
9234 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009235 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02009236 G.ifs_whitespace = (char*)G.ifs;
9237 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009238
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009239 IF_HUSH_JOB(pi->pgrp = -1;)
9240 pi->stopped_cmds = 0;
9241 command = &pi->cmds[0];
9242 argv_expanded = NULL;
9243
9244 if (pi->num_cmds != 1
9245 || pi->followup == PIPE_BG
9246 || command->cmd_type == CMD_SUBSHELL
9247 ) {
9248 goto must_fork;
9249 }
9250
9251 pi->alive_cmds = 1;
9252
9253 debug_printf_exec(": group:%p argv:'%s'\n",
9254 command->group, command->argv ? command->argv[0] : "NONE");
9255
9256 if (command->group) {
9257#if ENABLE_HUSH_FUNCTIONS
9258 if (command->cmd_type == CMD_FUNCDEF) {
9259 /* "executing" func () { list } */
9260 struct function *funcp;
9261
9262 funcp = new_function(command->argv[0]);
9263 /* funcp->name is already set to argv[0] */
9264 funcp->body = command->group;
9265# if !BB_MMU
9266 funcp->body_as_string = command->group_as_string;
9267 command->group_as_string = NULL;
9268# endif
9269 command->group = NULL;
9270 command->argv[0] = NULL;
9271 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
9272 funcp->parent_cmd = command;
9273 command->child_func = funcp;
9274
9275 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
9276 debug_leave();
9277 return EXIT_SUCCESS;
9278 }
9279#endif
9280 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009281 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009282 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009283 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009284 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02009285//FIXME: we need to pass squirrel down into run_list()
9286//for SH_STANDALONE case, or else this construct:
9287// { find /proc/self/fd; true; } >FILE; cmd2
9288//has no way of closing saved fd#1 for "find",
9289//and in SH_STANDALONE mode, "find" is not execed,
9290//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009291 rcode = run_list(command->group) & 0xff;
9292 }
9293 restore_redirects(squirrel);
9294 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9295 debug_leave();
9296 debug_printf_exec("run_pipe: return %d\n", rcode);
9297 return rcode;
9298 }
9299
9300 argv = command->argv ? command->argv : (char **) &null_ptr;
9301 {
9302 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009303 IF_HUSH_FUNCTIONS(const struct function *funcp;)
9304 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009305 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009306 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009307
Denys Vlasenko5807e182018-02-08 19:19:04 +01009308#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009309 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009310#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009311
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009312 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009313 /* Assignments, but no command.
9314 * Ensure redirects take effect (that is, create files).
9315 * Try "a=t >file"
9316 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009317 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009318 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009319 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009320 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009321 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009322
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009323 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009324 i = 0;
9325 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009326 char *p = expand_string_to_string(argv[i],
9327 EXP_FLAG_ESC_GLOB_CHARS,
9328 /*unbackslash:*/ 1
9329 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009330#if ENABLE_HUSH_MODE_X
9331 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009332 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009333 if (i == 0)
9334 x_mode_prefix();
9335 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009336 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009337 if (*eq) eq++;
9338 x_mode_addblock(p, (eq - p));
9339 x_mode_print_optionally_squoted(eq);
9340 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009341 }
9342#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009343 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009344 if (set_local_var(p, /*flag:*/ 0)) {
9345 /* assignment to readonly var / putenv error? */
9346 rcode = 1;
9347 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009348 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009349 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009350 /* Redirect error sets $? to 1. Otherwise,
9351 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009352 * Else, clear $?:
9353 * false; q=`exit 2`; echo $? - should print 2
9354 * false; x=1; echo $? - should print 0
9355 * Because of the 2nd case, we can't just use G.last_exitcode.
9356 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009357 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009358 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009359 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9360 debug_leave();
9361 debug_printf_exec("run_pipe: return %d\n", rcode);
9362 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009363 }
9364
9365 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkod2241f52020-10-31 03:34:07 +01009366#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
9367 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
9368 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
9369 else
9370#endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02009371#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009372 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009373 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009374 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009375#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009376 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009377
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009378 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009379 if (!argv_expanded[0]) {
9380 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009381 /* `false` still has to set exitcode 1 */
9382 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009383 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009384 }
9385
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009386 old_vars = NULL;
9387 sv_shadowed = G.shadowed_vars_pp;
9388
Denys Vlasenko75481d32017-07-31 05:27:09 +02009389 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009390 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9391 IF_HUSH_FUNCTIONS(x = NULL;)
9392 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009393 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009394 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009395 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9396 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009397 /*
9398 * Variable assignments are executed, but then "forgotten":
9399 * a=`sleep 1;echo A` exec 3>&-; echo $a
9400 * sleeps, but prints nothing.
9401 */
9402 enter_var_nest_level();
9403 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009404 rcode = redirect_and_varexp_helper(command,
9405 /*squirrel:*/ ERR_PTR,
9406 argv_expanded
9407 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009408 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009409 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009410
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009411 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009412 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009413
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009414 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009415 * a=b true; env | grep ^a=
9416 */
9417 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009418 /* Collect all variables "shadowed" by helper
9419 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9420 * into old_vars list:
9421 */
9422 G.shadowed_vars_pp = &old_vars;
9423 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009424 if (rcode == 0) {
9425 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009426 /* Do not collect *to old_vars list* vars shadowed
9427 * by e.g. "local VAR" builtin (collect them
9428 * in the previously nested list instead):
9429 * don't want them to be restored immediately
9430 * after "local" completes.
9431 */
9432 G.shadowed_vars_pp = sv_shadowed;
9433
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009434 debug_printf_exec(": builtin '%s' '%s'...\n",
9435 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009436 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009437 rcode = x->b_function(argv_expanded) & 0xff;
9438 fflush_all();
9439 }
9440#if ENABLE_HUSH_FUNCTIONS
9441 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009442 debug_printf_exec(": function '%s' '%s'...\n",
9443 funcp->name, argv_expanded[1]);
9444 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009445 /*
9446 * But do collect *to old_vars list* vars shadowed
9447 * within function execution. To that end, restore
9448 * this pointer _after_ function run:
9449 */
9450 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009451 }
9452#endif
9453 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009454 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009455 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009456 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009457 if (n < 0 || !APPLET_IS_NOFORK(n))
9458 goto must_fork;
9459
9460 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009461 /* Collect all variables "shadowed" by helper into old_vars list */
9462 G.shadowed_vars_pp = &old_vars;
9463 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9464 G.shadowed_vars_pp = sv_shadowed;
9465
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009466 if (rcode == 0) {
9467 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9468 argv_expanded[0], argv_expanded[1]);
9469 /*
9470 * Note: signals (^C) can't interrupt here.
9471 * We remember them and they will be acted upon
9472 * after applet returns.
9473 * This makes applets which can run for a long time
9474 * and/or wait for user input ineligible for NOFORK:
9475 * for example, "yes" or "rm" (rm -i waits for input).
9476 */
9477 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009478 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009479 } else
9480 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009481
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009482 restore_redirects(squirrel);
9483 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009484 leave_var_nest_level();
9485 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009486
9487 /*
9488 * Try "usleep 99999999" + ^C + "echo $?"
9489 * with FEATURE_SH_NOFORK=y.
9490 */
9491 if (!funcp) {
9492 /* It was builtin or nofork.
9493 * if this would be a real fork/execed program,
9494 * it should have died if a fatal sig was received.
9495 * But OTOH, there was no separate process,
9496 * the sig was sent to _shell_, not to non-existing
9497 * child.
9498 * Let's just handle ^C only, this one is obvious:
9499 * we aren't ok with exitcode 0 when ^C was pressed
9500 * during builtin/nofork.
9501 */
9502 if (sigismember(&G.pending_set, SIGINT))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009503 rcode = 128 | SIGINT;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009504 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009505 free(argv_expanded);
9506 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9507 debug_leave();
9508 debug_printf_exec("run_pipe return %d\n", rcode);
9509 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009510 }
9511
9512 must_fork:
9513 /* NB: argv_expanded may already be created, and that
9514 * might include `cmd` runs! Do not rerun it! We *must*
9515 * use argv_expanded if it's non-NULL */
9516
9517 /* Going to fork a child per each pipe member */
9518 pi->alive_cmds = 0;
9519 next_infd = 0;
9520
9521 cmd_no = 0;
9522 while (cmd_no < pi->num_cmds) {
9523 struct fd_pair pipefds;
9524#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009525 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009526 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009527 nommu_save.old_vars = NULL;
9528 nommu_save.argv = NULL;
9529 nommu_save.argv_from_re_execing = NULL;
9530#endif
9531 command = &pi->cmds[cmd_no];
9532 cmd_no++;
9533 if (command->argv) {
9534 debug_printf_exec(": pipe member '%s' '%s'...\n",
9535 command->argv[0], command->argv[1]);
9536 } else {
9537 debug_printf_exec(": pipe member with no argv\n");
9538 }
9539
9540 /* pipes are inserted between pairs of commands */
9541 pipefds.rd = 0;
9542 pipefds.wr = 1;
9543 if (cmd_no < pi->num_cmds)
9544 xpiped_pair(pipefds);
9545
Denys Vlasenko5807e182018-02-08 19:19:04 +01009546#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009547 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009548#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009549
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009550 command->pid = BB_MMU ? fork() : vfork();
9551 if (!command->pid) { /* child */
9552#if ENABLE_HUSH_JOB
9553 disable_restore_tty_pgrp_on_exit();
9554 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9555
9556 /* Every child adds itself to new process group
9557 * with pgid == pid_of_first_child_in_pipe */
9558 if (G.run_list_level == 1 && G_interactive_fd) {
9559 pid_t pgrp;
9560 pgrp = pi->pgrp;
9561 if (pgrp < 0) /* true for 1st process only */
9562 pgrp = getpid();
9563 if (setpgid(0, pgrp) == 0
9564 && pi->followup != PIPE_BG
9565 && G_saved_tty_pgrp /* we have ctty */
9566 ) {
9567 /* We do it in *every* child, not just first,
9568 * to avoid races */
9569 tcsetpgrp(G_interactive_fd, pgrp);
9570 }
9571 }
9572#endif
9573 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9574 /* 1st cmd in backgrounded pipe
9575 * should have its stdin /dev/null'ed */
9576 close(0);
9577 if (open(bb_dev_null, O_RDONLY))
9578 xopen("/", O_RDONLY);
9579 } else {
9580 xmove_fd(next_infd, 0);
9581 }
9582 xmove_fd(pipefds.wr, 1);
9583 if (pipefds.rd > 1)
9584 close(pipefds.rd);
9585 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009586 * and the pipe fd (fd#1) is available for dup'ing:
9587 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9588 * of cmd1 goes into pipe.
9589 */
9590 if (setup_redirects(command, NULL)) {
9591 /* Happens when redir file can't be opened:
9592 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9593 * FOO
9594 * hush: can't open '/qwe/rty': No such file or directory
9595 * BAZ
9596 * (echo BAR is not executed, it hits _exit(1) below)
9597 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009598 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009599 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009600
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009601 /* Stores to nommu_save list of env vars putenv'ed
9602 * (NOMMU, on MMU we don't need that) */
9603 /* cast away volatility... */
9604 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9605 /* pseudo_exec() does not return */
9606 }
9607
9608 /* parent or error */
9609#if ENABLE_HUSH_FAST
9610 G.count_SIGCHLD++;
9611//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9612#endif
9613 enable_restore_tty_pgrp_on_exit();
9614#if !BB_MMU
9615 /* Clean up after vforked child */
9616 free(nommu_save.argv);
9617 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009618 G.var_nest_level = sv_var_nest_level;
9619 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009620 add_vars(nommu_save.old_vars);
9621#endif
9622 free(argv_expanded);
9623 argv_expanded = NULL;
9624 if (command->pid < 0) { /* [v]fork failed */
9625 /* Clearly indicate, was it fork or vfork */
James Byrne69374872019-07-02 11:35:03 +02009626 bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009627 } else {
9628 pi->alive_cmds++;
9629#if ENABLE_HUSH_JOB
9630 /* Second and next children need to know pid of first one */
9631 if (pi->pgrp < 0)
9632 pi->pgrp = command->pid;
9633#endif
9634 }
9635
9636 if (cmd_no > 1)
9637 close(next_infd);
9638 if (cmd_no < pi->num_cmds)
9639 close(pipefds.wr);
9640 /* Pass read (output) pipe end to next iteration */
9641 next_infd = pipefds.rd;
9642 }
9643
9644 if (!pi->alive_cmds) {
9645 debug_leave();
9646 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9647 return 1;
9648 }
9649
9650 debug_leave();
9651 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9652 return -1;
9653}
9654
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009655/* NB: called by pseudo_exec, and therefore must not modify any
9656 * global data until exec/_exit (we can be a child after vfork!) */
9657static int run_list(struct pipe *pi)
9658{
9659#if ENABLE_HUSH_CASE
9660 char *case_word = NULL;
9661#endif
9662#if ENABLE_HUSH_LOOPS
9663 struct pipe *loop_top = NULL;
9664 char **for_lcur = NULL;
9665 char **for_list = NULL;
9666#endif
9667 smallint last_followup;
9668 smalluint rcode;
9669#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9670 smalluint cond_code = 0;
9671#else
9672 enum { cond_code = 0 };
9673#endif
9674#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009675 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009676 smallint last_rword; /* ditto */
9677#endif
9678
9679 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9680 debug_enter();
9681
9682#if ENABLE_HUSH_LOOPS
9683 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009684 {
9685 struct pipe *cpipe;
9686 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9687 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9688 continue;
9689 /* current word is FOR or IN (BOLD in comments below) */
9690 if (cpipe->next == NULL) {
9691 syntax_error("malformed for");
9692 debug_leave();
9693 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9694 return 1;
9695 }
9696 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9697 if (cpipe->next->res_word == RES_DO)
9698 continue;
9699 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9700 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9701 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9702 ) {
9703 syntax_error("malformed for");
9704 debug_leave();
9705 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9706 return 1;
9707 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009708 }
9709 }
9710#endif
9711
9712 /* Past this point, all code paths should jump to ret: label
9713 * in order to return, no direct "return" statements please.
9714 * This helps to ensure that no memory is leaked. */
9715
9716#if ENABLE_HUSH_JOB
9717 G.run_list_level++;
9718#endif
9719
9720#if HAS_KEYWORDS
9721 rword = RES_NONE;
9722 last_rword = RES_XXXX;
9723#endif
9724 last_followup = PIPE_SEQ;
9725 rcode = G.last_exitcode;
9726
9727 /* Go through list of pipes, (maybe) executing them. */
9728 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009729 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009730 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009731
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009732 if (G.flag_SIGINT)
9733 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009734 if (G_flag_return_in_progress == 1)
9735 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009736
9737 IF_HAS_KEYWORDS(rword = pi->res_word;)
9738 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9739 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009740
9741 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009742 if (
9743#if ENABLE_HUSH_IF
9744 rword == RES_IF || rword == RES_ELIF ||
9745#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009746 pi->followup != PIPE_SEQ
9747 ) {
9748 G.errexit_depth++;
9749 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009750#if ENABLE_HUSH_LOOPS
9751 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9752 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9753 ) {
9754 /* start of a loop: remember where loop starts */
9755 loop_top = pi;
9756 G.depth_of_loop++;
9757 }
9758#endif
9759 /* Still in the same "if...", "then..." or "do..." branch? */
9760 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9761 if ((rcode == 0 && last_followup == PIPE_OR)
9762 || (rcode != 0 && last_followup == PIPE_AND)
9763 ) {
9764 /* It is "<true> || CMD" or "<false> && CMD"
9765 * and we should not execute CMD */
9766 debug_printf_exec("skipped cmd because of || or &&\n");
9767 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009768 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009769 }
9770 }
9771 last_followup = pi->followup;
9772 IF_HAS_KEYWORDS(last_rword = rword;)
9773#if ENABLE_HUSH_IF
9774 if (cond_code) {
9775 if (rword == RES_THEN) {
9776 /* if false; then ... fi has exitcode 0! */
9777 G.last_exitcode = rcode = EXIT_SUCCESS;
9778 /* "if <false> THEN cmd": skip cmd */
9779 continue;
9780 }
9781 } else {
9782 if (rword == RES_ELSE || rword == RES_ELIF) {
9783 /* "if <true> then ... ELSE/ELIF cmd":
9784 * skip cmd and all following ones */
9785 break;
9786 }
9787 }
9788#endif
9789#if ENABLE_HUSH_LOOPS
9790 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9791 if (!for_lcur) {
9792 /* first loop through for */
9793
9794 static const char encoded_dollar_at[] ALIGN1 = {
9795 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9796 }; /* encoded representation of "$@" */
9797 static const char *const encoded_dollar_at_argv[] = {
9798 encoded_dollar_at, NULL
9799 }; /* argv list with one element: "$@" */
9800 char **vals;
9801
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009802 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009803 vals = (char**)encoded_dollar_at_argv;
9804 if (pi->next->res_word == RES_IN) {
9805 /* if no variable values after "in" we skip "for" */
9806 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009807 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9808 break;
9809 }
9810 vals = pi->next->cmds[0].argv;
9811 } /* else: "for var; do..." -> assume "$@" list */
9812 /* create list of variable values */
9813 debug_print_strings("for_list made from", vals);
9814 for_list = expand_strvec_to_strvec(vals);
9815 for_lcur = for_list;
9816 debug_print_strings("for_list", for_list);
9817 }
9818 if (!*for_lcur) {
9819 /* "for" loop is over, clean up */
9820 free(for_list);
9821 for_list = NULL;
9822 for_lcur = NULL;
9823 break;
9824 }
9825 /* Insert next value from for_lcur */
9826 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009827 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009828 continue;
9829 }
9830 if (rword == RES_IN) {
9831 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9832 }
9833 if (rword == RES_DONE) {
9834 continue; /* "done" has no cmds too */
9835 }
9836#endif
9837#if ENABLE_HUSH_CASE
9838 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009839 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009840 case_word = expand_string_to_string(pi->cmds->argv[0],
9841 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009842 debug_printf_exec("CASE word1:'%s'\n", case_word);
9843 //unbackslash(case_word);
9844 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009845 continue;
9846 }
9847 if (rword == RES_MATCH) {
9848 char **argv;
9849
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009850 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009851 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9852 break;
9853 /* all prev words didn't match, does this one match? */
9854 argv = pi->cmds->argv;
9855 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009856 char *pattern;
9857 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9858 pattern = expand_string_to_string(*argv,
9859 EXP_FLAG_ESC_GLOB_CHARS,
9860 /*unbackslash:*/ 0
9861 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009862 /* TODO: which FNM_xxx flags to use? */
9863 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009864 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9865 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009866 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009867 if (cond_code == 0) {
9868 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009869 free(case_word);
9870 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009871 break;
9872 }
9873 argv++;
9874 }
9875 continue;
9876 }
9877 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009878 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009879 if (cond_code != 0)
9880 continue; /* not matched yet, skip this pipe */
9881 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009882 if (rword == RES_ESAC) {
9883 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9884 if (case_word) {
9885 /* "case" did not match anything: still set $? (to 0) */
9886 G.last_exitcode = rcode = EXIT_SUCCESS;
9887 }
9888 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009889#endif
9890 /* Just pressing <enter> in shell should check for jobs.
9891 * OTOH, in non-interactive shell this is useless
9892 * and only leads to extra job checks */
9893 if (pi->num_cmds == 0) {
9894 if (G_interactive_fd)
9895 goto check_jobs_and_continue;
9896 continue;
9897 }
9898
9899 /* After analyzing all keywords and conditions, we decided
9900 * to execute this pipe. NB: have to do checkjobs(NULL)
9901 * after run_pipe to collect any background children,
9902 * even if list execution is to be stopped. */
9903 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009904#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009905 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009906#endif
Denys Vlasenkoe53c7db2021-09-07 02:23:51 +02009907 rcode = r = G.o_opt[OPT_O_NOEXEC] ? 0 : run_pipe(pi);
9908 /* NB: rcode is a smalluint, r is int */
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009909 if (r != -1) {
9910 /* We ran a builtin, function, or group.
9911 * rcode is already known
9912 * and we don't need to wait for anything. */
9913 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9914 G.last_exitcode = rcode;
9915 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009916#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9917 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9918#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009919#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009920 /* Was it "break" or "continue"? */
9921 if (G.flag_break_continue) {
9922 smallint fbc = G.flag_break_continue;
9923 /* We might fall into outer *loop*,
9924 * don't want to break it too */
9925 if (loop_top) {
9926 G.depth_break_continue--;
9927 if (G.depth_break_continue == 0)
9928 G.flag_break_continue = 0;
9929 /* else: e.g. "continue 2" should *break* once, *then* continue */
9930 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9931 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009932 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009933 break;
9934 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009935 /* "continue": simulate end of loop */
9936 rword = RES_DONE;
9937 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009938 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009939#endif
9940 if (G_flag_return_in_progress == 1) {
9941 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9942 break;
9943 }
9944 } else if (pi->followup == PIPE_BG) {
9945 /* What does bash do with attempts to background builtins? */
9946 /* even bash 3.2 doesn't do that well with nested bg:
9947 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9948 * I'm NOT treating inner &'s as jobs */
9949#if ENABLE_HUSH_JOB
9950 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009951 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009952#endif
9953 /* Last command's pid goes to $! */
9954 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009955 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009956 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009957/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009958 rcode = EXIT_SUCCESS;
9959 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009960 } else {
9961#if ENABLE_HUSH_JOB
9962 if (G.run_list_level == 1 && G_interactive_fd) {
9963 /* Waits for completion, then fg's main shell */
9964 rcode = checkjobs_and_fg_shell(pi);
9965 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009966 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009967 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009968#endif
9969 /* This one just waits for completion */
9970 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9971 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9972 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009973 G.last_exitcode = rcode;
9974 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009975#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9976 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9977#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009978 }
9979
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009980 /* Handle "set -e" */
9981 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9982 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9983 if (G.errexit_depth == 0)
9984 hush_exit(rcode);
9985 }
9986 G.errexit_depth = sv_errexit_depth;
9987
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009988 /* Analyze how result affects subsequent commands */
9989#if ENABLE_HUSH_IF
9990 if (rword == RES_IF || rword == RES_ELIF)
9991 cond_code = rcode;
9992#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009993 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009994 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009995 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009996#if ENABLE_HUSH_LOOPS
9997 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009998 if (pi->next
9999 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +020010000 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +020010001 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010002 if (rword == RES_WHILE) {
10003 if (rcode) {
10004 /* "while false; do...done" - exitcode 0 */
10005 G.last_exitcode = rcode = EXIT_SUCCESS;
10006 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +020010007 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010008 }
10009 }
10010 if (rword == RES_UNTIL) {
10011 if (!rcode) {
10012 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010013 break;
10014 }
10015 }
10016 }
10017#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010018 } /* for (pi) */
10019
10020#if ENABLE_HUSH_JOB
10021 G.run_list_level--;
10022#endif
10023#if ENABLE_HUSH_LOOPS
10024 if (loop_top)
10025 G.depth_of_loop--;
10026 free(for_list);
10027#endif
10028#if ENABLE_HUSH_CASE
10029 free(case_word);
10030#endif
10031 debug_leave();
10032 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
10033 return rcode;
10034}
10035
10036/* Select which version we will use */
10037static int run_and_free_list(struct pipe *pi)
10038{
10039 int rcode = 0;
10040 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -080010041 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010042 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
10043 rcode = run_list(pi);
10044 }
10045 /* free_pipe_list has the side effect of clearing memory.
10046 * In the long run that function can be merged with run_list,
10047 * but doing that now would hobble the debugging effort. */
10048 free_pipe_list(pi);
10049 debug_printf_exec("run_and_free_list return %d\n", rcode);
10050 return rcode;
10051}
10052
10053
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010054static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +000010055{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010056 sighandler_t old_handler;
10057 unsigned sig = 0;
10058 while ((mask >>= 1) != 0) {
10059 sig++;
10060 if (!(mask & 1))
10061 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +020010062 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010063 /* POSIX allows shell to re-enable SIGCHLD
10064 * even if it was SIG_IGN on entry.
10065 * Therefore we skip IGN check for it:
10066 */
10067 if (sig == SIGCHLD)
10068 continue;
Denys Vlasenko23bc5622020-02-18 16:46:01 +010010069 /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
10070 * Try:
10071 * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
10072 * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
Denys Vlasenko49e6bf22017-08-04 14:28:16 +020010073 */
Denys Vlasenko23bc5622020-02-18 16:46:01 +010010074 if (sig == SIGHUP && G_interactive_fd)
10075 continue;
10076 /* Unless one of the above signals, is it SIG_IGN? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010077 if (old_handler == SIG_IGN) {
10078 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010079 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010080#if ENABLE_HUSH_TRAP
10081 if (!G_traps)
10082 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10083 free(G_traps[sig]);
10084 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
10085#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010086 }
10087 }
10088}
10089
10090/* Called a few times only (or even once if "sh -c") */
10091static void install_special_sighandlers(void)
10092{
Denis Vlasenkof9375282009-04-05 19:13:39 +000010093 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010094
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010095 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010096 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010097 if (G_interactive_fd) {
10098 mask |= SPECIAL_INTERACTIVE_SIGS;
10099 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010100 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010101 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010102 /* Careful, do not re-install handlers we already installed */
10103 if (G.special_sig_mask != mask) {
10104 unsigned diff = mask & ~G.special_sig_mask;
10105 G.special_sig_mask = mask;
10106 install_sighandlers(diff);
10107 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010108}
10109
10110#if ENABLE_HUSH_JOB
10111/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010112/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010113static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +000010114{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010115 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010116
10117 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010118 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +010010119 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
10120 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010121 + (1 << SIGBUS ) * HUSH_DEBUG
10122 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +010010123 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010124 + (1 << SIGABRT)
10125 /* bash 3.2 seems to handle these just like 'fatal' ones */
10126 + (1 << SIGPIPE)
10127 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010128 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010129 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010130 * we never want to restore pgrp on exit, and this fn is not called
10131 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010132 /*+ (1 << SIGHUP )*/
10133 /*+ (1 << SIGTERM)*/
10134 /*+ (1 << SIGINT )*/
10135 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010136 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010137
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010138 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010139}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000010140#endif
Eric Andersenada18ff2001-05-21 16:18:22 +000010141
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010142static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +000010143{
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010144 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +000010145 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010146 case 'n':
Denys Vlasenkoe53c7db2021-09-07 02:23:51 +020010147 /* set -n has no effect in interactive shell */
10148 /* Try: while set -n; do echo $-; done */
10149 if (!G_interactive_fd)
10150 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010151 break;
10152 case 'x':
10153 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +020010154 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 +010010155 break;
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010156 case 'e':
10157 G.o_opt[OPT_O_ERREXIT] = state;
10158 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010159 case 'o':
10160 if (!o_opt) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010161 /* "set -o" or "set +o" without parameter.
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010162 * in bash, set -o produces this output:
10163 * pipefail off
10164 * and set +o:
10165 * set +o pipefail
10166 * We always use the second form.
10167 */
10168 const char *p = o_opt_strings;
10169 idx = 0;
10170 while (*p) {
10171 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
10172 idx++;
10173 p += strlen(p) + 1;
10174 }
10175 break;
10176 }
10177 idx = index_in_strings(o_opt_strings, o_opt);
10178 if (idx >= 0) {
10179 G.o_opt[idx] = state;
10180 break;
10181 }
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010182 /* fall through to error */
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010183 default:
10184 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +000010185 }
10186 return EXIT_SUCCESS;
10187}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010188
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000010189int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +000010190int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +000010191{
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010192 pid_t cached_getpid;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010193 enum {
10194 OPT_login = (1 << 0),
10195 };
10196 unsigned flags;
Denys Vlasenko63139b52020-12-13 22:00:56 +010010197#if !BB_MMU
10198 unsigned builtin_argc = 0;
10199#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010200 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010201 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010202 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +000010203
Denis Vlasenko574f2f42008-02-27 18:41:59 +000010204 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +020010205 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010206 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010207#if ENABLE_HUSH_TRAP
10208# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010209 G.return_exitcode = -1;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010210# endif
10211 G.pre_trap_exitcode = -1;
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010212#endif
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010213
Denys Vlasenko10c01312011-05-11 11:49:21 +020010214#if ENABLE_HUSH_FAST
10215 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
10216#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010217#if !BB_MMU
10218 G.argv0_for_re_execing = argv[0];
10219#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010220
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010221 cached_getpid = getpid(); /* for tcsetpgrp() during init */
Denys Vlasenko46a71dc2020-12-25 18:49:29 +010010222 G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
10223 G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010224
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010225 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010226 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
10227 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010228 shell_ver = xzalloc(sizeof(*shell_ver));
10229 shell_ver->flg_export = 1;
10230 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +020010231 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +020010232 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010233 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010234
Denys Vlasenko605067b2010-09-06 12:10:51 +020010235 /* Create shell local variables from the values
10236 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010237 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010238 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010239 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010240 if (e) while (*e) {
10241 char *value = strchr(*e, '=');
10242 if (value) { /* paranoia */
10243 cur_var->next = xzalloc(sizeof(*cur_var));
10244 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +000010245 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010246 cur_var->max_len = strlen(*e);
10247 cur_var->flg_export = 1;
10248 }
10249 e++;
10250 }
Denys Vlasenko605067b2010-09-06 12:10:51 +020010251 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010252 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
10253 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +020010254
10255 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010256 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010257
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010258#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010259 /* Set (but not export) HOSTNAME unless already set */
10260 if (!get_local_var_value("HOSTNAME")) {
10261 struct utsname uts;
10262 uname(&uts);
10263 set_local_var_from_halves("HOSTNAME", uts.nodename);
10264 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +020010265#endif
10266 /* IFS is not inherited from the parent environment */
10267 set_local_var_from_halves("IFS", defifs);
10268
Denys Vlasenkoef8985c2019-05-19 16:29:09 +020010269 if (!get_local_var_value("PATH"))
10270 set_local_var_from_halves("PATH", bb_default_root_path);
10271
Denys Vlasenko0c360192019-05-19 15:37:50 +020010272 /* PS1/PS2 are set later, if we determine that we are interactive */
10273
Denys Vlasenko6db47842009-09-05 20:15:17 +020010274 /* bash also exports SHLVL and _,
10275 * and sets (but doesn't export) the following variables:
10276 * BASH=/bin/bash
10277 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
10278 * BASH_VERSION='3.2.0(1)-release'
10279 * HOSTTYPE=i386
10280 * MACHTYPE=i386-pc-linux-gnu
10281 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +020010282 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +020010283 * EUID=<NNNNN>
10284 * UID=<NNNNN>
10285 * GROUPS=()
10286 * LINES=<NNN>
10287 * COLUMNS=<NNN>
10288 * BASH_ARGC=()
10289 * BASH_ARGV=()
10290 * BASH_LINENO=()
10291 * BASH_SOURCE=()
10292 * DIRSTACK=()
10293 * PIPESTATUS=([0]="0")
10294 * HISTFILE=/<xxx>/.bash_history
10295 * HISTFILESIZE=500
10296 * HISTSIZE=500
10297 * MAILCHECK=60
10298 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
10299 * SHELL=/bin/bash
10300 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
10301 * TERM=dumb
10302 * OPTERR=1
10303 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +020010304 * PS4='+ '
10305 */
10306
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010307#if NUM_SCRIPTS > 0
10308 if (argc < 0) {
10309 char *script = get_script_content(-argc - 1);
10310 G.global_argv = argv;
10311 G.global_argc = string_array_len(argv);
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010312 //install_special_sighandlers(); - needed?
10313 parse_and_run_string(script);
10314 goto final_return;
10315 }
10316#endif
10317
Eric Andersen94ac2442001-05-22 19:05:18 +000010318 /* Initialize some more globals to non-zero values */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010319 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +000010320
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010321 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010322 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010323 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010324 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010325 * in order to intercept (more) signals.
10326 */
10327
10328 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010329 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010330 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010331 while (1) {
Denys Vlasenko3b053052021-01-04 03:05:34 +010010332 int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
10333 "cexinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010334#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +000010335 "<:$:R:V:"
10336# if ENABLE_HUSH_FUNCTIONS
10337 "F:"
10338# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010339#endif
10340 );
10341 if (opt <= 0)
10342 break;
Eric Andersen25f27032001-04-26 23:22:31 +000010343 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010344 case 'c':
Denys Vlasenko0ab2dd42020-12-23 02:22:08 +010010345 /* Note: -c is not an option with param!
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010346 * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010347 */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010348 G.opt_c = 1;
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010349 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010350 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010351 /* Well, we cannot just declare interactiveness,
10352 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010353 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010354 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010355 case 's':
Denys Vlasenkof3634582019-06-03 12:21:04 +020010356 G.opt_s = 1;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010357 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010358 case 'l':
10359 flags |= OPT_login;
10360 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010361#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010362 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010363 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010364 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010365 case '$': {
10366 unsigned long long empty_trap_mask;
10367
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010368 G.root_pid = bb_strtou(optarg, &optarg, 16);
10369 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010370 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10371 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010372 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10373 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010374 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010375 optarg++;
10376 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010377 optarg++;
10378 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10379 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010380 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010381 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010382# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010383 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010384 for (sig = 1; sig < NSIG; sig++) {
10385 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010386 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010387 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010388 }
10389 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010390# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010391 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010392# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010393 optarg++;
10394 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010395# endif
Denys Vlasenko49142d42020-12-13 18:44:07 +010010396 /* Suppress "killed by signal" message, -$ hack is used
10397 * for subshells: echo `sh -c 'kill -9 $$'`
10398 * should be silent.
10399 */
10400 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010401# if ENABLE_HUSH_FUNCTIONS
10402 /* nommu uses re-exec trick for "... | func | ...",
10403 * should allow "return".
10404 * This accidentally allows returns in subshells.
10405 */
10406 G_flag_return_in_progress = -1;
10407# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010408 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010409 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010410 case 'R':
10411 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010412 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010413 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010414# if ENABLE_HUSH_FUNCTIONS
10415 case 'F': {
10416 struct function *funcp = new_function(optarg);
10417 /* funcp->name is already set to optarg */
10418 /* funcp->body is set to NULL. It's a special case. */
10419 funcp->body_as_string = argv[optind];
10420 optind++;
10421 break;
10422 }
10423# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010424#endif
Denys Vlasenko3b053052021-01-04 03:05:34 +010010425 /*case '?': invalid option encountered (set_mode('?') will fail) */
10426 /*case 'n':*/
10427 /*case 'x':*/
10428 /*case 'e':*/
10429 default:
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010430 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010431 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010432 bb_show_usage();
Eric Andersen25f27032001-04-26 23:22:31 +000010433 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010434 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010435
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010436 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10437 G.global_argc = argc - (optind - 1);
10438 G.global_argv = argv + (optind - 1);
10439 G.global_argv[0] = argv[0];
10440
Denis Vlasenkof9375282009-04-05 19:13:39 +000010441 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010442 if (flags & OPT_login) {
Denys Vlasenko63139b52020-12-13 22:00:56 +010010443 const char *hp = NULL;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010444 HFILE *input;
Denys Vlasenko63139b52020-12-13 22:00:56 +010010445
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010446 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010447 input = hfopen("/etc/profile");
Denys Vlasenko63139b52020-12-13 22:00:56 +010010448 run_profile:
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010449 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010450 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010451 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010452 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010453 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010454 /* bash: after sourcing /etc/profile,
10455 * tries to source (in the given order):
10456 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010457 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010458 * bash also sources ~/.bash_logout on exit.
10459 * If called as sh, skips .bash_XXX files.
10460 */
Denys Vlasenko63139b52020-12-13 22:00:56 +010010461 if (!hp) { /* unless we looped on the "goto" already */
10462 hp = get_local_var_value("HOME");
10463 if (hp && hp[0]) {
10464 debug_printf("sourcing ~/.profile\n");
10465 hp = concat_path_file(hp, ".profile");
10466 input = hfopen(hp);
10467 free((char*)hp);
10468 goto run_profile;
10469 }
10470 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010471 }
10472
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010473 /* -c takes effect *after* -l */
10474 if (G.opt_c) {
10475 /* Possibilities:
10476 * sh ... -c 'script'
10477 * sh ... -c 'script' ARG0 [ARG1...]
10478 * On NOMMU, if builtin_argc != 0,
10479 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
10480 * "" needs to be replaced with NULL
10481 * and BARGV vector fed to builtin function.
10482 * Note: the form without ARG0 never happens:
10483 * sh ... -c 'builtin' BARGV... ""
10484 */
10485 char *script;
10486
10487 install_special_sighandlers();
10488
10489 G.global_argc--;
10490 G.global_argv++;
Denys Vlasenko49142d42020-12-13 18:44:07 +010010491#if !BB_MMU
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010492 if (builtin_argc) {
10493 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10494 const struct built_in_command *x;
10495 x = find_builtin(G.global_argv[0]);
10496 if (x) { /* paranoia */
10497 argv = G.global_argv;
10498 G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
10499 G.global_argv += builtin_argc + 1;
10500 G.global_argv[-1] = NULL; /* replace "" */
10501 G.last_exitcode = x->b_function(argv);
10502 }
10503 goto final_return;
10504 }
Denys Vlasenko49142d42020-12-13 18:44:07 +010010505#endif
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010506
10507 script = G.global_argv[0];
10508 if (!script)
10509 bb_error_msg_and_die(bb_msg_requires_arg, "-c");
10510 if (!G.global_argv[1]) {
10511 /* -c 'script' (no params): prevent empty $0 */
10512 G.global_argv[0] = argv[0];
10513 } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
10514 G.global_argc--;
10515 G.global_argv++;
10516 }
10517 parse_and_run_string(script);
10518 goto final_return;
10519 }
10520
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010521 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010522 if (!G.opt_s && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010523 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010524 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010525 * "bash <script>" (which is never interactive (unless -i?))
10526 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010527 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010528 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010529 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010530 G.global_argc--;
10531 G.global_argv++;
10532 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010533 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010534 input = hfopen(G.global_argv[0]);
10535 if (!input) {
10536 bb_simple_perror_msg_and_die(G.global_argv[0]);
10537 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010538 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010539 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010540 parse_and_run_file(input);
10541#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010542 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010543#endif
10544 goto final_return;
10545 }
Denys Vlasenkof3634582019-06-03 12:21:04 +020010546 /* "implicit" -s: bare interactive hush shows 's' in $- */
Denys Vlasenkod8740b22019-05-19 19:11:21 +020010547 G.opt_s = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010548
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010549 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010550 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010551 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010552
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010553 /* A shell is interactive if the '-i' flag was given,
10554 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010555 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010556 * no arguments remaining or the -s flag given
10557 * standard input is a terminal
10558 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010559 * Refer to Posix.2, the description of the 'sh' utility.
10560 */
10561#if ENABLE_HUSH_JOB
10562 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010563 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10564 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10565 if (G_saved_tty_pgrp < 0)
10566 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010567
10568 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010569 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010570 if (G_interactive_fd < 0) {
10571 /* try to dup to any fd */
10572 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010573 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010574 /* give up */
10575 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010576 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010577 }
10578 }
Eric Andersen25f27032001-04-26 23:22:31 +000010579 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010580 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010581 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010582 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010583
Mike Frysinger38478a62009-05-20 04:48:06 -040010584 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010585 /* If we were run as 'hush &', sleep until we are
10586 * in the foreground (tty pgrp == our pgrp).
10587 * If we get started under a job aware app (like bash),
10588 * make sure we are now in charge so we don't fight over
10589 * who gets the foreground */
10590 while (1) {
10591 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010592 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10593 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010594 break;
10595 /* send TTIN to ourself (should stop us) */
10596 kill(- shell_pgrp, SIGTTIN);
10597 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010598 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010599
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010600 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010601 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010602
Mike Frysinger38478a62009-05-20 04:48:06 -040010603 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010604 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010605 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010606 /* Put ourselves in our own process group
10607 * (bash, too, does this only if ctty is available) */
10608 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10609 /* Grab control of the terminal */
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010610 tcsetpgrp(G_interactive_fd, cached_getpid);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010611 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010612 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010613
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010614# if ENABLE_FEATURE_EDITING
10615 G.line_input_state = new_line_input_t(FOR_SHELL);
Ron Yorston9e2a5662020-01-21 16:01:58 +000010616# if EDITING_HAS_get_exe_name
10617 G.line_input_state->get_exe_name = get_builtin_name;
10618# endif
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010619# endif
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010620# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10621 {
10622 const char *hp = get_local_var_value("HISTFILE");
10623 if (!hp) {
10624 hp = get_local_var_value("HOME");
10625 if (hp)
10626 hp = concat_path_file(hp, ".hush_history");
10627 } else {
10628 hp = xstrdup(hp);
10629 }
10630 if (hp) {
10631 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010632 //set_local_var(xasprintf("HISTFILE=%s", ...));
10633 }
10634# if ENABLE_FEATURE_SH_HISTFILESIZE
10635 hp = get_local_var_value("HISTFILESIZE");
10636 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10637# endif
10638 }
10639# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010640 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010641 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010642 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010643#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010644 /* No job control compiled in, only prompt/line editing */
10645 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010646 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010647 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010648 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010649 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010650 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010651 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010652 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010653 }
10654 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010655 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010656 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010657 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010658 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010659#else
10660 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010661 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010662#endif
10663 /* bash:
10664 * if interactive but not a login shell, sources ~/.bashrc
10665 * (--norc turns this off, --rcfile <file> overrides)
10666 */
10667
Denys Vlasenko0c360192019-05-19 15:37:50 +020010668 if (G_interactive_fd) {
10669#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
10670 /* Set (but not export) PS1/2 unless already set */
10671 if (!get_local_var_value("PS1"))
10672 set_local_var_from_halves("PS1", "\\w \\$ ");
10673 if (!get_local_var_value("PS2"))
10674 set_local_var_from_halves("PS2", "> ");
10675#endif
10676 if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
10677 /* note: ash and hush share this string */
10678 printf("\n\n%s %s\n"
10679 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10680 "\n",
10681 bb_banner,
10682 "hush - the humble shell"
10683 );
10684 }
Mike Frysingerb2705e12009-03-23 08:44:02 +000010685 }
10686
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010687 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010688
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010689 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010690 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010691}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010692
10693
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010694/*
10695 * Built-ins
10696 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010697static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010698{
10699 return 0;
10700}
10701
Denys Vlasenko265062d2017-01-10 15:13:30 +010010702#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenkoa8e19602020-12-14 03:52:54 +010010703static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010704{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010705 int argc = string_array_len(argv);
10706 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010707}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010708#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010709#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010710static int FAST_FUNC builtin_test(char **argv)
10711{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010712 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010713}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010714#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010715#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010716static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010717{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010718 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010719}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010720#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010721#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010722static int FAST_FUNC builtin_printf(char **argv)
10723{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010724 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010725}
10726#endif
10727
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010728#if ENABLE_HUSH_HELP
10729static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10730{
10731 const struct built_in_command *x;
10732
10733 printf(
10734 "Built-in commands:\n"
10735 "------------------\n");
10736 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10737 if (x->b_descr)
10738 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10739 }
10740 return EXIT_SUCCESS;
10741}
10742#endif
10743
10744#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10745static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10746{
Ron Yorston9f3b4102019-12-16 09:31:10 +000010747 show_history(G.line_input_state);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010748 return EXIT_SUCCESS;
10749}
10750#endif
10751
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010752static char **skip_dash_dash(char **argv)
10753{
10754 argv++;
10755 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10756 argv++;
10757 return argv;
10758}
10759
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010760static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010761{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010762 const char *newdir;
10763
10764 argv = skip_dash_dash(argv);
10765 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010766 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010767 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010768 * bash says "bash: cd: HOME not set" and does nothing
10769 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010770 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010771 const char *home = get_local_var_value("HOME");
10772 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010773 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010774 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010775 /* Mimic bash message exactly */
10776 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010777 return EXIT_FAILURE;
10778 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010779 /* Read current dir (get_cwd(1) is inside) and set PWD.
10780 * Note: do not enforce exporting. If PWD was unset or unexported,
10781 * set it again, but do not export. bash does the same.
10782 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010783 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010784 return EXIT_SUCCESS;
10785}
10786
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010787static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10788{
10789 puts(get_cwd(0));
10790 return EXIT_SUCCESS;
10791}
10792
10793static int FAST_FUNC builtin_eval(char **argv)
10794{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010795 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010796
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010797 if (!argv[0])
10798 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010799
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010800 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010801 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010802 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010803 /* bash:
10804 * eval "echo Hi; done" ("done" is syntax error):
10805 * "echo Hi" will not execute too.
10806 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010807 parse_and_run_string(argv[0]);
10808 } else {
10809 /* "The eval utility shall construct a command by
10810 * concatenating arguments together, separating
10811 * each with a <space> character."
10812 */
10813 char *str, *p;
10814 unsigned len = 0;
10815 char **pp = argv;
10816 do
10817 len += strlen(*pp) + 1;
10818 while (*++pp);
10819 str = p = xmalloc(len);
10820 pp = argv;
10821 for (;;) {
10822 p = stpcpy(p, *pp);
10823 pp++;
10824 if (!*pp)
10825 break;
10826 *p++ = ' ';
10827 }
10828 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010829 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010830 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010831 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010832 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010833 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010834}
10835
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010836static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010837{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010838 argv = skip_dash_dash(argv);
10839 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010840 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010841
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010842 /* Careful: we can end up here after [v]fork. Do not restore
10843 * tty pgrp then, only top-level shell process does that */
10844 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10845 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10846
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010847 /* Saved-redirect fds, script fds and G_interactive_fd are still
10848 * open here. However, they are all CLOEXEC, and execv below
10849 * closes them. Try interactive "exec ls -l /proc/self/fd",
10850 * it should show no extra open fds in the "ls" process.
10851 * If we'd try to run builtins/NOEXECs, this would need improving.
10852 */
10853 //close_saved_fds_and_FILE_fds();
10854
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010855 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010856 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010857 * and tcsetpgrp, and this is inherently racy.
10858 */
10859 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010860}
10861
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010862static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010863{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010864 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010865
10866 /* interactive bash:
10867 * # trap "echo EEE" EXIT
10868 * # exit
10869 * exit
10870 * There are stopped jobs.
10871 * (if there are _stopped_ jobs, running ones don't count)
10872 * # exit
10873 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010874 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010875 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010876 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010877 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010878
10879 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010880 argv = skip_dash_dash(argv);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010881 if (argv[0] == NULL) {
10882#if ENABLE_HUSH_TRAP
10883 if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
10884 hush_exit(G.pre_trap_exitcode);
10885#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010886 hush_exit(G.last_exitcode);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010887 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010888 /* mimic bash: exit 123abc == exit 255 + error msg */
10889 xfunc_error_retval = 255;
10890 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010891 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010892}
10893
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010894#if ENABLE_HUSH_TYPE
10895/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10896static int FAST_FUNC builtin_type(char **argv)
10897{
10898 int ret = EXIT_SUCCESS;
10899
10900 while (*++argv) {
10901 const char *type;
10902 char *path = NULL;
10903
10904 if (0) {} /* make conditional compile easier below */
10905 /*else if (find_alias(*argv))
10906 type = "an alias";*/
Denys Vlasenko259747c2019-11-28 10:28:14 +010010907# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010908 else if (find_function(*argv))
10909 type = "a function";
Denys Vlasenko259747c2019-11-28 10:28:14 +010010910# endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010911 else if (find_builtin(*argv))
10912 type = "a shell builtin";
10913 else if ((path = find_in_path(*argv)) != NULL)
10914 type = path;
10915 else {
10916 bb_error_msg("type: %s: not found", *argv);
10917 ret = EXIT_FAILURE;
10918 continue;
10919 }
10920
10921 printf("%s is %s\n", *argv, type);
10922 free(path);
10923 }
10924
10925 return ret;
10926}
10927#endif
10928
10929#if ENABLE_HUSH_READ
10930/* Interruptibility of read builtin in bash
10931 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10932 *
10933 * Empty trap makes read ignore corresponding signal, for any signal.
10934 *
10935 * SIGINT:
10936 * - terminates non-interactive shell;
10937 * - interrupts read in interactive shell;
10938 * if it has non-empty trap:
10939 * - executes trap and returns to command prompt in interactive shell;
10940 * - executes trap and returns to read in non-interactive shell;
10941 * SIGTERM:
10942 * - is ignored (does not interrupt) read in interactive shell;
10943 * - terminates non-interactive shell;
10944 * if it has non-empty trap:
10945 * - executes trap and returns to read;
10946 * SIGHUP:
10947 * - terminates shell (regardless of interactivity);
10948 * if it has non-empty trap:
10949 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010950 * SIGCHLD from children:
10951 * - does not interrupt read regardless of interactivity:
10952 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010953 */
10954static int FAST_FUNC builtin_read(char **argv)
10955{
10956 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010957 struct builtin_read_params params;
10958
10959 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010960
10961 /* "!": do not abort on errors.
10962 * Option string must start with "sr" to match BUILTIN_READ_xxx
10963 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010964 params.read_flags = getopt32(argv,
Denys Vlasenko259747c2019-11-28 10:28:14 +010010965# if BASH_READ_D
Denys Vlasenko457825f2021-06-06 12:07:11 +020010966 IF_NOT_HUSH_BASH_COMPAT("^")
10967 "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
10968 &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko259747c2019-11-28 10:28:14 +010010969# else
Denys Vlasenko457825f2021-06-06 12:07:11 +020010970 IF_NOT_HUSH_BASH_COMPAT("^")
10971 "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
10972 &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko259747c2019-11-28 10:28:14 +010010973# endif
Denys Vlasenko457825f2021-06-06 12:07:11 +020010974//TODO: print "read: need variable name"
10975//for the case of !BASH "read" with no args (now it fails silently)
10976//(or maybe extend getopt32() to emit a message if "-1" fails)
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010977 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010978 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010979 return EXIT_FAILURE;
10980 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010981 params.argv = argv;
10982 params.setvar = set_local_var_from_halves;
10983 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010984
10985 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010986 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010987
10988 if ((uintptr_t)r == 1 && errno == EINTR) {
10989 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010990 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010991 goto again;
10992 }
10993
10994 if ((uintptr_t)r > 1) {
James Byrne69374872019-07-02 11:35:03 +020010995 bb_simple_error_msg(r);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010996 r = (char*)(uintptr_t)1;
10997 }
10998
10999 return (uintptr_t)r;
11000}
11001#endif
11002
11003#if ENABLE_HUSH_UMASK
11004static int FAST_FUNC builtin_umask(char **argv)
11005{
11006 int rc;
11007 mode_t mask;
11008
11009 rc = 1;
11010 mask = umask(0);
11011 argv = skip_dash_dash(argv);
11012 if (argv[0]) {
11013 mode_t old_mask = mask;
11014
11015 /* numeric umasks are taken as-is */
11016 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
11017 if (!isdigit(argv[0][0]))
11018 mask ^= 0777;
11019 mask = bb_parse_mode(argv[0], mask);
11020 if (!isdigit(argv[0][0]))
11021 mask ^= 0777;
11022 if ((unsigned)mask > 0777) {
11023 mask = old_mask;
11024 /* bash messages:
11025 * bash: umask: 'q': invalid symbolic mode operator
11026 * bash: umask: 999: octal number out of range
11027 */
11028 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
11029 rc = 0;
11030 }
11031 } else {
11032 /* Mimic bash */
11033 printf("%04o\n", (unsigned) mask);
11034 /* fall through and restore mask which we set to 0 */
11035 }
11036 umask(mask);
11037
11038 return !rc; /* rc != 0 - success */
11039}
11040#endif
11041
Denys Vlasenko41ade052017-01-08 18:56:24 +010011042#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011043static void print_escaped(const char *s)
11044{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020011045 if (*s == '\'')
11046 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011047 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020011048 const char *p = strchrnul(s, '\'');
11049 /* print 'xxxx', possibly just '' */
11050 printf("'%.*s'", (int)(p - s), s);
11051 if (*p == '\0')
11052 break;
11053 s = p;
11054 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011055 /* s points to '; print "'''...'''" */
11056 putchar('"');
11057 do putchar('\''); while (*++s == '\'');
11058 putchar('"');
11059 } while (*s);
11060}
Denys Vlasenko41ade052017-01-08 18:56:24 +010011061#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011062
Denys Vlasenko1e660422017-07-17 21:10:50 +020011063#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011064static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020011065{
11066 do {
11067 char *name = *argv;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020011068 const char *name_end = endofname(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011069
Denys Vlasenko27c56f12010-09-07 09:56:34 +020011070 if (*name_end == '\0') {
11071 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020011072
Denys Vlasenko27c56f12010-09-07 09:56:34 +020011073 vpp = get_ptr_to_local_var(name, name_end - name);
11074 var = vpp ? *vpp : NULL;
11075
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011076 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020011077 /* export -n NAME (without =VALUE) */
11078 if (var) {
11079 var->flg_export = 0;
11080 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
11081 unsetenv(name);
11082 } /* else: export -n NOT_EXISTING_VAR: no-op */
11083 continue;
11084 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011085 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020011086 /* export NAME (without =VALUE) */
11087 if (var) {
11088 var->flg_export = 1;
11089 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
11090 putenv(var->varstr);
11091 continue;
11092 }
11093 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020011094 if (flags & SETFLAG_MAKE_RO) {
11095 /* readonly NAME (without =VALUE) */
11096 if (var) {
11097 var->flg_read_only = 1;
11098 continue;
11099 }
11100 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011101# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020011102 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011103 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020011104 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
11105 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020011106 /* "local x=abc; ...; local x" - ignore second local decl */
11107 continue;
11108 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011109 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011110# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020011111 /* Exporting non-existing variable.
11112 * bash does not put it in environment,
11113 * but remembers that it is exported,
11114 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020011115 * We just set it to "" and export.
11116 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020011117 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020011118 * bash sets the value to "".
11119 */
11120 /* Or, it's "readonly NAME" (without =VALUE).
11121 * bash remembers NAME and disallows its creation
11122 * in the future.
11123 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020011124 name = xasprintf("%s=", name);
11125 } else {
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020011126 if (*name_end != '=') {
11127 bb_error_msg("'%s': bad variable name", name);
11128 /* do not parse following argv[]s: */
11129 return 1;
11130 }
Denys Vlasenko295fef82009-06-03 12:47:26 +020011131 /* (Un)exporting/making local NAME=VALUE */
11132 name = xstrdup(name);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020011133 /* Testcase: export PS1='\w \$ ' */
11134 unbackslash(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011135 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020011136 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020011137 if (set_local_var(name, flags))
11138 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020011139 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020011140 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020011141}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011142#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020011143
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011144#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011145static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011146{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000011147 unsigned opt_unexport;
11148
Denys Vlasenko259747c2019-11-28 10:28:14 +010011149# if ENABLE_HUSH_EXPORT_N
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020011150 /* "!": do not abort on errors */
11151 opt_unexport = getopt32(argv, "!n");
11152 if (opt_unexport == (uint32_t)-1)
11153 return EXIT_FAILURE;
11154 argv += optind;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011155# else
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020011156 opt_unexport = 0;
11157 argv++;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011158# endif
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020011159
11160 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011161 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011162 if (e) {
11163 while (*e) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010011164# if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011165 puts(*e++);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011166# else
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011167 /* ash emits: export VAR='VAL'
11168 * bash: declare -x VAR="VAL"
11169 * we follow ash example */
11170 const char *s = *e++;
11171 const char *p = strchr(s, '=');
11172
11173 if (!p) /* wtf? take next variable */
11174 continue;
11175 /* export var= */
11176 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011177 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011178 putchar('\n');
Denys Vlasenko259747c2019-11-28 10:28:14 +010011179# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011180 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011181 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011182 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011183 return EXIT_SUCCESS;
11184 }
11185
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011186 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011187}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011188#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011189
Denys Vlasenko295fef82009-06-03 12:47:26 +020011190#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011191static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020011192{
11193 if (G.func_nest_level == 0) {
11194 bb_error_msg("%s: not in a function", argv[0]);
11195 return EXIT_FAILURE; /* bash compat */
11196 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020011197 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020011198 /* Since all builtins run in a nested variable level,
11199 * need to use level - 1 here. Or else the variable will be removed at once
11200 * after builtin returns.
11201 */
11202 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011203}
11204#endif
11205
Denys Vlasenko1e660422017-07-17 21:10:50 +020011206#if ENABLE_HUSH_READONLY
11207static int FAST_FUNC builtin_readonly(char **argv)
11208{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011209 argv++;
11210 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020011211 /* bash: readonly [-p]: list all readonly VARs
11212 * (-p has no effect in bash)
11213 */
11214 struct variable *e;
11215 for (e = G.top_var; e; e = e->next) {
11216 if (e->flg_read_only) {
11217//TODO: quote value: readonly VAR='VAL'
11218 printf("readonly %s\n", e->varstr);
11219 }
11220 }
11221 return EXIT_SUCCESS;
11222 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011223 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020011224}
11225#endif
11226
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011227#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011228/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
11229static int FAST_FUNC builtin_unset(char **argv)
11230{
11231 int ret;
11232 unsigned opts;
11233
11234 /* "!": do not abort on errors */
11235 /* "+": stop at 1st non-option */
11236 opts = getopt32(argv, "!+vf");
11237 if (opts == (unsigned)-1)
11238 return EXIT_FAILURE;
11239 if (opts == 3) {
James Byrne69374872019-07-02 11:35:03 +020011240 bb_simple_error_msg("unset: -v and -f are exclusive");
Denys Vlasenko61508d92016-10-02 21:12:02 +020011241 return EXIT_FAILURE;
11242 }
11243 argv += optind;
11244
11245 ret = EXIT_SUCCESS;
11246 while (*argv) {
11247 if (!(opts & 2)) { /* not -f */
11248 if (unset_local_var(*argv)) {
11249 /* unset <nonexistent_var> doesn't fail.
11250 * Error is when one tries to unset RO var.
11251 * Message was printed by unset_local_var. */
11252 ret = EXIT_FAILURE;
11253 }
11254 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011255# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020011256 else {
11257 unset_func(*argv);
11258 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011259# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011260 argv++;
11261 }
11262 return ret;
11263}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011264#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011265
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011266#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011267/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
11268 * built-in 'set' handler
11269 * SUSv3 says:
11270 * set [-abCefhmnuvx] [-o option] [argument...]
11271 * set [+abCefhmnuvx] [+o option] [argument...]
11272 * set -- [argument...]
11273 * set -o
11274 * set +o
11275 * Implementations shall support the options in both their hyphen and
11276 * plus-sign forms. These options can also be specified as options to sh.
11277 * Examples:
11278 * Write out all variables and their values: set
11279 * Set $1, $2, and $3 and set "$#" to 3: set c a b
11280 * Turn on the -x and -v options: set -xv
11281 * Unset all positional parameters: set --
11282 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
11283 * Set the positional parameters to the expansion of x, even if x expands
11284 * with a leading '-' or '+': set -- $x
11285 *
11286 * So far, we only support "set -- [argument...]" and some of the short names.
11287 */
11288static int FAST_FUNC builtin_set(char **argv)
11289{
11290 int n;
11291 char **pp, **g_argv;
11292 char *arg = *++argv;
11293
11294 if (arg == NULL) {
11295 struct variable *e;
11296 for (e = G.top_var; e; e = e->next)
11297 puts(e->varstr);
11298 return EXIT_SUCCESS;
11299 }
11300
11301 do {
11302 if (strcmp(arg, "--") == 0) {
11303 ++argv;
11304 goto set_argv;
11305 }
11306 if (arg[0] != '+' && arg[0] != '-')
11307 break;
11308 for (n = 1; arg[n]; ++n) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020011309 if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
11310 bb_error_msg("%s: %s: invalid option", "set", arg);
11311 return EXIT_FAILURE;
11312 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011313 if (arg[n] == 'o' && argv[1])
11314 argv++;
11315 }
11316 } while ((arg = *++argv) != NULL);
11317 /* Now argv[0] is 1st argument */
11318
11319 if (arg == NULL)
11320 return EXIT_SUCCESS;
11321 set_argv:
11322
11323 /* NB: G.global_argv[0] ($0) is never freed/changed */
11324 g_argv = G.global_argv;
11325 if (G.global_args_malloced) {
11326 pp = g_argv;
11327 while (*++pp)
11328 free(*pp);
11329 g_argv[1] = NULL;
11330 } else {
11331 G.global_args_malloced = 1;
11332 pp = xzalloc(sizeof(pp[0]) * 2);
11333 pp[0] = g_argv[0]; /* retain $0 */
11334 g_argv = pp;
11335 }
11336 /* This realloc's G.global_argv */
11337 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
11338
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020011339 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020011340
11341 return EXIT_SUCCESS;
Denys Vlasenko61508d92016-10-02 21:12:02 +020011342}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011343#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011344
11345static int FAST_FUNC builtin_shift(char **argv)
11346{
11347 int n = 1;
11348 argv = skip_dash_dash(argv);
11349 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020011350 n = bb_strtou(argv[0], NULL, 10);
11351 if (errno || n < 0) {
11352 /* shared string with ash.c */
11353 bb_error_msg("Illegal number: %s", argv[0]);
11354 /*
11355 * ash aborts in this case.
11356 * bash prints error message and set $? to 1.
11357 * Interestingly, for "shift 99999" bash does not
11358 * print error message, but does set $? to 1
11359 * (and does no shifting at all).
11360 */
11361 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011362 }
11363 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010011364 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020011365 int m = 1;
11366 while (m <= n)
11367 free(G.global_argv[m++]);
11368 }
11369 G.global_argc -= n;
11370 memmove(&G.global_argv[1], &G.global_argv[n+1],
11371 G.global_argc * sizeof(G.global_argv[0]));
11372 return EXIT_SUCCESS;
11373 }
11374 return EXIT_FAILURE;
11375}
11376
Denys Vlasenko74d40582017-08-11 01:32:46 +020011377#if ENABLE_HUSH_GETOPTS
11378static int FAST_FUNC builtin_getopts(char **argv)
11379{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011380/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11381
Denys Vlasenko74d40582017-08-11 01:32:46 +020011382TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011383If a required argument is not found, and getopts is not silent,
11384a question mark (?) is placed in VAR, OPTARG is unset, and a
11385diagnostic message is printed. If getopts is silent, then a
11386colon (:) is placed in VAR and OPTARG is set to the option
11387character found.
11388
11389Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011390
11391"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011392*/
11393 char cbuf[2];
11394 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011395 int c, n, exitcode, my_opterr;
11396 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011397
11398 optstring = *++argv;
11399 if (!optstring || !(var = *++argv)) {
James Byrne69374872019-07-02 11:35:03 +020011400 bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
Denys Vlasenko74d40582017-08-11 01:32:46 +020011401 return EXIT_FAILURE;
11402 }
11403
Denys Vlasenko238ff982017-08-29 13:38:30 +020011404 if (argv[1])
11405 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11406 else
11407 argv = G.global_argv;
11408 cbuf[1] = '\0';
11409
11410 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011411 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011412 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011413 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011414 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011415 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011416
11417 /* getopts stops on first non-option. Add "+" to force that */
11418 /*if (optstring[0] != '+')*/ {
11419 char *s = alloca(strlen(optstring) + 2);
11420 sprintf(s, "+%s", optstring);
11421 optstring = s;
11422 }
11423
Denys Vlasenko238ff982017-08-29 13:38:30 +020011424 /* Naively, now we should just
11425 * cp = get_local_var_value("OPTIND");
11426 * optind = cp ? atoi(cp) : 0;
11427 * optarg = NULL;
11428 * opterr = my_opterr;
11429 * c = getopt(string_array_len(argv), argv, optstring);
11430 * and be done? Not so fast...
11431 * Unlike normal getopt() usage in C programs, here
11432 * each successive call will (usually) have the same argv[] CONTENTS,
11433 * but not the ADDRESSES. Worse yet, it's possible that between
11434 * invocations of "getopts", there will be calls to shell builtins
11435 * which use getopt() internally. Example:
11436 * while getopts "abc" RES -a -bc -abc de; do
11437 * unset -ff func
11438 * done
11439 * This would not work correctly: getopt() call inside "unset"
11440 * modifies internal libc state which is tracking position in
11441 * multi-option strings ("-abc"). At best, it can skip options
11442 * or return the same option infinitely. With glibc implementation
11443 * of getopt(), it would use outright invalid pointers and return
11444 * garbage even _without_ "unset" mangling internal state.
11445 *
11446 * We resort to resetting getopt() state and calling it N times,
11447 * until we get Nth result (or failure).
11448 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11449 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011450 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011451 count = 0;
11452 n = string_array_len(argv);
11453 do {
11454 optarg = NULL;
11455 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11456 c = getopt(n, argv, optstring);
11457 if (c < 0)
11458 break;
11459 count++;
11460 } while (count <= G.getopt_count);
11461
11462 /* Set OPTIND. Prevent resetting of the magic counter! */
11463 set_local_var_from_halves("OPTIND", utoa(optind));
11464 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011465 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011466
11467 /* Set OPTARG */
11468 /* Always set or unset, never left as-is, even on exit/error:
11469 * "If no option was found, or if the option that was found
11470 * does not have an option-argument, OPTARG shall be unset."
11471 */
11472 cp = optarg;
11473 if (c == '?') {
11474 /* If ":optstring" and unknown option is seen,
11475 * it is stored to OPTARG.
11476 */
11477 if (optstring[1] == ':') {
11478 cbuf[0] = optopt;
11479 cp = cbuf;
11480 }
11481 }
11482 if (cp)
11483 set_local_var_from_halves("OPTARG", cp);
11484 else
11485 unset_local_var("OPTARG");
11486
11487 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011488 exitcode = EXIT_SUCCESS;
11489 if (c < 0) { /* -1: end of options */
11490 exitcode = EXIT_FAILURE;
11491 c = '?';
11492 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011493
Denys Vlasenko238ff982017-08-29 13:38:30 +020011494 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011495 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011496 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011497
Denys Vlasenko74d40582017-08-11 01:32:46 +020011498 return exitcode;
11499}
11500#endif
11501
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011502static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011503{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011504 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011505 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011506 save_arg_t sv;
11507 char *args_need_save;
11508#if ENABLE_HUSH_FUNCTIONS
11509 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011510#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011511
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011512 argv = skip_dash_dash(argv);
11513 filename = argv[0];
11514 if (!filename) {
11515 /* bash says: "bash: .: filename argument required" */
11516 return 2; /* bash compat */
11517 }
11518 arg_path = NULL;
11519 if (!strchr(filename, '/')) {
11520 arg_path = find_in_path(filename);
11521 if (arg_path)
11522 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011523 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011524 errno = ENOENT;
11525 bb_simple_perror_msg(filename);
11526 return EXIT_FAILURE;
11527 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011528 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011529 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011530 free(arg_path);
11531 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011532 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011533 /* POSIX: non-interactive shell should abort here,
11534 * not merely fail. So far no one complained :)
11535 */
11536 return EXIT_FAILURE;
11537 }
11538
11539#if ENABLE_HUSH_FUNCTIONS
11540 sv_flg = G_flag_return_in_progress;
11541 /* "we are inside sourced file, ok to use return" */
11542 G_flag_return_in_progress = -1;
11543#endif
11544 args_need_save = argv[1]; /* used as a boolean variable */
11545 if (args_need_save)
11546 save_and_replace_G_args(&sv, argv);
11547
11548 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11549 G.last_exitcode = 0;
11550 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011551 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011552
11553 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11554 restore_G_args(&sv, argv);
11555#if ENABLE_HUSH_FUNCTIONS
11556 G_flag_return_in_progress = sv_flg;
11557#endif
11558
11559 return G.last_exitcode;
11560}
11561
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011562#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011563static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011564{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011565 int sig;
11566 char *new_cmd;
11567
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011568 if (!G_traps)
11569 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011570
11571 argv++;
11572 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011573 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011574 /* No args: print all trapped */
11575 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011576 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011577 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011578 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011579 /* note: bash adds "SIG", but only if invoked
11580 * as "bash". If called as "sh", or if set -o posix,
11581 * then it prints short signal names.
11582 * We are printing short names: */
11583 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011584 }
11585 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011586 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011587 return EXIT_SUCCESS;
11588 }
11589
11590 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011591 /* If first arg is a number: reset all specified signals */
11592 sig = bb_strtou(*argv, NULL, 10);
11593 if (errno == 0) {
11594 int ret;
11595 process_sig_list:
11596 ret = EXIT_SUCCESS;
11597 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011598 sighandler_t handler;
11599
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011600 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011601 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011602 ret = EXIT_FAILURE;
11603 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011604 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011605 continue;
11606 }
11607
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011608 free(G_traps[sig]);
11609 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011610
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011611 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011612 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011613
11614 /* There is no signal for 0 (EXIT) */
11615 if (sig == 0)
11616 continue;
11617
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011618 if (new_cmd)
11619 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11620 else
11621 /* We are removing trap handler */
11622 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011623 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011624 }
11625 return ret;
11626 }
11627
11628 if (!argv[1]) { /* no second arg */
James Byrne69374872019-07-02 11:35:03 +020011629 bb_simple_error_msg("trap: invalid arguments");
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011630 return EXIT_FAILURE;
11631 }
11632
11633 /* First arg is "-": reset all specified to default */
11634 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11635 /* Everything else: set arg as signal handler
11636 * (includes "" case, which ignores signal) */
11637 if (argv[0][0] == '-') {
11638 if (argv[0][1] == '\0') { /* "-" */
11639 /* new_cmd remains NULL: "reset these sigs" */
11640 goto reset_traps;
11641 }
11642 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11643 argv++;
11644 }
11645 /* else: "-something", no special meaning */
11646 }
11647 new_cmd = *argv;
11648 reset_traps:
11649 argv++;
11650 goto process_sig_list;
11651}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011652#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011653
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011654#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011655static struct pipe *parse_jobspec(const char *str)
11656{
11657 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011658 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011659
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011660 if (sscanf(str, "%%%u", &jobnum) != 1) {
11661 if (str[0] != '%'
11662 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11663 ) {
11664 bb_error_msg("bad argument '%s'", str);
11665 return NULL;
11666 }
11667 /* It is "%%", "%+" or "%" - current job */
11668 jobnum = G.last_jobid;
11669 if (jobnum == 0) {
James Byrne69374872019-07-02 11:35:03 +020011670 bb_simple_error_msg("no current job");
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011671 return NULL;
11672 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011673 }
11674 for (pi = G.job_list; pi; pi = pi->next) {
11675 if (pi->jobid == jobnum) {
11676 return pi;
11677 }
11678 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011679 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011680 return NULL;
11681}
11682
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011683static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11684{
11685 struct pipe *job;
11686 const char *status_string;
11687
11688 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11689 for (job = G.job_list; job; job = job->next) {
11690 if (job->alive_cmds == job->stopped_cmds)
11691 status_string = "Stopped";
11692 else
11693 status_string = "Running";
11694
11695 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11696 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011697
11698 clean_up_last_dead_job();
11699
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011700 return EXIT_SUCCESS;
11701}
11702
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011703/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011704static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011705{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011706 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011707 struct pipe *pi;
11708
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011709 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011710 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011711
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011712 /* If they gave us no args, assume they want the last backgrounded task */
11713 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011714 for (pi = G.job_list; pi; pi = pi->next) {
11715 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011716 goto found;
11717 }
11718 }
11719 bb_error_msg("%s: no current job", argv[0]);
11720 return EXIT_FAILURE;
11721 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011722
11723 pi = parse_jobspec(argv[1]);
11724 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011725 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011726 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011727 /* TODO: bash prints a string representation
11728 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011729 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011730 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011731 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011732 }
11733
11734 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011735 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11736 for (i = 0; i < pi->num_cmds; i++) {
11737 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011738 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011739 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011740
11741 i = kill(- pi->pgrp, SIGCONT);
11742 if (i < 0) {
11743 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011744 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011745 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011746 }
James Byrne69374872019-07-02 11:35:03 +020011747 bb_simple_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011748 }
11749
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011750 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011751 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011752 return checkjobs_and_fg_shell(pi);
11753 }
11754 return EXIT_SUCCESS;
11755}
11756#endif
11757
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011758#if ENABLE_HUSH_KILL
11759static int FAST_FUNC builtin_kill(char **argv)
11760{
11761 int ret = 0;
11762
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011763# if ENABLE_HUSH_JOB
11764 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11765 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011766
11767 do {
11768 struct pipe *pi;
11769 char *dst;
11770 int j, n;
11771
11772 if (argv[i][0] != '%')
11773 continue;
11774 /*
11775 * "kill %N" - job kill
11776 * Converting to pgrp / pid kill
11777 */
11778 pi = parse_jobspec(argv[i]);
11779 if (!pi) {
11780 /* Eat bad jobspec */
11781 j = i;
11782 do {
11783 j++;
11784 argv[j - 1] = argv[j];
11785 } while (argv[j]);
11786 ret = 1;
11787 i--;
11788 continue;
11789 }
11790 /*
11791 * In jobs started under job control, we signal
11792 * entire process group by kill -PGRP_ID.
11793 * This happens, f.e., in interactive shell.
11794 *
11795 * Otherwise, we signal each child via
11796 * kill PID1 PID2 PID3.
11797 * Testcases:
11798 * sh -c 'sleep 1|sleep 1 & kill %1'
11799 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11800 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11801 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011802 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011803 dst = alloca(n * sizeof(int)*4);
11804 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011805 if (G_interactive_fd)
11806 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011807 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011808 struct command *cmd = &pi->cmds[j];
11809 /* Skip exited members of the job */
11810 if (cmd->pid == 0)
11811 continue;
11812 /*
11813 * kill_main has matching code to expect
11814 * leading space. Needed to not confuse
11815 * negative pids with "kill -SIGNAL_NO" syntax
11816 */
11817 dst += sprintf(dst, " %u", (int)cmd->pid);
11818 }
11819 *dst = '\0';
11820 } while (argv[++i]);
11821 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011822# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011823
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011824 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011825 ret = run_applet_main(argv, kill_main);
11826 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011827 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011828 return ret;
11829}
11830#endif
11831
11832#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011833/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011834# if !ENABLE_HUSH_JOB
11835# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11836# endif
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011837static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011838{
11839 int ret = 0;
11840 for (;;) {
11841 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011842 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011843
Denys Vlasenko830ea352016-11-08 04:59:11 +010011844 if (!sigisemptyset(&G.pending_set))
11845 goto check_sig;
11846
Denys Vlasenko7e675362016-10-28 21:57:31 +020011847 /* waitpid is not interruptible by SA_RESTARTed
11848 * signals which we use. Thus, this ugly dance:
11849 */
11850
11851 /* Make sure possible SIGCHLD is stored in kernel's
11852 * pending signal mask before we call waitpid.
11853 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011854 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011855 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011856 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011857 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011858
11859 if (!sigisemptyset(&G.pending_set)) {
11860 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011861 goto restore;
11862 }
11863
11864 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011865/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011866 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011867 debug_printf_exec("checkjobs:%d\n", ret);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011868# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011869 if (waitfor_pipe) {
11870 int rcode = job_exited_or_stopped(waitfor_pipe);
11871 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11872 if (rcode >= 0) {
11873 ret = rcode;
11874 sigprocmask(SIG_SETMASK, &oldset, NULL);
11875 break;
11876 }
11877 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011878# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011879 /* if ECHILD, there are no children (ret is -1 or 0) */
11880 /* if ret == 0, no children changed state */
11881 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011882 if (errno == ECHILD || ret) {
11883 ret--;
11884 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011885 ret = 0;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011886# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011887 if (waitfor_pid == -1 && errno == ECHILD) {
11888 /* exitcode of "wait -n" with no children is 127, not 0 */
11889 ret = 127;
11890 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011891# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011892 sigprocmask(SIG_SETMASK, &oldset, NULL);
11893 break;
11894 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011895 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011896 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11897 /* Note: sigsuspend invokes signal handler */
11898 sigsuspend(&oldset);
Denys Vlasenko23bc5622020-02-18 16:46:01 +010011899 /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
11900 * to make sure SIGCHLD is not masked off?
11901 * It was reported that this:
11902 * fn() { : | return; }
11903 * shopt -s lastpipe
11904 * fn
11905 * exec hush SCRIPT
11906 * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
11907 * making "wait" commands in SCRIPT block forever.
11908 */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011909 restore:
11910 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011911 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011912 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011913 sig = check_and_run_traps();
11914 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011915 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko93e2a222020-12-23 12:23:21 +010011916 ret = 128 | sig;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011917 break;
11918 }
11919 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11920 }
11921 return ret;
11922}
11923
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011924static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011925{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011926 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011927 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011928
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011929 argv = skip_dash_dash(argv);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011930# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011931 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011932 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011933 /* (bash accepts "wait -n PID" too and ignores PID) */
11934 G.dead_job_exitcode = -1;
11935 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011936 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011937# endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011938 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011939 /* Don't care about wait results */
11940 /* Note 1: must wait until there are no more children */
11941 /* Note 2: must be interruptible */
11942 /* Examples:
11943 * $ sleep 3 & sleep 6 & wait
11944 * [1] 30934 sleep 3
11945 * [2] 30935 sleep 6
11946 * [1] Done sleep 3
11947 * [2] Done sleep 6
11948 * $ sleep 3 & sleep 6 & wait
11949 * [1] 30936 sleep 3
11950 * [2] 30937 sleep 6
11951 * [1] Done sleep 3
11952 * ^C <-- after ~4 sec from keyboard
11953 * $
11954 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011955 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011956 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011957
Denys Vlasenko7e675362016-10-28 21:57:31 +020011958 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011959 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011960 if (errno || pid <= 0) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010011961# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011962 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011963 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011964 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011965 wait_pipe = parse_jobspec(*argv);
11966 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011967 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011968 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011969 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011970 } else {
11971 /* waiting on "last dead job" removes it */
11972 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011973 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011974 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011975 /* else: parse_jobspec() already emitted error msg */
11976 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011977 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011978# endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011979 /* mimic bash message */
11980 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011981 ret = EXIT_FAILURE;
11982 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011983 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011984
Denys Vlasenko7e675362016-10-28 21:57:31 +020011985 /* Do we have such child? */
11986 ret = waitpid(pid, &status, WNOHANG);
11987 if (ret < 0) {
11988 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011989 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011990 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011991 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011992 /* "wait $!" but last bg task has already exited. Try:
11993 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11994 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011995 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011996 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011997 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011998 } else {
11999 /* Example: "wait 1". mimic bash message */
Denys Vlasenko259747c2019-11-28 10:28:14 +010012000 bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012001 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020012002 } else {
12003 /* ??? */
12004 bb_perror_msg("wait %s", *argv);
12005 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012006 continue; /* bash checks all argv[] */
12007 }
12008 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020012009 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010012010 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020012011 } else {
12012 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010012013 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020012014 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000012015 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +010012016 ret = 128 | WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000012017 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012018 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000012019
12020 return ret;
12021}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010012022#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000012023
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012024#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
12025static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
12026{
12027 if (argv[1]) {
12028 def = bb_strtou(argv[1], NULL, 10);
12029 if (errno || def < def_min || argv[2]) {
12030 bb_error_msg("%s: bad arguments", argv[0]);
12031 def = UINT_MAX;
12032 }
12033 }
12034 return def;
12035}
12036#endif
12037
Denis Vlasenkodadfb492008-07-29 10:16:05 +000012038#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012039static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012040{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012041 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000012042 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000012043 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020012044 /* if we came from builtin_continue(), need to undo "= 1" */
12045 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000012046 return EXIT_SUCCESS; /* bash compat */
12047 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020012048 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012049
12050 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
12051 if (depth == UINT_MAX)
12052 G.flag_break_continue = BC_BREAK;
12053 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000012054 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012055
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012056 return EXIT_SUCCESS;
12057}
12058
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012059static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012060{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000012061 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
12062 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012063}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000012064#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012065
12066#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012067static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012068{
12069 int rc;
12070
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020012071 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012072 bb_error_msg("%s: not in a function or sourced script", argv[0]);
12073 return EXIT_FAILURE; /* bash compat */
12074 }
12075
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020012076 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012077
12078 /* bash:
12079 * out of range: wraps around at 256, does not error out
12080 * non-numeric param:
12081 * f() { false; return qwe; }; f; echo $?
12082 * bash: return: qwe: numeric argument required <== we do this
12083 * 255 <== we also do this
12084 */
12085 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
Denys Vlasenkobb095f42020-02-20 16:37:59 +010012086# if ENABLE_HUSH_TRAP
12087 if (argv[1]) { /* "return ARG" inside a running trap sets $? */
12088 debug_printf_exec("G.return_exitcode=%d\n", rc);
12089 G.return_exitcode = rc;
12090 }
12091# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012092 return rc;
12093}
12094#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010012095
Denys Vlasenko11f2e992017-08-10 16:34:03 +020012096#if ENABLE_HUSH_TIMES
12097static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
12098{
12099 static const uint8_t times_tbl[] ALIGN1 = {
12100 ' ', offsetof(struct tms, tms_utime),
12101 '\n', offsetof(struct tms, tms_stime),
12102 ' ', offsetof(struct tms, tms_cutime),
12103 '\n', offsetof(struct tms, tms_cstime),
12104 0
12105 };
12106 const uint8_t *p;
12107 unsigned clk_tck;
12108 struct tms buf;
12109
12110 clk_tck = bb_clk_tck();
12111
12112 times(&buf);
12113 p = times_tbl;
12114 do {
12115 unsigned sec, frac;
12116 unsigned long t;
12117 t = *(clock_t *)(((char *) &buf) + p[1]);
12118 sec = t / clk_tck;
12119 frac = t % clk_tck;
12120 printf("%um%u.%03us%c",
12121 sec / 60, sec % 60,
12122 (frac * 1000) / clk_tck,
12123 p[0]);
12124 p += 2;
12125 } while (*p);
12126
12127 return EXIT_SUCCESS;
12128}
12129#endif
12130
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010012131#if ENABLE_HUSH_MEMLEAK
12132static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
12133{
12134 void *p;
12135 unsigned long l;
12136
12137# ifdef M_TRIM_THRESHOLD
12138 /* Optional. Reduces probability of false positives */
12139 malloc_trim(0);
12140# endif
12141 /* Crude attempt to find where "free memory" starts,
12142 * sans fragmentation. */
12143 p = malloc(240);
12144 l = (unsigned long)p;
12145 free(p);
12146 p = malloc(3400);
12147 if (l < (unsigned long)p) l = (unsigned long)p;
12148 free(p);
12149
12150
12151# if 0 /* debug */
12152 {
12153 struct mallinfo mi = mallinfo();
12154 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
12155 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
12156 }
12157# endif
12158
12159 if (!G.memleak_value)
12160 G.memleak_value = l;
12161
12162 l -= G.memleak_value;
12163 if ((long)l < 0)
12164 l = 0;
12165 l /= 1024;
12166 if (l > 127)
12167 l = 127;
12168
12169 /* Exitcode is "how many kilobytes we leaked since 1st call" */
12170 return l;
12171}
12172#endif