blob: ba9540c98d205c044a535309c85b1142bbbd39df [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 Vlasenko5807e182018-02-08 19:19:04 +0100130//config:config HUSH_LINENO_VAR
131//config: bool "$LINENO variable"
132//config: default y
133//config: depends on HUSH_BASH_COMPAT
134//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100135//config:config HUSH_BASH_SOURCE_CURDIR
136//config: bool "'source' and '.' builtins search current directory after $PATH"
137//config: default n # do not encourage non-standard behavior
138//config: depends on HUSH_BASH_COMPAT
139//config: help
140//config: This is not compliant with standards. Avoid if possible.
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 Vlasenkof2ed39b2018-04-05 16:46:49 +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
387#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Ron Yorstona81700b2019-04-15 10:48:29 +0100388#define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200389#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200390#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100391
392
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200393/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000394#define LEAK_HUNTING 0
395#define BUILD_AS_NOMMU 0
396/* Enable/disable sanity checks. Ok to enable in production,
397 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
398 * Keeping 1 for now even in released versions.
399 */
400#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200401/* Slightly bigger (+200 bytes), but faster hush.
402 * So far it only enables a trick with counting SIGCHLDs and forks,
403 * which allows us to do fewer waitpid's.
404 * (we can detect a case where neither forks were done nor SIGCHLDs happened
405 * and therefore waitpid will return the same result as last time)
406 */
407#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200408/* TODO: implement simplified code for users which do not need ${var%...} ops
409 * So far ${var%...} ops are always enabled:
410 */
411#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000412
413
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000414#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000415# undef BB_MMU
416# undef USE_FOR_NOMMU
417# undef USE_FOR_MMU
418# define BB_MMU 0
419# define USE_FOR_NOMMU(...) __VA_ARGS__
420# define USE_FOR_MMU(...)
421#endif
422
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200423#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100424#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000425/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000426# undef CONFIG_FEATURE_SH_STANDALONE
427# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000428# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100429# undef IF_NOT_FEATURE_SH_STANDALONE
430# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000431# define IF_FEATURE_SH_STANDALONE(...)
432# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000433#endif
434
Denis Vlasenko05743d72008-02-10 12:10:08 +0000435#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000436# undef ENABLE_FEATURE_EDITING
437# define ENABLE_FEATURE_EDITING 0
438# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
439# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200440# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
441# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000442#endif
443
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000444/* Do we support ANY keywords? */
445#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000446# define HAS_KEYWORDS 1
447# define IF_HAS_KEYWORDS(...) __VA_ARGS__
448# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000449#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000450# define HAS_KEYWORDS 0
451# define IF_HAS_KEYWORDS(...)
452# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000453#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000454
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000455/* If you comment out one of these below, it will be #defined later
456 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200457#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000458/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200459#define debug_printf_parse(...) do {} while (0)
460#define debug_printf_heredoc(...) do {} while (0)
461#define debug_print_tree(a, b) do {} while (0)
462#define debug_printf_exec(...) do {} while (0)
463#define debug_printf_env(...) do {} while (0)
464#define debug_printf_jobs(...) do {} while (0)
465#define debug_printf_expand(...) do {} while (0)
466#define debug_printf_varexp(...) do {} while (0)
467#define debug_printf_glob(...) do {} while (0)
468#define debug_printf_redir(...) do {} while (0)
469#define debug_printf_list(...) do {} while (0)
470#define debug_printf_subst(...) do {} while (0)
471#define debug_printf_prompt(...) do {} while (0)
472#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000473
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000474#define ERR_PTR ((void*)(long)1)
475
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100476#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000477
Denys Vlasenkoef8985c2019-05-19 16:29:09 +0200478#define _SPECIAL_VARS_STR "_*@$!?#-"
479#define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
480#define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100481#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200482/* Support / and // replace ops */
483/* Note that // is stored as \ in "encoded" string representation */
484# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
485# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
486# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
487#else
488# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
489# define VAR_SUBST_OPS "%#:-=+?"
490# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
491#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200492
Denys Vlasenko932b9972018-01-11 12:39:48 +0100493#define SPECIAL_VAR_SYMBOL_STR "\3"
494#define SPECIAL_VAR_SYMBOL 3
495/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
496#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000497
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200498struct variable;
499
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000500static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
501
502/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000503 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000504 */
505#if !BB_MMU
506typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200507 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000508 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000509 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000510} nommu_save_t;
511#endif
512
Denys Vlasenko9b782552010-09-08 13:33:26 +0200513enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000514 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000515#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000516 RES_IF ,
517 RES_THEN ,
518 RES_ELIF ,
519 RES_ELSE ,
520 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000521#endif
522#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000523 RES_FOR ,
524 RES_WHILE ,
525 RES_UNTIL ,
526 RES_DO ,
527 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000528#endif
529#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000530 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000531#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000532#if ENABLE_HUSH_CASE
533 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200534 /* three pseudo-keywords support contrived "case" syntax: */
535 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
536 RES_MATCH , /* "word)" */
537 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000538 RES_ESAC ,
539#endif
540 RES_XXXX ,
541 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200542};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000543
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000544typedef struct o_string {
545 char *data;
546 int length; /* position where data is appended */
547 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200548 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000549 /* At least some part of the string was inside '' or "",
550 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200551 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000552 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200553 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000554} o_string;
555enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200556 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
557 EXP_FLAG_GLOB = 0x2,
558 /* Protect newly added chars against globbing
559 * by prepending \ to *, ?, [, \ */
560 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
561};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000562/* Used for initialization: o_string foo = NULL_O_STRING; */
563#define NULL_O_STRING { NULL }
564
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200565#ifndef debug_printf_parse
566static const char *const assignment_flag[] = {
567 "MAYBE_ASSIGNMENT",
568 "DEFINITELY_ASSIGNMENT",
569 "NOT_ASSIGNMENT",
570 "WORD_IS_KEYWORD",
571};
572#endif
573
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200574/* We almost can use standard FILE api, but we need an ability to move
575 * its fd when redirects coincide with it. No api exists for that
576 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
577 * HFILE is our internal alternative. Only supports reading.
578 * Since we now can, we incorporate linked list of all opened HFILEs
579 * into the struct (used to be a separate mini-list).
580 */
581typedef struct HFILE {
582 char *cur;
583 char *end;
584 struct HFILE *next_hfile;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200585 int fd;
586 char buf[1024];
587} HFILE;
588
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000589typedef struct in_str {
590 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200591 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200592 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200593 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000594} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000595
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200596/* The descrip member of this structure is only used to make
597 * debugging output pretty */
598static const struct {
Denys Vlasenko965b7952020-11-30 13:03:03 +0100599 int32_t mode;
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200600 signed char default_fd;
601 char descrip[3];
Denys Vlasenko965b7952020-11-30 13:03:03 +0100602} redir_table[] ALIGN4 = {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200603 { O_RDONLY, 0, "<" },
604 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
605 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
606 { O_CREAT|O_RDWR, 1, "<>" },
607 { O_RDONLY, 0, "<<" },
608/* Should not be needed. Bogus default_fd helps in debugging */
609/* { O_RDONLY, 77, "<<" }, */
610};
611
Eric Andersen25f27032001-04-26 23:22:31 +0000612struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000613 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000614 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000615 int rd_fd; /* fd to redirect */
616 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
617 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000618 smallint rd_type; /* (enum redir_type) */
619 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000620 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200621 * bit 0: do we need to trim leading tabs?
622 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000623 */
Eric Andersen25f27032001-04-26 23:22:31 +0000624};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000625typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200626 REDIRECT_INPUT = 0,
627 REDIRECT_OVERWRITE = 1,
628 REDIRECT_APPEND = 2,
629 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000630 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200631 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000632
633 REDIRFD_CLOSE = -3,
634 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000635 REDIRFD_TO_FILE = -1,
636 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000637
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000638 HEREDOC_SKIPTABS = 1,
639 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000640} redir_type;
641
Eric Andersen25f27032001-04-26 23:22:31 +0000642
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000643struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000644 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200645 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100646#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100647 unsigned lineno;
648#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200649 smallint cmd_type; /* CMD_xxx */
650#define CMD_NORMAL 0
651#define CMD_SUBSHELL 1
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100652#if BASH_TEST2
653/* used for "[[ EXPR ]]" */
654# define CMD_TEST2_SINGLEWORD_NOGLOB 2
655#endif
656#if ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
657/* used to prevent word splitting and globbing in "export v=t*" */
658# define CMD_SINGLEWORD_NOGLOB 3
Denis Vlasenkoed055212009-04-11 10:37:10 +0000659#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200660#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100661# define CMD_FUNCDEF 4
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200662#endif
663
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100664 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200665 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
666 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000667#if !BB_MMU
668 char *group_as_string;
669#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000670#if ENABLE_HUSH_FUNCTIONS
671 struct function *child_func;
672/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200673 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000674 * When we execute "f1() {a;}" cmd, we create new function and clear
675 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200676 * When we execute "f1() {b;}", we notice that f1 exists,
677 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000678 * we put those fields back into cmd->xxx
679 * (struct function has ->parent_cmd ptr to facilitate that).
680 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
681 * Without this trick, loop would execute a;b;b;b;...
682 * instead of correct sequence a;b;a;b;...
683 * When command is freed, it severs the link
684 * (sets ->child_func->parent_cmd to NULL).
685 */
686#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000687 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000688/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
689 * and on execution these are substituted with their values.
690 * Substitution can make _several_ words out of one argv[n]!
691 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000692 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000693 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000694 struct redir_struct *redirects; /* I/O redirections */
695};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000696/* Is there anything in this command at all? */
697#define IS_NULL_CMD(cmd) \
698 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
699
Eric Andersen25f27032001-04-26 23:22:31 +0000700struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000701 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000702 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000703 int alive_cmds; /* number of commands running (not exited) */
704 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000705#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100706 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000707 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000708 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000709#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000710 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000711 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000712 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
713 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000714};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000715typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100716 PIPE_SEQ = 0,
717 PIPE_AND = 1,
718 PIPE_OR = 2,
719 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000720} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000721/* Is there anything in this pipe at all? */
722#define IS_NULL_PIPE(pi) \
723 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000724
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000725/* This holds pointers to the various results of parsing */
726struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000727 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000728 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000729 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000730 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000731 /* last command in pipe (being constructed right now) */
732 struct command *command;
733 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000734 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200735 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000736#if !BB_MMU
737 o_string as_string;
738#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200739 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000740#if HAS_KEYWORDS
741 smallint ctx_res_w;
742 smallint ctx_inverted; /* "! cmd | cmd" */
743#if ENABLE_HUSH_CASE
744 smallint ctx_dsemicolon; /* ";;" seen */
745#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000746 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
747 int old_flag;
748 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000749 * example: "if pipe1; pipe2; then pipe3; fi"
750 * when we see "if" or "then", we malloc and copy current context,
751 * and make ->stack point to it. then we parse pipeN.
752 * when closing "then" / fi" / whatever is found,
753 * we move list_head into ->stack->command->group,
754 * copy ->stack into current context, and delete ->stack.
755 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000756 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000757 struct parse_context *stack;
758#endif
759};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200760enum {
761 MAYBE_ASSIGNMENT = 0,
762 DEFINITELY_ASSIGNMENT = 1,
763 NOT_ASSIGNMENT = 2,
764 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
765 WORD_IS_KEYWORD = 3,
766};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000767
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000768/* On program start, environ points to initial environment.
769 * putenv adds new pointers into it, unsetenv removes them.
770 * Neither of these (de)allocates the strings.
771 * setenv allocates new strings in malloc space and does putenv,
772 * and thus setenv is unusable (leaky) for shell's purposes */
773#define setenv(...) setenv_is_leaky_dont_use()
774struct variable {
775 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000776 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000777 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200778 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000779 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000780 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000781};
782
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000783enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000784 BC_BREAK = 1,
785 BC_CONTINUE = 2,
786};
787
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000788#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000789struct function {
790 struct function *next;
791 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000792 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000793 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200794# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000795 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200796# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000797};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000798#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000799
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000800
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100801/* set -/+o OPT support. (TODO: make it optional)
802 * bash supports the following opts:
803 * allexport off
804 * braceexpand on
805 * emacs on
806 * errexit off
807 * errtrace off
808 * functrace off
809 * hashall on
810 * histexpand off
811 * history on
812 * ignoreeof off
813 * interactive-comments on
814 * keyword off
815 * monitor on
816 * noclobber off
817 * noexec off
818 * noglob off
819 * nolog off
820 * notify off
821 * nounset off
822 * onecmd off
823 * physical off
824 * pipefail off
825 * posix off
826 * privileged off
827 * verbose off
828 * vi off
829 * xtrace off
830 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800831static const char o_opt_strings[] ALIGN1 =
832 "pipefail\0"
833 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200834 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800835#if ENABLE_HUSH_MODE_X
836 "xtrace\0"
837#endif
838 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100839enum {
840 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800841 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200842 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800843#if ENABLE_HUSH_MODE_X
844 OPT_O_XTRACE,
845#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100846 NUM_OPT_O
847};
848
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000849/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850/* Sorted roughly by size (smaller offsets == smaller code) */
851struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000852 /* interactive_fd != 0 means we are an interactive shell.
853 * If we are, then saved_tty_pgrp can also be != 0, meaning
854 * that controlling tty is available. With saved_tty_pgrp == 0,
855 * job control still works, but terminal signals
856 * (^C, ^Z, ^Y, ^\) won't work at all, and background
857 * process groups can only be created with "cmd &".
858 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
859 * to give tty to the foreground process group,
860 * and will take it back when the group is stopped (^Z)
861 * or killed (^C).
862 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000863#if ENABLE_HUSH_INTERACTIVE
864 /* 'interactive_fd' is a fd# open to ctty, if we have one
865 * _AND_ if we decided to act interactively */
866 int interactive_fd;
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +0200867 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000868# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000869#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000870# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000871#endif
872#if ENABLE_FEATURE_EDITING
873 line_input_t *line_input_state;
874#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000875 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200876 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000877 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200878#if ENABLE_HUSH_RANDOM_SUPPORT
879 random_t random_gen;
880#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000881#if ENABLE_HUSH_JOB
882 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100883 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000884 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000885 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400886# define G_saved_tty_pgrp (G.saved_tty_pgrp)
887#else
888# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000889#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200890 /* How deeply are we in context where "set -e" is ignored */
891 int errexit_depth;
892 /* "set -e" rules (do we follow them correctly?):
893 * Exit if pipe, list, or compound command exits with a non-zero status.
894 * Shell does not exit if failed command is part of condition in
895 * if/while, part of && or || list except the last command, any command
896 * in a pipe but the last, or if the command's return value is being
897 * inverted with !. If a compound command other than a subshell returns a
898 * non-zero status because a command failed while -e was being ignored, the
899 * shell does not exit. A trap on ERR, if set, is executed before the shell
900 * exits [ERR is a bashism].
901 *
902 * If a compound command or function executes in a context where -e is
903 * ignored, none of the commands executed within are affected by the -e
904 * setting. If a compound command or function sets -e while executing in a
905 * context where -e is ignored, that setting does not have any effect until
906 * the compound command or the command containing the function call completes.
907 */
908
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100909 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100910#if ENABLE_HUSH_MODE_X
911# define G_x_mode (G.o_opt[OPT_O_XTRACE])
912#else
913# define G_x_mode 0
914#endif
Denys Vlasenkod8740b22019-05-19 19:11:21 +0200915 char opt_s;
Denys Vlasenkof3634582019-06-03 12:21:04 +0200916 char opt_c;
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200917#if ENABLE_HUSH_INTERACTIVE
918 smallint promptmode; /* 0: PS1, 1: PS2 */
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +0100919# if ENABLE_FEATURE_EDITING
920 smallint flag_ctrlC; /* when set, suppresses syntax error messages */
921# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200922#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000923 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000924#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000925 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000926#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000927#if ENABLE_HUSH_FUNCTIONS
928 /* 0: outside of a function (or sourced file)
929 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000930 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000931 */
932 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200933# define G_flag_return_in_progress (G.flag_return_in_progress)
934#else
935# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000936#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000937 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100938 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000939 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200940 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200941 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100942#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000943 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000944 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100945# define G_global_args_malloced (G.global_args_malloced)
946#else
947# define G_global_args_malloced 0
948#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100949#if ENABLE_HUSH_BASH_COMPAT
950 int dead_job_exitcode; /* for "wait -n" */
951#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000952 /* how many non-NULL argv's we have. NB: $# + 1 */
953 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000954 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000955#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000956 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000957#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000958#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000959 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000960 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000961#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200962#if ENABLE_HUSH_GETOPTS
963 unsigned getopt_count;
964#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000965 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200966 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000967 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200968 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200969 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200970 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200971 unsigned var_nest_level;
972#if ENABLE_HUSH_FUNCTIONS
973# if ENABLE_HUSH_LOCAL
974 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200975# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200976 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000977#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000978 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200979#if ENABLE_HUSH_FAST
980 unsigned count_SIGCHLD;
981 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200982 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200983#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100984#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +0200985 unsigned parse_lineno;
986 unsigned execute_lineno;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100987#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200988 HFILE *HFILE_list;
Denys Vlasenko21806562019-11-01 14:16:07 +0100989 HFILE *HFILE_stdin;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200990 /* Which signals have non-DFL handler (even with no traps set)?
991 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200992 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200993 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200994 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200995 * Other than these two times, never modified.
996 */
997 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200998#if ENABLE_HUSH_JOB
999 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001000# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001001#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001002# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001003#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001004#if ENABLE_HUSH_TRAP
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01001005 int pre_trap_exitcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01001006# if ENABLE_HUSH_FUNCTIONS
1007 int return_exitcode;
1008# endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001009 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001010# define G_traps G.traps
1011#else
1012# define G_traps ((char**)NULL)
1013#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001014 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +01001015#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001016 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +01001017#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001018#if ENABLE_HUSH_MODE_X
1019 unsigned x_mode_depth;
1020 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1021 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1022 * for all subsequent output.
1023 */
1024 int x_mode_fd;
1025 o_string x_mode_buf;
1026#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001027#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001028 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001029#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001030 struct sigaction sa;
Denys Vlasenkof3634582019-06-03 12:21:04 +02001031 char optstring_buf[sizeof("eixcs")];
Ron Yorstona81700b2019-04-15 10:48:29 +01001032#if BASH_EPOCH_VARS
1033 char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
1034#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001035#if ENABLE_FEATURE_EDITING
1036 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1037#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001038};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001039#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001040/* Not #defining name to G.name - this quickly gets unwieldy
1041 * (too many defines). Also, I actually prefer to see when a variable
1042 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001043#define INIT_G() do { \
1044 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001045 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1046 sigfillset(&G.sa.sa_mask); \
1047 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001048} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001049
1050
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001051/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001052static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001053#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001055#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001056static int builtin_eval(char **argv) FAST_FUNC;
1057static int builtin_exec(char **argv) FAST_FUNC;
1058static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001059#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001060static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001061#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001062#if ENABLE_HUSH_READONLY
1063static int builtin_readonly(char **argv) FAST_FUNC;
1064#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001065#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001066static int builtin_fg_bg(char **argv) FAST_FUNC;
1067static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001068#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001069#if ENABLE_HUSH_GETOPTS
1070static int builtin_getopts(char **argv) FAST_FUNC;
1071#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001072#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001073static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001074#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001075#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001076static int builtin_history(char **argv) FAST_FUNC;
1077#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001078#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001079static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001080#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001081#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001082static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001083#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001084#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001085static int builtin_printf(char **argv) FAST_FUNC;
1086#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001087static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001088#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001089static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001090#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001091#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001092static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001093#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001094static int builtin_shift(char **argv) FAST_FUNC;
1095static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001096#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001097static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001098#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001099#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001100static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001101#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001102#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001103static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001104#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001105#if ENABLE_HUSH_TIMES
1106static int builtin_times(char **argv) FAST_FUNC;
1107#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001108static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001109#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001110static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001111#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001112#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001113static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001114#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001115#if ENABLE_HUSH_KILL
1116static int builtin_kill(char **argv) FAST_FUNC;
1117#endif
1118#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001119static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001120#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001122static int builtin_break(char **argv) FAST_FUNC;
1123static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001124#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001125#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001126static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001127#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001128
1129/* Table of built-in functions. They can be forked or not, depending on
1130 * context: within pipes, they fork. As simple commands, they do not.
1131 * When used in non-forking context, they can change global variables
1132 * in the parent shell process. If forked, of course they cannot.
1133 * For example, 'unset foo | whatever' will parse and run, but foo will
1134 * still be set at the end. */
1135struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001136 const char *b_cmd;
1137 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001138#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001139 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001140# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001141#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001142# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001143#endif
1144};
1145
Denys Vlasenko965b7952020-11-30 13:03:03 +01001146static const struct built_in_command bltins1[] ALIGN_PTR = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001147 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001148 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001149#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001150 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001151#endif
1152#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001153 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001154#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001156#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001157 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001158#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001159 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1160 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001161 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001162#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001163 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001164#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001165#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001166 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001167#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001168#if ENABLE_HUSH_GETOPTS
1169 BLTIN("getopts" , builtin_getopts , NULL),
1170#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001171#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001172 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001173#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001174#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001175 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001176#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001177#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001178 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001179#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001180#if ENABLE_HUSH_KILL
1181 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1182#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001183#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001184 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001185#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001186#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001187 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001188#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001189#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001190 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001191#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001192#if ENABLE_HUSH_READONLY
1193 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1194#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001195#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001196 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001197#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001198#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001199 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001200#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001201 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001202#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001203 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001204#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001205#if ENABLE_HUSH_TIMES
1206 BLTIN("times" , builtin_times , NULL),
1207#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001208#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001209 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001210#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001211 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001212#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001213 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001214#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001215#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001216 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001217#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001218#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001219 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001220#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001221#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001222 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001223#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001224#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001225 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001226#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001227};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001228/* These builtins won't be used if we are on NOMMU and need to re-exec
1229 * (it's cheaper to run an external program in this case):
1230 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01001231static const struct built_in_command bltins2[] ALIGN_PTR = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001232#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001233 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001234#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001235#if BASH_TEST2
1236 BLTIN("[[" , builtin_test , NULL),
1237#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001238#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001239 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001240#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001241#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001242 BLTIN("printf" , builtin_printf , NULL),
1243#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001244 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001245#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001246 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001247#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001248};
1249
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001250
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001251/* Debug printouts.
1252 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001253#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001254/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001255# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001256# define debug_enter() (G.debug_indent++)
1257# define debug_leave() (G.debug_indent--)
1258#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001259# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001260# define debug_enter() ((void)0)
1261# define debug_leave() ((void)0)
1262#endif
1263
1264#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001265# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001266#endif
1267
1268#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001269# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001270#endif
1271
Denys Vlasenko3675c372018-07-23 16:31:21 +02001272#ifndef debug_printf_heredoc
1273# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1274#endif
1275
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001276#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001277#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001278#endif
1279
1280#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001281# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001282#endif
1283
1284#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001285# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001286# define DEBUG_JOBS 1
1287#else
1288# define DEBUG_JOBS 0
1289#endif
1290
1291#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001292# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001293# define DEBUG_EXPAND 1
1294#else
1295# define DEBUG_EXPAND 0
1296#endif
1297
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001298#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001299# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001300#endif
1301
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001302#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001303# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001304# define DEBUG_GLOB 1
1305#else
1306# define DEBUG_GLOB 0
1307#endif
1308
Denys Vlasenko2db74612017-07-07 22:07:28 +02001309#ifndef debug_printf_redir
1310# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1311#endif
1312
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001313#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001314# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001315#endif
1316
1317#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001318# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001319#endif
1320
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001321#ifndef debug_printf_prompt
1322# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1323#endif
1324
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001325#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001326# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001327# define DEBUG_CLEAN 1
1328#else
1329# define DEBUG_CLEAN 0
1330#endif
1331
1332#if DEBUG_EXPAND
1333static void debug_print_strings(const char *prefix, char **vv)
1334{
1335 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001336 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001337 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001338 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001339}
1340#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001341# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001342#endif
1343
1344
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001345/* Leak hunting. Use hush_leaktool.sh for post-processing.
1346 */
1347#if LEAK_HUNTING
1348static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001349{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001350 void *ptr = xmalloc((size + 0xff) & ~0xff);
1351 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1352 return ptr;
1353}
1354static void *xxrealloc(int lineno, void *ptr, size_t size)
1355{
1356 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1357 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1358 return ptr;
1359}
1360static char *xxstrdup(int lineno, const char *str)
1361{
1362 char *ptr = xstrdup(str);
1363 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1364 return ptr;
1365}
1366static void xxfree(void *ptr)
1367{
1368 fdprintf(2, "free %p\n", ptr);
1369 free(ptr);
1370}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001371# define xmalloc(s) xxmalloc(__LINE__, s)
1372# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1373# define xstrdup(s) xxstrdup(__LINE__, s)
1374# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001375#endif
1376
1377
1378/* Syntax and runtime errors. They always abort scripts.
1379 * In interactive use they usually discard unparsed and/or unexecuted commands
1380 * and return to the prompt.
1381 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1382 */
1383#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001384# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001385# define syntax_error(lineno, msg) syntax_error(msg)
1386# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1387# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1388# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1389# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001390#endif
1391
Denys Vlasenko39701202017-08-02 19:44:05 +02001392static void die_if_script(void)
1393{
1394 if (!G_interactive_fd) {
1395 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1396 xfunc_error_retval = G.last_exitcode;
1397 xfunc_die();
1398 }
1399}
1400
1401static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001402{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001403 va_list p;
1404
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001405#if HUSH_DEBUG >= 2
1406 bb_error_msg("hush.c:%u", lineno);
1407#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001408 va_start(p, fmt);
1409 bb_verror_msg(fmt, p, NULL);
1410 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001411 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001412}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001413
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001414static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001415{
1416 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001417 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001418 else
James Byrne69374872019-07-02 11:35:03 +02001419 bb_simple_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001420 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001421}
1422
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001423static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001424{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001425 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001426 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001427}
1428
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001429static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001430{
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01001431#if ENABLE_FEATURE_EDITING
1432 if (!G.flag_ctrlC)
1433#endif
1434 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001435//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1436// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001437}
1438
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001439static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001440{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001441 char msg[2] = { ch, '\0' };
1442 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001443}
1444
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001445static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001446{
1447 char msg[2];
1448 msg[0] = ch;
1449 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001450#if HUSH_DEBUG >= 2
1451 bb_error_msg("hush.c:%u", lineno);
1452#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001453 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001454 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001455}
1456
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001457#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001458# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001459# undef syntax_error
1460# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001461# undef syntax_error_unterm_ch
1462# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001463# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001464#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001465# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001466# define syntax_error(msg) syntax_error(__LINE__, msg)
1467# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1468# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1469# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1470# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001471#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001472
Denis Vlasenko552433b2009-04-04 19:29:21 +00001473
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001474/* Utility functions
1475 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001476/* Replace each \x with x in place, return ptr past NUL. */
1477static char *unbackslash(char *src)
1478{
Denys Vlasenko71885402009-09-24 01:44:13 +02001479 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001480 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001481 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001482 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001483 if (*src != '\0') {
1484 /* \x -> x */
1485 *dst++ = *src++;
1486 continue;
1487 }
1488 /* else: "\<nul>". Do not delete this backslash.
1489 * Testcase: eval 'echo ok\'
1490 */
1491 *dst++ = '\\';
1492 /* fallthrough */
1493 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001494 if ((*dst++ = *src++) == '\0')
1495 break;
1496 }
1497 return dst;
1498}
1499
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001500static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001501{
1502 int i;
1503 unsigned count1;
1504 unsigned count2;
1505 char **v;
1506
1507 v = strings;
1508 count1 = 0;
1509 if (v) {
1510 while (*v) {
1511 count1++;
1512 v++;
1513 }
1514 }
1515 count2 = 0;
1516 v = add;
1517 while (*v) {
1518 count2++;
1519 v++;
1520 }
1521 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1522 v[count1 + count2] = NULL;
1523 i = count2;
1524 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001525 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001526 return v;
1527}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001528#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001529static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1530{
1531 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1532 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1533 return ptr;
1534}
1535#define add_strings_to_strings(strings, add, need_to_dup) \
1536 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1537#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001538
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001539/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001540static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001541{
1542 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001543 v[0] = add;
1544 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001545 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001546}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001547#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001548static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1549{
1550 char **ptr = add_string_to_strings(strings, add);
1551 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1552 return ptr;
1553}
1554#define add_string_to_strings(strings, add) \
1555 xx_add_string_to_strings(__LINE__, strings, add)
1556#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001557
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001558static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001559{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001560 char **v;
1561
1562 if (!strings)
1563 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001564 v = strings;
1565 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001566 free(*v);
1567 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001568 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001569 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001570}
1571
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001572static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001573{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001574 int newfd;
1575 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001576 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1577 if (newfd >= 0) {
1578 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1579 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1580 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001581 if (errno == EBUSY)
1582 goto repeat;
1583 if (errno == EINTR)
1584 goto repeat;
1585 }
1586 return newfd;
1587}
1588
Denys Vlasenko657e9002017-07-30 23:34:04 +02001589static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001590{
1591 int newfd;
1592 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001593 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001594 if (newfd < 0) {
1595 if (errno == EBUSY)
1596 goto repeat;
1597 if (errno == EINTR)
1598 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001599 /* fd was not open? */
1600 if (errno == EBADF)
1601 return fd;
1602 xfunc_die();
1603 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001604 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1605 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001606 close(fd);
1607 return newfd;
1608}
1609
1610
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001611/* Manipulating HFILEs */
1612static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001613{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001614 HFILE *fp;
1615 int fd;
1616
1617 fd = STDIN_FILENO;
1618 if (name) {
1619 fd = open(name, O_RDONLY | O_CLOEXEC);
1620 if (fd < 0)
1621 return NULL;
1622 if (O_CLOEXEC == 0) /* ancient libc */
1623 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001624 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001625
1626 fp = xmalloc(sizeof(*fp));
Denys Vlasenko21806562019-11-01 14:16:07 +01001627 if (name == NULL)
1628 G.HFILE_stdin = fp;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001629 fp->fd = fd;
1630 fp->cur = fp->end = fp->buf;
1631 fp->next_hfile = G.HFILE_list;
1632 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001633 return fp;
1634}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001635static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001636{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001637 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001638 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001639 HFILE *cur = *pp;
1640 if (cur == fp) {
1641 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001642 break;
1643 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001644 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001645 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001646 if (fp->fd >= 0)
1647 close(fp->fd);
1648 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001649}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001650static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001651{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001652 int n;
1653
1654 if (fp->fd < 0) {
1655 /* Already saw EOF */
1656 return EOF;
1657 }
1658 /* Try to buffer more input */
1659 fp->cur = fp->buf;
1660 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1661 if (n < 0) {
James Byrne69374872019-07-02 11:35:03 +02001662 bb_simple_perror_msg("read error");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001663 n = 0;
1664 }
1665 fp->end = fp->buf + n;
1666 if (n == 0) {
1667 /* EOF/error */
1668 close(fp->fd);
1669 fp->fd = -1;
1670 return EOF;
1671 }
1672 return (unsigned char)(*fp->cur++);
1673}
1674/* Inlined for common case of non-empty buffer.
1675 */
1676static ALWAYS_INLINE int hfgetc(HFILE *fp)
1677{
1678 if (fp->cur < fp->end)
1679 return (unsigned char)(*fp->cur++);
1680 /* Buffer empty */
1681 return refill_HFILE_and_getc(fp);
1682}
1683static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1684{
1685 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001686 while (fl) {
1687 if (fd == fl->fd) {
1688 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001689 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001690 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 +02001691 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001692 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001693 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001694 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001695#if ENABLE_HUSH_MODE_X
1696 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1697 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1698 return 1; /* "found and moved" */
1699 }
1700#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001701 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001702}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001703#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001704static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001705{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001706 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001707 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001708 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001709 * It is disastrous if we share memory with a vforked parent.
1710 * I'm not sure we never come here after vfork.
1711 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001712 *
1713 * ">" instead of ">=": we don't close fd#0,
1714 * interactive shell uses hfopen(NULL) as stdin input
1715 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1716 * If we'd close it here, then e.g. interactive "set | sort"
1717 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001718 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001719 if (fl->fd > 0)
1720 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001721 close(fl->fd);
1722 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001723 }
1724}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001725#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001726static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001727{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001728 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001729 while (fl) {
1730 if (fl->fd == fd)
1731 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001732 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001733 }
1734 return 0;
1735}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001736
1737
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001738/* Helpers for setting new $n and restoring them back
1739 */
1740typedef struct save_arg_t {
1741 char *sv_argv0;
1742 char **sv_g_argv;
1743 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001744 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001745} save_arg_t;
1746
1747static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1748{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001749 sv->sv_argv0 = argv[0];
1750 sv->sv_g_argv = G.global_argv;
1751 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001752 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001753
1754 argv[0] = G.global_argv[0]; /* retain $0 */
1755 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001756 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001757
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001758 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001759}
1760
1761static void restore_G_args(save_arg_t *sv, char **argv)
1762{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001763#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001764 if (G.global_args_malloced) {
1765 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001766 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001767 while (*++pp) /* note: does not free $0 */
1768 free(*pp);
1769 free(G.global_argv);
1770 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001771#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001772 argv[0] = sv->sv_argv0;
1773 G.global_argv = sv->sv_g_argv;
1774 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001775 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001776}
1777
1778
Denis Vlasenkod5762932009-03-31 11:22:57 +00001779/* Basic theory of signal handling in shell
1780 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001781 * This does not describe what hush does, rather, it is current understanding
1782 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001783 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1784 *
1785 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1786 * is finished or backgrounded. It is the same in interactive and
1787 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001788 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001789 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001790 * backgrounds (i.e. stops) or kills all members of currently running
1791 * pipe.
1792 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001793 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001794 * or by SIGINT in interactive shell.
1795 *
1796 * Trap handlers will execute even within trap handlers. (right?)
1797 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001798 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1799 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001800 *
1801 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001802 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001803 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001804 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001805 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001806 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001807 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001808 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001809 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001810 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001811 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001812 *
1813 * SIGQUIT: ignore
1814 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001815 * SIGHUP (interactive):
1816 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001817 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001818 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1819 * that all pipe members are stopped. Try this in bash:
1820 * while :; do :; done - ^Z does not background it
1821 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001822 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001823 * of the command line, show prompt. NB: ^C does not send SIGINT
1824 * to interactive shell while shell is waiting for a pipe,
1825 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001826 * Example 1: this waits 5 sec, but does not execute ls:
1827 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1828 * Example 2: this does not wait and does not execute ls:
1829 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1830 * Example 3: this does not wait 5 sec, but executes ls:
1831 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001832 * Example 4: this does not wait and does not execute ls:
1833 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001834 *
1835 * (What happens to signals which are IGN on shell start?)
1836 * (What happens with signal mask on shell start?)
1837 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001838 * Old implementation
1839 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001840 * We use in-kernel pending signal mask to determine which signals were sent.
1841 * We block all signals which we don't want to take action immediately,
1842 * i.e. we block all signals which need to have special handling as described
1843 * above, and all signals which have traps set.
1844 * After each pipe execution, we extract any pending signals via sigtimedwait()
1845 * and act on them.
1846 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001847 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001848 * sigset_t blocked_set: current blocked signal set
1849 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001850 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001851 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001852 * "trap 'cmd' SIGxxx":
1853 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001854 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001855 * unblock signals with special interactive handling
1856 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001857 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001858 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001859 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001860 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001861 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001862 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001863 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001864 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001865 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001866 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001867 * Standard says "When a subshell is entered, traps that are not being ignored
1868 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001869 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001870 *
1871 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001872 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001873 * masked signals are not visible!
1874 *
1875 * New implementation
1876 * ==================
1877 * We record each signal we are interested in by installing signal handler
1878 * for them - a bit like emulating kernel pending signal mask in userspace.
1879 * We are interested in: signals which need to have special handling
1880 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001881 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001882 * After each pipe execution, we extract any pending signals
1883 * and act on them.
1884 *
1885 * unsigned special_sig_mask: a mask of shell-special signals.
1886 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1887 * char *traps[sig] if trap for sig is set (even if it's '').
1888 * sigset_t pending_set: set of sigs we received.
1889 *
1890 * "trap - SIGxxx":
1891 * if sig is in special_sig_mask, set handler back to:
1892 * record_pending_signo, or to IGN if it's a tty stop signal
1893 * if sig is in fatal_sig_mask, set handler back to sigexit.
1894 * else: set handler back to SIG_DFL
1895 * "trap 'cmd' SIGxxx":
1896 * set handler to record_pending_signo.
1897 * "trap '' SIGxxx":
1898 * set handler to SIG_IGN.
1899 * after [v]fork, if we plan to be a shell:
1900 * set signals with special interactive handling to SIG_DFL
1901 * (because child shell is not interactive),
1902 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1903 * after [v]fork, if we plan to exec:
1904 * POSIX says fork clears pending signal mask in child - no need to clear it.
1905 *
1906 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1907 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1908 *
1909 * Note (compat):
1910 * Standard says "When a subshell is entered, traps that are not being ignored
1911 * are set to the default actions". bash interprets it so that traps which
1912 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001913 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001914enum {
1915 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001916 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001917 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001918 | (1 << SIGHUP)
1919 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001920 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001921#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001922 | (1 << SIGTTIN)
1923 | (1 << SIGTTOU)
1924 | (1 << SIGTSTP)
1925#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001926 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001927};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001928
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001929static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001930{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001931 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001932#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001933 if (sig == SIGCHLD) {
1934 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001935//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 +02001936 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001937#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001938}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001939
Denys Vlasenko0806e402011-05-12 23:06:20 +02001940static sighandler_t install_sighandler(int sig, sighandler_t handler)
1941{
1942 struct sigaction old_sa;
1943
1944 /* We could use signal() to install handlers... almost:
1945 * except that we need to mask ALL signals while handlers run.
1946 * I saw signal nesting in strace, race window isn't small.
1947 * SA_RESTART is also needed, but in Linux, signal()
1948 * sets SA_RESTART too.
1949 */
1950 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1951 /* sigfillset(&G.sa.sa_mask); - already done */
1952 /* G.sa.sa_flags = SA_RESTART; - already done */
1953 G.sa.sa_handler = handler;
1954 sigaction(sig, &G.sa, &old_sa);
1955 return old_sa.sa_handler;
1956}
1957
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001958static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001959
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001960static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001961static void restore_ttypgrp_and__exit(void)
1962{
1963 /* xfunc has failed! die die die */
1964 /* no EXIT traps, this is an escape hatch! */
1965 G.exiting = 1;
1966 hush_exit(xfunc_error_retval);
1967}
1968
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001969#if ENABLE_HUSH_JOB
1970
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001971/* Needed only on some libc:
1972 * It was observed that on exit(), fgetc'ed buffered data
1973 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1974 * With the net effect that even after fork(), not vfork(),
1975 * exit() in NOEXECed applet in "sh SCRIPT":
1976 * noexec_applet_here
1977 * echo END_OF_SCRIPT
1978 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1979 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001980 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001981 * and in `cmd` handling.
1982 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1983 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001984static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001985static void fflush_and__exit(void)
1986{
1987 fflush_all();
1988 _exit(xfunc_error_retval);
1989}
1990
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001991/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001992# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001993/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001994# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001995
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001996/* Restores tty foreground process group, and exits.
1997 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001998 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001999 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002000 * We also call it if xfunc is exiting.
2001 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002002static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002003static void sigexit(int sig)
2004{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002005 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00002006 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002007 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
2008 /* Disable all signals: job control, SIGPIPE, etc.
2009 * Mostly paranoid measure, to prevent infinite SIGTTOU.
2010 */
2011 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04002012 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002013 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002014
2015 /* Not a signal, just exit */
2016 if (sig <= 0)
2017 _exit(- sig);
2018
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00002019 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002020}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002021#else
2022
Denys Vlasenko8391c482010-05-22 17:50:43 +02002023# define disable_restore_tty_pgrp_on_exit() ((void)0)
2024# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002025
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002026#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002027
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002028static sighandler_t pick_sighandler(unsigned sig)
2029{
2030 sighandler_t handler = SIG_DFL;
2031 if (sig < sizeof(unsigned)*8) {
2032 unsigned sigmask = (1 << sig);
2033
2034#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002035 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002036 if (G_fatal_sig_mask & sigmask)
2037 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002038 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002039#endif
2040 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002041 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002042 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002043 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002044 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002045 * in an endless loop when we try to do some
2046 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002047 */
2048 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2049 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002050 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002051 }
2052 return handler;
2053}
2054
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002055/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002056static void hush_exit(int exitcode)
2057{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002058#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
Denys Vlasenko76a4e832019-05-19 18:24:52 +02002059 if (G.line_input_state)
2060 save_history(G.line_input_state);
Denys Vlasenkobede2152011-09-04 16:12:33 +02002061#endif
2062
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002063 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002064 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002065 char *argv[3];
2066 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002067 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002068 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002069 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002070 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002071 * "trap" will still show it, if executed
2072 * in the handler */
2073 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002074 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002075
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002076#if ENABLE_FEATURE_CLEAN_UP
2077 {
2078 struct variable *cur_var;
2079 if (G.cwd != bb_msg_unknown)
2080 free((char*)G.cwd);
2081 cur_var = G.top_var;
2082 while (cur_var) {
2083 struct variable *tmp = cur_var;
2084 if (!cur_var->max_len)
2085 free(cur_var->varstr);
2086 cur_var = cur_var->next;
2087 free(tmp);
2088 }
2089 }
2090#endif
2091
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002092 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002093#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002094 sigexit(- (exitcode & 0xff));
2095#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002096 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002097#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002098}
2099
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002100
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002101//TODO: return a mask of ALL handled sigs?
2102static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002103{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002104 int last_sig = 0;
2105
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002106 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002107 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002108
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002109 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002110 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002111 sig = 0;
2112 do {
2113 sig++;
2114 if (sigismember(&G.pending_set, sig)) {
2115 sigdelset(&G.pending_set, sig);
2116 goto got_sig;
2117 }
2118 } while (sig < NSIG);
2119 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002120 got_sig:
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002121#if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002122 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002123 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002124 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002125 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002126 smalluint save_rcode;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002127 int save_pre;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002128 char *argv[3];
2129 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002130 argv[1] = xstrdup(G_traps[sig]);
2131 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002132 argv[2] = NULL;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002133 save_pre = G.pre_trap_exitcode;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01002134 G.pre_trap_exitcode = save_rcode = G.last_exitcode;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002135 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002136 free(argv[1]);
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002137 G.pre_trap_exitcode = save_pre;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002138 G.last_exitcode = save_rcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002139# if ENABLE_HUSH_FUNCTIONS
2140 if (G.return_exitcode >= 0) {
2141 debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
2142 G.last_exitcode = G.return_exitcode;
2143 }
2144# endif
Denys Vlasenkob8709032011-05-08 21:20:01 +02002145 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002146 } /* else: "" trap, ignoring signal */
2147 continue;
2148 }
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002149#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002150 /* not a trap: special action */
2151 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002152 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002153 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002154 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002155 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002156 break;
2157#if ENABLE_HUSH_JOB
2158 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002159//TODO: why are we doing this? ash and dash don't do this,
2160//they have no handler for SIGHUP at all,
2161//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002162 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002163 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002164 /* bash is observed to signal whole process groups,
2165 * not individual processes */
2166 for (job = G.job_list; job; job = job->next) {
2167 if (job->pgrp <= 0)
2168 continue;
2169 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2170 if (kill(- job->pgrp, SIGHUP) == 0)
2171 kill(- job->pgrp, SIGCONT);
2172 }
2173 sigexit(SIGHUP);
2174 }
2175#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002176#if ENABLE_HUSH_FAST
2177 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002178 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002179 G.count_SIGCHLD++;
2180//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2181 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002182 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002183 * This simplifies wait builtin a bit.
2184 */
2185 break;
2186#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002187 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002188 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002189 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002190 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002191 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002192 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002193 * in interactive shell, because TERM is ignored.
2194 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002195 break;
2196 }
2197 }
2198 return last_sig;
2199}
2200
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002201
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002202static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002203{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002204 if (force || G.cwd == NULL) {
2205 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2206 * we must not try to free(bb_msg_unknown) */
2207 if (G.cwd == bb_msg_unknown)
2208 G.cwd = NULL;
2209 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2210 if (!G.cwd)
2211 G.cwd = bb_msg_unknown;
2212 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002213 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002214}
2215
Denis Vlasenko83506862007-11-23 13:11:42 +00002216
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002217/*
2218 * Shell and environment variable support
2219 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002220static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002221{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002222 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002223 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002224
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002225 pp = &G.top_var;
2226 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002227 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002228 return pp;
2229 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002230 }
2231 return NULL;
2232}
2233
Denys Vlasenko03dad222010-01-12 23:29:57 +01002234static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002235{
Denys Vlasenko29082232010-07-16 13:52:32 +02002236 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002237 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002238
2239 if (G.expanded_assignments) {
2240 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002241 while (*cpp) {
2242 char *cp = *cpp;
2243 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2244 return cp + len + 1;
2245 cpp++;
2246 }
2247 }
2248
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002249 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002250 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002251 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002252
Denys Vlasenkodea47882009-10-09 15:40:49 +02002253 if (strcmp(name, "PPID") == 0)
2254 return utoa(G.root_ppid);
2255 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002256#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002257 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002258 return utoa(next_random(&G.random_gen));
2259#endif
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002260#if ENABLE_HUSH_LINENO_VAR
2261 if (strcmp(name, "LINENO") == 0)
2262 return utoa(G.execute_lineno);
2263#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002264#if BASH_EPOCH_VARS
2265 {
2266 const char *fmt = NULL;
2267 if (strcmp(name, "EPOCHSECONDS") == 0)
2268 fmt = "%lu";
2269 else if (strcmp(name, "EPOCHREALTIME") == 0)
2270 fmt = "%lu.%06u";
2271 if (fmt) {
2272 struct timeval tv;
2273 gettimeofday(&tv, NULL);
2274 sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
2275 (unsigned)tv.tv_usec);
2276 return G.epoch_buf;
2277 }
2278 }
2279#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002280 return NULL;
2281}
2282
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002283#if ENABLE_HUSH_GETOPTS
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002284static void handle_changed_special_names(const char *name, unsigned name_len)
2285{
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002286 if (name_len == 6) {
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002287 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002288 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002289 return;
2290 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002291 }
2292}
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002293#else
2294/* Do not even bother evaluating arguments */
2295# define handle_changed_special_names(...) ((void)0)
2296#endif
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002297
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002298/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002299 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002300 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002301#define SETFLAG_EXPORT (1 << 0)
2302#define SETFLAG_UNEXPORT (1 << 1)
2303#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002304#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002305static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002306{
Denys Vlasenko61407802018-04-04 21:14:28 +02002307 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002308 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002309 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002310 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002311 int name_len;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002312 int retval;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002313 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002314
Denis Vlasenko950bd722009-04-21 11:23:56 +00002315 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002316 if (HUSH_DEBUG && !eq_sign)
James Byrne69374872019-07-02 11:35:03 +02002317 bb_simple_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002318
Denis Vlasenko950bd722009-04-21 11:23:56 +00002319 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002320 cur_pp = &G.top_var;
2321 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002322 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002323 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002324 continue;
2325 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002326
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002327 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002328 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002329 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002330 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002331//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2332//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002333 return -1;
2334 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002335 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002336 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2337 *eq_sign = '\0';
2338 unsetenv(str);
2339 *eq_sign = '=';
2340 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002341 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002342 /* bash 3.2.33(1) and exported vars:
2343 * # export z=z
2344 * # f() { local z=a; env | grep ^z; }
2345 * # f
2346 * z=a
2347 * # env | grep ^z
2348 * z=z
2349 */
2350 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002351 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002352 /* New variable is local ("local VAR=VAL" or
2353 * "VAR=VAL cmd")
2354 * and existing one is global, or local
2355 * on a lower level that new one.
2356 * Remove it from global variable list:
2357 */
2358 *cur_pp = cur->next;
2359 if (G.shadowed_vars_pp) {
2360 /* Save in "shadowed" list */
2361 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2362 cur->flg_export ? "exported " : "",
2363 cur->varstr, cur->var_nest_level, str, local_lvl
2364 );
2365 cur->next = *G.shadowed_vars_pp;
2366 *G.shadowed_vars_pp = cur;
2367 } else {
2368 /* Came from pseudo_exec_argv(), no need to save: delete it */
2369 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2370 cur->flg_export ? "exported " : "",
2371 cur->varstr, cur->var_nest_level, str, local_lvl
2372 );
2373 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2374 free_me = cur->varstr; /* then free it later */
2375 free(cur);
2376 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002377 break;
2378 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002379
Denis Vlasenko950bd722009-04-21 11:23:56 +00002380 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002381 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002382 free_and_exp:
2383 free(str);
2384 goto exp;
2385 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002386
2387 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002388 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002389 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002390 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002391 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002392 strcpy(cur->varstr, str);
2393 goto free_and_exp;
2394 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002395 /* Can't reuse */
2396 cur->max_len = 0;
2397 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002398 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002399 /* max_len == 0 signifies "malloced" var, which we can
2400 * (and have to) free. But we can't free(cur->varstr) here:
2401 * if cur->flg_export is 1, it is in the environment.
2402 * We should either unsetenv+free, or wait until putenv,
2403 * then putenv(new)+free(old).
2404 */
2405 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002406 goto set_str_and_exp;
2407 }
2408
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002409 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002410 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002411 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002412 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002413 cur->next = *cur_pp;
2414 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002415
2416 set_str_and_exp:
2417 cur->varstr = str;
2418 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002419#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002420 if (flags & SETFLAG_MAKE_RO) {
2421 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002422 }
2423#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002424 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002425 cur->flg_export = 1;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002426 retval = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002427 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002428 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002429 cur->flg_export = 0;
2430 /* unsetenv was already done */
2431 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002432 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002433 retval = putenv(cur->varstr);
2434 /* fall through to "free(free_me)" -
2435 * only now we can free old exported malloced string
2436 */
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002437 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002438 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002439 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002440
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002441 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002442
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002443 return retval;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002444}
2445
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002446static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2447{
2448 char *var = xasprintf("%s=%s", name, val);
2449 set_local_var(var, /*flag:*/ 0);
2450}
2451
Denys Vlasenko6db47842009-09-05 20:15:17 +02002452/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002453static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002454{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002455 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002456}
2457
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002458#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002459static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002460{
2461 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002462 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002463
Denys Vlasenko61407802018-04-04 21:14:28 +02002464 cur_pp = &G.top_var;
2465 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002466 if (strncmp(cur->varstr, name, name_len) == 0
2467 && cur->varstr[name_len] == '='
2468 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002469 if (cur->flg_read_only) {
2470 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002471 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002472 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002473
Denys Vlasenko61407802018-04-04 21:14:28 +02002474 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002475 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2476 bb_unsetenv(cur->varstr);
2477 if (!cur->max_len)
2478 free(cur->varstr);
2479 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002480
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002481 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002482 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002483 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002484 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002485
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002486 /* Handle "unset LINENO" et al even if did not find the variable to unset */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002487 handle_changed_special_names(name, name_len);
2488
Mike Frysingerd690f682009-03-30 06:50:54 +00002489 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002490}
2491
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002492static int unset_local_var(const char *name)
2493{
2494 return unset_local_var_len(name, strlen(name));
2495}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002496#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002497
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002498
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002499/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002500 * Helpers for "var1=val1 var2=val2 cmd" feature
2501 */
2502static void add_vars(struct variable *var)
2503{
2504 struct variable *next;
2505
2506 while (var) {
2507 next = var->next;
2508 var->next = G.top_var;
2509 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002510 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002511 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002512 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002513 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002514 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002515 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002516 var = next;
2517 }
2518}
2519
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002520/* We put strings[i] into variable table and possibly putenv them.
2521 * If variable is read only, we can free the strings[i]
2522 * which attempts to overwrite it.
2523 * The strings[] vector itself is freed.
2524 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002525static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002526{
2527 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002528
2529 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002530 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002531
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002532 s = strings;
2533 while (*s) {
2534 struct variable *var_p;
2535 struct variable **var_pp;
2536 char *eq;
2537
2538 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002539 if (HUSH_DEBUG && !eq)
James Byrne69374872019-07-02 11:35:03 +02002540 bb_simple_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002541 var_pp = get_ptr_to_local_var(*s, eq - *s);
2542 if (var_pp) {
2543 var_p = *var_pp;
2544 if (var_p->flg_read_only) {
2545 char **p;
2546 bb_error_msg("%s: readonly variable", *s);
2547 /*
2548 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2549 * If VAR is readonly, leaving it in the list
2550 * after asssignment error (msg above)
2551 * causes doubled error message later, on unset.
2552 */
2553 debug_printf_env("removing/freeing '%s' element\n", *s);
2554 free(*s);
2555 p = s;
2556 do { *p = p[1]; p++; } while (*p);
2557 goto next;
2558 }
2559 /* below, set_local_var() with nest level will
2560 * "shadow" (remove) this variable from
2561 * global linked list.
2562 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002563 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002564 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2565 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002566 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002567 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002568 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002569 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002570}
2571
2572
2573/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002574 * Unicode helper
2575 */
2576static void reinit_unicode_for_hush(void)
2577{
2578 /* Unicode support should be activated even if LANG is set
2579 * _during_ shell execution, not only if it was set when
2580 * shell was started. Therefore, re-check LANG every time:
2581 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002582 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2583 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002584 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002585 const char *s = get_local_var_value("LC_ALL");
2586 if (!s) s = get_local_var_value("LC_CTYPE");
2587 if (!s) s = get_local_var_value("LANG");
2588 reinit_unicode(s);
2589 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002590}
2591
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002592/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002593 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002594 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002595
2596#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002597/* To test correct lineedit/interactive behavior, type from command line:
2598 * echo $P\
2599 * \
2600 * AT\
2601 * H\
2602 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002603 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002604 */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002605static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002606{
2607 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002608
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002609 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002610
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002611# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2612 prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
2613 if (!prompt_str)
2614 prompt_str = "";
2615# else
2616 prompt_str = "> "; /* if PS2, else... */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002617 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002618 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2619 free(G.PS1);
2620 /* bash uses $PWD value, even if it is set by user.
2621 * It uses current dir only if PWD is unset.
2622 * We always use current dir. */
2623 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002624 }
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002625# endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002626 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002627 return prompt_str;
2628}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002629static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002630{
2631 int r;
2632 const char *prompt_str;
2633
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002634 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002635# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002636 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002637 reinit_unicode_for_hush();
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002638 G.flag_SIGINT = 0;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002639 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002640 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002641 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002642 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002643 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002644 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002645 if (r == 0) {
2646 G.flag_ctrlC = 1;
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002647 raise(SIGINT);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002648 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002649 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002650 if (r != 0 && !G.flag_SIGINT)
2651 break;
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002652 /* ^C or SIGINT: return EOF */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002653 /* bash prints ^C even on real SIGINT (non-kbd generated) */
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002654 write(STDOUT_FILENO, "^C\n", 3);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002655 G.last_exitcode = 128 + SIGINT;
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002656 i->p = NULL;
2657 i->peek_buf[0] = r = EOF;
2658 return r;
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002659 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002660 if (r < 0) {
2661 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002662 i->p = NULL;
2663 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002664 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002665 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002666 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002667 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002668# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002669 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002670 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002671 if (i->last_char == '\0' || i->last_char == '\n') {
2672 /* Why check_and_run_traps here? Try this interactively:
2673 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2674 * $ <[enter], repeatedly...>
2675 * Without check_and_run_traps, handler never runs.
2676 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002677 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002678 fputs(prompt_str, stdout);
2679 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002680 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002681//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002682 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002683 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2684 * no ^C masking happens during fgetc, no special code for ^C:
2685 * it generates SIGINT as usual.
2686 */
2687 check_and_run_traps();
2688 if (G.flag_SIGINT)
2689 G.last_exitcode = 128 + SIGINT;
2690 if (r != '\0')
2691 break;
2692 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002693 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002694# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002695}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002696/* This is the magic location that prints prompts
2697 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002698static int fgetc_interactive(struct in_str *i)
2699{
2700 int ch;
2701 /* If it's interactive stdin, get new line. */
Denys Vlasenko21806562019-11-01 14:16:07 +01002702 if (G_interactive_fd && i->file == G.HFILE_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002703 /* Returns first char (or EOF), the rest is in i->p[] */
2704 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002705 G.promptmode = 1; /* PS2 */
2706 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002707 } else {
2708 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002709 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002710 }
2711 return ch;
2712}
2713#else
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002714static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002715{
2716 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002717 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002718 return ch;
2719}
2720#endif /* INTERACTIVE */
2721
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002722static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002723{
2724 int ch;
2725
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002726 if (!i->file) {
2727 /* string-based in_str */
2728 ch = (unsigned char)*i->p;
2729 if (ch != '\0') {
2730 i->p++;
2731 i->last_char = ch;
2732 return ch;
2733 }
2734 return EOF;
2735 }
2736
2737 /* FILE-based in_str */
2738
Denys Vlasenko4074d492016-09-30 01:49:53 +02002739#if ENABLE_FEATURE_EDITING
2740 /* This can be stdin, check line editing char[] buffer */
2741 if (i->p && *i->p != '\0') {
2742 ch = (unsigned char)*i->p++;
2743 goto out;
2744 }
2745#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002746 /* peek_buf[] is an int array, not char. Can contain EOF. */
2747 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002748 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002749 int ch2 = i->peek_buf[1];
2750 i->peek_buf[0] = ch2;
2751 if (ch2 == 0) /* very likely, avoid redundant write */
2752 goto out;
2753 i->peek_buf[1] = 0;
2754 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002755 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002756
Denys Vlasenko4074d492016-09-30 01:49:53 +02002757 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002758 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002759 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002760 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002761#if ENABLE_HUSH_LINENO_VAR
2762 if (ch == '\n') {
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002763 G.parse_lineno++;
2764 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
Denys Vlasenko5807e182018-02-08 19:19:04 +01002765 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002766#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002767 return ch;
2768}
2769
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002770static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002771{
2772 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002773
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002774 if (!i->file) {
2775 /* string-based in_str */
2776 /* Doesn't report EOF on NUL. None of the callers care. */
2777 return (unsigned char)*i->p;
2778 }
2779
2780 /* FILE-based in_str */
2781
Denys Vlasenko4074d492016-09-30 01:49:53 +02002782#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002783 /* This can be stdin, check line editing char[] buffer */
2784 if (i->p && *i->p != '\0')
2785 return (unsigned char)*i->p;
2786#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002787 /* peek_buf[] is an int array, not char. Can contain EOF. */
2788 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002789 if (ch != 0)
2790 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002791
Denys Vlasenko4074d492016-09-30 01:49:53 +02002792 /* Need to get a new char */
2793 ch = fgetc_interactive(i);
2794 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2795
2796 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2797#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2798 if (i->p) {
2799 i->p -= 1;
2800 return ch;
2801 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002802#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002803 i->peek_buf[0] = ch;
2804 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002805 return ch;
2806}
2807
Denys Vlasenko4074d492016-09-30 01:49:53 +02002808/* Only ever called if i_peek() was called, and did not return EOF.
2809 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2810 * not end-of-line. Therefore we never need to read a new editing line here.
2811 */
2812static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002813{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002814 int ch;
2815
2816 /* There are two cases when i->p[] buffer exists.
2817 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002818 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002819 * In both cases, we know that i->p[0] exists and not NUL, and
2820 * the peek2 result is in i->p[1].
2821 */
2822 if (i->p)
2823 return (unsigned char)i->p[1];
2824
2825 /* Now we know it is a file-based in_str. */
2826
2827 /* peek_buf[] is an int array, not char. Can contain EOF. */
2828 /* Is there 2nd char? */
2829 ch = i->peek_buf[1];
2830 if (ch == 0) {
2831 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002832 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002833 i->peek_buf[1] = ch;
2834 }
2835
2836 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2837 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002838}
2839
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002840static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2841{
2842 for (;;) {
2843 int ch, ch2;
2844
2845 ch = i_getch(input);
2846 if (ch != '\\')
2847 return ch;
2848 ch2 = i_peek(input);
2849 if (ch2 != '\n')
2850 return ch;
2851 /* backslash+newline, skip it */
2852 i_getch(input);
2853 }
2854}
2855
2856/* Note: this function _eats_ \<newline> pairs, safe to use plain
2857 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2858 */
2859static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2860{
2861 for (;;) {
2862 int ch, ch2;
2863
2864 ch = i_peek(input);
2865 if (ch != '\\')
2866 return ch;
2867 ch2 = i_peek2(input);
2868 if (ch2 != '\n')
2869 return ch;
2870 /* backslash+newline, skip it */
2871 i_getch(input);
2872 i_getch(input);
2873 }
2874}
2875
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002876static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002877{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002878 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002879 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002880 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002881}
2882
2883static void setup_string_in_str(struct in_str *i, const char *s)
2884{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002885 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002886 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002887 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002888}
2889
2890
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002891/*
2892 * o_string support
2893 */
2894#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002895
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002896static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002897{
2898 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002899 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002900 if (o->data)
2901 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002902}
2903
Denys Vlasenko18567402018-07-20 17:51:31 +02002904static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002905{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002906 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002907 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002908}
2909
Denys Vlasenko18567402018-07-20 17:51:31 +02002910static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002911{
2912 free(o->data);
2913}
2914
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002915static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002916{
2917 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002918 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002919 o->data = xrealloc(o->data, 1 + o->maxlen);
2920 }
2921}
2922
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002923static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002924{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002925 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002926 if (o->length < o->maxlen) {
2927 /* likely. avoid o_grow_by() call */
2928 add:
2929 o->data[o->length] = ch;
2930 o->length++;
2931 o->data[o->length] = '\0';
2932 return;
2933 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002934 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002935 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002936}
2937
Denys Vlasenko657086a2016-09-29 18:07:42 +02002938#if 0
2939/* Valid only if we know o_string is not empty */
2940static void o_delchr(o_string *o)
2941{
2942 o->length--;
2943 o->data[o->length] = '\0';
2944}
2945#endif
2946
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002947static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002948{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002949 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002950 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002951 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002952}
2953
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002954static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002955{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002956 o_addblock(o, str, strlen(str));
2957}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002958
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002959static void o_addstr_with_NUL(o_string *o, const char *str)
2960{
2961 o_addblock(o, str, strlen(str) + 1);
2962}
2963
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002964#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002965static void nommu_addchr(o_string *o, int ch)
2966{
2967 if (o)
2968 o_addchr(o, ch);
2969}
2970#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002971# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002972#endif
2973
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002974#if ENABLE_HUSH_MODE_X
2975static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002976{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002977 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00002978}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002979static void x_mode_addstr(const char *str)
2980{
2981 o_addstr(&G.x_mode_buf, str);
2982}
2983static void x_mode_addblock(const char *str, int len)
2984{
2985 o_addblock(&G.x_mode_buf, str, len);
2986}
2987static void x_mode_prefix(void)
2988{
2989 int n = G.x_mode_depth;
2990 do x_mode_addchr('+'); while (--n >= 0);
2991}
2992static void x_mode_flush(void)
2993{
2994 int len = G.x_mode_buf.length;
2995 if (len <= 0)
2996 return;
2997 if (G.x_mode_fd > 0) {
2998 G.x_mode_buf.data[len] = '\n';
2999 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
3000 }
3001 G.x_mode_buf.length = 0;
3002}
3003#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00003004
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003005/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02003006 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003007 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
3008 * Apparently, on unquoted $v bash still does globbing
3009 * ("v='*.txt'; echo $v" prints all .txt files),
3010 * but NOT brace expansion! Thus, there should be TWO independent
3011 * quoting mechanisms on $v expansion side: one protects
3012 * $v from brace expansion, and other additionally protects "$v" against globbing.
3013 * We have only second one.
3014 */
3015
Denys Vlasenko9e800222010-10-03 14:28:04 +02003016#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003017# define MAYBE_BRACES "{}"
3018#else
3019# define MAYBE_BRACES ""
3020#endif
3021
Eric Andersen25f27032001-04-26 23:22:31 +00003022/* My analysis of quoting semantics tells me that state information
3023 * is associated with a destination, not a source.
3024 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003025static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00003026{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003027 int sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003028 /* '-' is included because of this case:
3029 * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
3030 */
3031 char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003032 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003033 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003034 o_grow_by(o, sz);
3035 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003036 o->data[o->length] = '\\';
3037 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003038 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003039 o->data[o->length] = ch;
3040 o->length++;
3041 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003042}
3043
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003044static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003045{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003046 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003047 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003048 && strchr("*?[-\\" MAYBE_BRACES, ch)
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003049 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003050 sz++;
3051 o->data[o->length] = '\\';
3052 o->length++;
3053 }
3054 o_grow_by(o, sz);
3055 o->data[o->length] = ch;
3056 o->length++;
3057 o->data[o->length] = '\0';
3058}
3059
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003060static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003061{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003062 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003063 char ch;
3064 int sz;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003065 int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003066 if (ordinary_cnt > len) /* paranoia */
3067 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003068 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003069 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003070 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003071 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003072 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003073
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003074 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003075 sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003076 if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003077 sz++;
3078 o->data[o->length] = '\\';
3079 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003080 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003081 o_grow_by(o, sz);
3082 o->data[o->length] = ch;
3083 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003084 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003085 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003086}
3087
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003088static void o_addQblock(o_string *o, const char *str, int len)
3089{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003090 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003091 o_addblock(o, str, len);
3092 return;
3093 }
3094 o_addqblock(o, str, len);
3095}
3096
Denys Vlasenko38292b62010-09-05 14:49:40 +02003097static void o_addQstr(o_string *o, const char *str)
3098{
3099 o_addQblock(o, str, strlen(str));
3100}
3101
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003102/* A special kind of o_string for $VAR and `cmd` expansion.
3103 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003104 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003105 * list[i] contains an INDEX (int!) into this string data.
3106 * It means that if list[] needs to grow, data needs to be moved higher up
3107 * but list[i]'s need not be modified.
3108 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003109 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003110 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3111 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003112#if DEBUG_EXPAND || DEBUG_GLOB
3113static void debug_print_list(const char *prefix, o_string *o, int n)
3114{
3115 char **list = (char**)o->data;
3116 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3117 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003118
3119 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003120 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 +02003121 prefix, list, n, string_start, o->length, o->maxlen,
3122 !!(o->o_expflags & EXP_FLAG_GLOB),
3123 o->has_quoted_part,
3124 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003125 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003126 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003127 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3128 o->data + (int)(uintptr_t)list[i] + string_start,
3129 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003130 i++;
3131 }
3132 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003133 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003134 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003135 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003136 }
3137}
3138#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003139# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003140#endif
3141
3142/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3143 * in list[n] so that it points past last stored byte so far.
3144 * It returns n+1. */
3145static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003146{
3147 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003148 int string_start;
3149 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003150
3151 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003152 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3153 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003154 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003155 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003156 /* list[n] points to string_start, make space for 16 more pointers */
3157 o->maxlen += 0x10 * sizeof(list[0]);
3158 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003159 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003160 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003161 /*
3162 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3163 * check. (grep for -prev-ifs-check-).
3164 * Ensure that argv[-1][last] is not garbage
3165 * but zero bytes, to save index check there.
3166 */
3167 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003168 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003169 } else {
3170 debug_printf_list("list[%d]=%d string_start=%d\n",
3171 n, string_len, string_start);
3172 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003173 } else {
3174 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003175 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3176 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003177 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3178 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003179 o->has_empty_slot = 0;
3180 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003181 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003182 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003183 return n + 1;
3184}
3185
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003186/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003187static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003188{
3189 char **list = (char**)o->data;
3190 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3191
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003192 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003193}
3194
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003195/*
3196 * Globbing routines.
3197 *
3198 * Most words in commands need to be globbed, even ones which are
3199 * (single or double) quoted. This stems from the possiblity of
3200 * constructs like "abc"* and 'abc'* - these should be globbed.
3201 * Having a different code path for fully-quoted strings ("abc",
3202 * 'abc') would only help performance-wise, but we still need
3203 * code for partially-quoted strings.
3204 *
3205 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003206 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003207 * to a string, then globbed, and if globbing does not match anything,
3208 * it is used verbatim". Here are two examples where it fails:
3209 *
3210 * echo 'b\*'?
3211 *
3212 * The globbing can't be avoided (because of '?' at the end).
3213 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3214 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003215 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003216 * Now, look at this:
3217 *
3218 * v='\\\*'; echo b$v?
3219 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003220 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003221 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003222 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003223 *
3224 * ash implements this by having an encoded representation of the word
3225 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3226 * Glob pattern is derived from it. If glob fails, the decision what result
3227 * should be is made using that encoded representation. Not glob pattern.
3228 */
3229
Denys Vlasenko9e800222010-10-03 14:28:04 +02003230#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003231/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3232 * first, it processes even {a} (no commas), second,
3233 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003234 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003235 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003236
3237/* Helper */
3238static int glob_needed(const char *s)
3239{
3240 while (*s) {
3241 if (*s == '\\') {
3242 if (!s[1])
3243 return 0;
3244 s += 2;
3245 continue;
3246 }
3247 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3248 return 1;
3249 s++;
3250 }
3251 return 0;
3252}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003253/* Return pointer to next closing brace or to comma */
3254static const char *next_brace_sub(const char *cp)
3255{
3256 unsigned depth = 0;
3257 cp++;
3258 while (*cp != '\0') {
3259 if (*cp == '\\') {
3260 if (*++cp == '\0')
3261 break;
3262 cp++;
3263 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003264 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003265 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003266 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003267 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003268 depth++;
3269 }
3270
3271 return *cp != '\0' ? cp : NULL;
3272}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003273/* Recursive brace globber. Note: may garble pattern[]. */
3274static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003275{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003276 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003277 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003278 const char *next;
3279 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003280 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003281 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003282
3283 debug_printf_glob("glob_brace('%s')\n", pattern);
3284
3285 begin = pattern;
3286 while (1) {
3287 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003288 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003289 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003290 /* Find the first sub-pattern and at the same time
3291 * find the rest after the closing brace */
3292 next = next_brace_sub(begin);
3293 if (next == NULL) {
3294 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003295 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003296 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003297 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003298 /* "{abc}" with no commas - illegal
3299 * brace expr, disregard and skip it */
3300 begin = next + 1;
3301 continue;
3302 }
3303 break;
3304 }
3305 if (*begin == '\\' && begin[1] != '\0')
3306 begin++;
3307 begin++;
3308 }
3309 debug_printf_glob("begin:%s\n", begin);
3310 debug_printf_glob("next:%s\n", next);
3311
3312 /* Now find the end of the whole brace expression */
3313 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003314 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003315 rest = next_brace_sub(rest);
3316 if (rest == NULL) {
3317 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003318 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003319 }
3320 debug_printf_glob("rest:%s\n", rest);
3321 }
3322 rest_len = strlen(++rest) + 1;
3323
3324 /* We are sure the brace expression is well-formed */
3325
3326 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003327 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003328
3329 /* We have a brace expression. BEGIN points to the opening {,
3330 * NEXT points past the terminator of the first element, and REST
3331 * points past the final }. We will accumulate result names from
3332 * recursive runs for each brace alternative in the buffer using
3333 * GLOB_APPEND. */
3334
3335 p = begin + 1;
3336 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003337 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003338 memcpy(
3339 mempcpy(
3340 mempcpy(new_pattern_buf,
3341 /* We know the prefix for all sub-patterns */
3342 pattern, begin - pattern),
3343 p, next - p),
3344 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003345
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003346 /* Note: glob_brace() may garble new_pattern_buf[].
3347 * That's why we re-copy prefix every time (1st memcpy above).
3348 */
3349 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003350 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003351 /* We saw the last entry */
3352 break;
3353 }
3354 p = next + 1;
3355 next = next_brace_sub(next);
3356 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003357 free(new_pattern_buf);
3358 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003359
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003360 simple_glob:
3361 {
3362 int gr;
3363 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003364
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003365 memset(&globdata, 0, sizeof(globdata));
3366 gr = glob(pattern, 0, NULL, &globdata);
3367 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3368 if (gr != 0) {
3369 if (gr == GLOB_NOMATCH) {
3370 globfree(&globdata);
3371 /* NB: garbles parameter */
3372 unbackslash(pattern);
3373 o_addstr_with_NUL(o, pattern);
3374 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3375 return o_save_ptr_helper(o, n);
3376 }
3377 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003378 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003379 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3380 * but we didn't specify it. Paranoia again. */
3381 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3382 }
3383 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3384 char **argv = globdata.gl_pathv;
3385 while (1) {
3386 o_addstr_with_NUL(o, *argv);
3387 n = o_save_ptr_helper(o, n);
3388 argv++;
3389 if (!*argv)
3390 break;
3391 }
3392 }
3393 globfree(&globdata);
3394 }
3395 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003396}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003397/* Performs globbing on last list[],
3398 * saving each result as a new list[].
3399 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003400static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003401{
3402 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003403
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003404 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003405 if (!o->data)
3406 return o_save_ptr_helper(o, n);
3407 pattern = o->data + o_get_last_ptr(o, n);
3408 debug_printf_glob("glob pattern '%s'\n", pattern);
3409 if (!glob_needed(pattern)) {
3410 /* unbackslash last string in o in place, fix length */
3411 o->length = unbackslash(pattern) - o->data;
3412 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3413 return o_save_ptr_helper(o, n);
3414 }
3415
3416 copy = xstrdup(pattern);
3417 /* "forget" pattern in o */
3418 o->length = pattern - o->data;
3419 n = glob_brace(copy, o, n);
3420 free(copy);
3421 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003422 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003423 return n;
3424}
3425
Denys Vlasenko238081f2010-10-03 14:26:26 +02003426#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003427
3428/* Helper */
3429static int glob_needed(const char *s)
3430{
3431 while (*s) {
3432 if (*s == '\\') {
3433 if (!s[1])
3434 return 0;
3435 s += 2;
3436 continue;
3437 }
3438 if (*s == '*' || *s == '[' || *s == '?')
3439 return 1;
3440 s++;
3441 }
3442 return 0;
3443}
3444/* Performs globbing on last list[],
3445 * saving each result as a new list[].
3446 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003447static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003448{
3449 glob_t globdata;
3450 int gr;
3451 char *pattern;
3452
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003453 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003454 if (!o->data)
3455 return o_save_ptr_helper(o, n);
3456 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003457 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003458 if (!glob_needed(pattern)) {
3459 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003460 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003461 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003462 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003463 return o_save_ptr_helper(o, n);
3464 }
3465
3466 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003467 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3468 * If we glob "*.\*" and don't find anything, we need
3469 * to fall back to using literal "*.*", but GLOB_NOCHECK
3470 * will return "*.\*"!
3471 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003472 gr = glob(pattern, 0, NULL, &globdata);
3473 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003474 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003475 if (gr == GLOB_NOMATCH) {
3476 globfree(&globdata);
3477 goto literal;
3478 }
3479 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003480 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003481 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3482 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003483 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003484 }
3485 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3486 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003487 /* "forget" pattern in o */
3488 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003489 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003490 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003491 n = o_save_ptr_helper(o, n);
3492 argv++;
3493 if (!*argv)
3494 break;
3495 }
3496 }
3497 globfree(&globdata);
3498 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003499 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003500 return n;
3501}
3502
Denys Vlasenko238081f2010-10-03 14:26:26 +02003503#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003504
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003505/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003506 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003507static int o_save_ptr(o_string *o, int n)
3508{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003509 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003510 /* If o->has_empty_slot, list[n] was already globbed
3511 * (if it was requested back then when it was filled)
3512 * so don't do that again! */
3513 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003514 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003515 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003516 return o_save_ptr_helper(o, n);
3517}
3518
3519/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003520static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003521{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003522 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003523 int string_start;
3524
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003525 if (DEBUG_EXPAND)
3526 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003527 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003528 list = (char**)o->data;
3529 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3530 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003531 while (n) {
3532 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003533 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003534 }
3535 return list;
3536}
3537
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003538static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003539
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003540/* Returns pi->next - next pipe in the list */
3541static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003542{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003543 struct pipe *next;
3544 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003545
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003546 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003547 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003548 struct command *command;
3549 struct redir_struct *r, *rnext;
3550
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003551 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003552 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003553 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003554 if (DEBUG_CLEAN) {
3555 int a;
3556 char **p;
3557 for (a = 0, p = command->argv; *p; a++, p++) {
3558 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3559 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003560 }
3561 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003562 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003563 }
3564 /* not "else if": on syntax error, we may have both! */
3565 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003566 debug_printf_clean(" begin group (cmd_type:%d)\n",
3567 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003568 free_pipe_list(command->group);
3569 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003570 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003571 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003572 /* else is crucial here.
3573 * If group != NULL, child_func is meaningless */
3574#if ENABLE_HUSH_FUNCTIONS
3575 else if (command->child_func) {
3576 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3577 command->child_func->parent_cmd = NULL;
3578 }
3579#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003580#if !BB_MMU
3581 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003582 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003583#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003584 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003585 debug_printf_clean(" redirect %d%s",
3586 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003587 /* guard against the case >$FOO, where foo is unset or blank */
3588 if (r->rd_filename) {
3589 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3590 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003591 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003592 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003593 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003594 rnext = r->next;
3595 free(r);
3596 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003597 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003598 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003599 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003600 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003601#if ENABLE_HUSH_JOB
3602 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003603 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003604#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003605
3606 next = pi->next;
3607 free(pi);
3608 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003609}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003610
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003611static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003612{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003613 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003614#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003615 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003616#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003617 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003618 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003619 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003620}
3621
3622
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003623/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003624
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003625#ifndef debug_print_tree
3626static void debug_print_tree(struct pipe *pi, int lvl)
3627{
3628 static const char *const PIPE[] = {
3629 [PIPE_SEQ] = "SEQ",
3630 [PIPE_AND] = "AND",
3631 [PIPE_OR ] = "OR" ,
3632 [PIPE_BG ] = "BG" ,
3633 };
3634 static const char *RES[] = {
3635 [RES_NONE ] = "NONE" ,
3636# if ENABLE_HUSH_IF
3637 [RES_IF ] = "IF" ,
3638 [RES_THEN ] = "THEN" ,
3639 [RES_ELIF ] = "ELIF" ,
3640 [RES_ELSE ] = "ELSE" ,
3641 [RES_FI ] = "FI" ,
3642# endif
3643# if ENABLE_HUSH_LOOPS
3644 [RES_FOR ] = "FOR" ,
3645 [RES_WHILE] = "WHILE",
3646 [RES_UNTIL] = "UNTIL",
3647 [RES_DO ] = "DO" ,
3648 [RES_DONE ] = "DONE" ,
3649# endif
3650# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3651 [RES_IN ] = "IN" ,
3652# endif
3653# if ENABLE_HUSH_CASE
3654 [RES_CASE ] = "CASE" ,
3655 [RES_CASE_IN ] = "CASE_IN" ,
3656 [RES_MATCH] = "MATCH",
3657 [RES_CASE_BODY] = "CASE_BODY",
3658 [RES_ESAC ] = "ESAC" ,
3659# endif
3660 [RES_XXXX ] = "XXXX" ,
3661 [RES_SNTX ] = "SNTX" ,
3662 };
3663 static const char *const CMDTYPE[] = {
3664 "{}",
3665 "()",
3666 "[noglob]",
3667# if ENABLE_HUSH_FUNCTIONS
3668 "func()",
3669# endif
3670 };
3671
3672 int pin, prn;
3673
3674 pin = 0;
3675 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003676 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3677 lvl*2, "",
3678 pin,
3679 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3680 RES[pi->res_word],
3681 pi->followup, PIPE[pi->followup]
3682 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003683 prn = 0;
3684 while (prn < pi->num_cmds) {
3685 struct command *command = &pi->cmds[prn];
3686 char **argv = command->argv;
3687
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003688 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003689 lvl*2, "", prn,
3690 command->assignment_cnt);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003691# if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko5807e182018-02-08 19:19:04 +01003692 fdprintf(2, " LINENO:%u", command->lineno);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003693# endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003694 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003695 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003696 CMDTYPE[command->cmd_type],
3697 argv
3698# if !BB_MMU
3699 , " group_as_string:", command->group_as_string
3700# else
3701 , "", ""
3702# endif
3703 );
3704 debug_print_tree(command->group, lvl+1);
3705 prn++;
3706 continue;
3707 }
3708 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003709 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003710 argv++;
3711 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003712 if (command->redirects)
3713 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003714 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003715 prn++;
3716 }
3717 pi = pi->next;
3718 pin++;
3719 }
3720}
3721#endif /* debug_print_tree */
3722
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003723static struct pipe *new_pipe(void)
3724{
Eric Andersen25f27032001-04-26 23:22:31 +00003725 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003726 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003727 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003728 return pi;
3729}
3730
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003731/* Command (member of a pipe) is complete, or we start a new pipe
3732 * if ctx->command is NULL.
3733 * No errors possible here.
3734 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003735static int done_command(struct parse_context *ctx)
3736{
3737 /* The command is really already in the pipe structure, so
3738 * advance the pipe counter and make a new, null command. */
3739 struct pipe *pi = ctx->pipe;
3740 struct command *command = ctx->command;
3741
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003742#if 0 /* Instead we emit error message at run time */
3743 if (ctx->pending_redirect) {
3744 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003745 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003746 ctx->pending_redirect = NULL;
3747 }
3748#endif
3749
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003750 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003751 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003752 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003753 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003754 }
3755 pi->num_cmds++;
3756 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003757 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003758 } else {
3759 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3760 }
3761
3762 /* Only real trickiness here is that the uncommitted
3763 * command structure is not counted in pi->num_cmds. */
3764 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003765 ctx->command = command = &pi->cmds[pi->num_cmds];
3766 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003767 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003768#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02003769 command->lineno = G.parse_lineno;
3770 debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003771#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003772 return pi->num_cmds; /* used only for 0/nonzero check */
3773}
3774
3775static void done_pipe(struct parse_context *ctx, pipe_style type)
3776{
3777 int not_null;
3778
3779 debug_printf_parse("done_pipe entered, followup %d\n", type);
3780 /* Close previous command */
3781 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003782#if HAS_KEYWORDS
3783 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3784 ctx->ctx_inverted = 0;
3785 ctx->pipe->res_word = ctx->ctx_res_w;
3786#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003787 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3788 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003789 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3790 * in a backgrounded subshell.
3791 */
3792 struct pipe *pi;
3793 struct command *command;
3794
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003795 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003796 pi = ctx->list_head;
3797 while (pi != ctx->pipe) {
3798 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3799 goto no_conv;
3800 pi = pi->next;
3801 }
3802
3803 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3804 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3805 pi = xzalloc(sizeof(*pi));
3806 pi->followup = PIPE_BG;
3807 pi->num_cmds = 1;
3808 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3809 command = &pi->cmds[0];
3810 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3811 command->cmd_type = CMD_NORMAL;
3812 command->group = ctx->list_head;
3813#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003814 command->group_as_string = xstrndup(
3815 ctx->as_string.data,
3816 ctx->as_string.length - 1 /* do not copy last char, "&" */
3817 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003818#endif
3819 /* Replace all pipes in ctx with one newly created */
3820 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003821 } else {
3822 no_conv:
3823 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003824 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003825
3826 /* Without this check, even just <enter> on command line generates
3827 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003828 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003829 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003830#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003831 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003832#endif
3833#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003834 || ctx->ctx_res_w == RES_DONE
3835 || ctx->ctx_res_w == RES_FOR
3836 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003837#endif
3838#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003839 || ctx->ctx_res_w == RES_ESAC
3840#endif
3841 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003842 struct pipe *new_p;
3843 debug_printf_parse("done_pipe: adding new pipe: "
3844 "not_null:%d ctx->ctx_res_w:%d\n",
3845 not_null, ctx->ctx_res_w);
3846 new_p = new_pipe();
3847 ctx->pipe->next = new_p;
3848 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003849 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003850 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003851 * This is used to control execution.
3852 * RES_FOR and RES_IN are NOT sticky (needed to support
3853 * cases where variable or value happens to match a keyword):
3854 */
3855#if ENABLE_HUSH_LOOPS
3856 if (ctx->ctx_res_w == RES_FOR
3857 || ctx->ctx_res_w == RES_IN)
3858 ctx->ctx_res_w = RES_NONE;
3859#endif
3860#if ENABLE_HUSH_CASE
3861 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003862 ctx->ctx_res_w = RES_CASE_BODY;
3863 if (ctx->ctx_res_w == RES_CASE)
3864 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003865#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003866 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003867 /* Create the memory for command, roughly:
3868 * ctx->pipe->cmds = new struct command;
3869 * ctx->command = &ctx->pipe->cmds[0];
3870 */
3871 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003872 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003873 }
3874 debug_printf_parse("done_pipe return\n");
3875}
3876
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003877static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003878{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003879 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003880 if (MAYBE_ASSIGNMENT != 0)
3881 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003882 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003883 /* Create the memory for command, roughly:
3884 * ctx->pipe->cmds = new struct command;
3885 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003886 */
3887 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003888}
3889
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003890/* If a reserved word is found and processed, parse context is modified
3891 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003892 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003893#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003894struct reserved_combo {
3895 char literal[6];
3896 unsigned char res;
3897 unsigned char assignment_flag;
Denys Vlasenko965b7952020-11-30 13:03:03 +01003898 uint32_t flag;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003899};
3900enum {
3901 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003902# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003903 FLAG_IF = (1 << RES_IF ),
3904 FLAG_THEN = (1 << RES_THEN ),
3905 FLAG_ELIF = (1 << RES_ELIF ),
3906 FLAG_ELSE = (1 << RES_ELSE ),
3907 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003908# endif
3909# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003910 FLAG_FOR = (1 << RES_FOR ),
3911 FLAG_WHILE = (1 << RES_WHILE),
3912 FLAG_UNTIL = (1 << RES_UNTIL),
3913 FLAG_DO = (1 << RES_DO ),
3914 FLAG_DONE = (1 << RES_DONE ),
3915 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003916# endif
3917# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003918 FLAG_MATCH = (1 << RES_MATCH),
3919 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003920# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003921 FLAG_START = (1 << RES_XXXX ),
3922};
3923
3924static const struct reserved_combo* match_reserved_word(o_string *word)
3925{
Eric Andersen25f27032001-04-26 23:22:31 +00003926 /* Mostly a list of accepted follow-up reserved words.
3927 * FLAG_END means we are done with the sequence, and are ready
3928 * to turn the compound list into a command.
3929 * FLAG_START means the word must start a new compound list.
3930 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01003931 static const struct reserved_combo reserved_list[] ALIGN4 = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003932# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003933 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3934 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3935 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3936 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3937 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3938 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003939# endif
3940# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003941 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3942 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3943 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3944 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3945 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3946 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003947# endif
3948# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003949 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3950 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003951# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003952 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003953 const struct reserved_combo *r;
3954
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003955 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003956 if (strcmp(word->data, r->literal) == 0)
3957 return r;
3958 }
3959 return NULL;
3960}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003961/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003962 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003963static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003964{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003965# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003966 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003967 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003968 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003969# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003970 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003971
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003972 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003973 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003974 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003975 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003976 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003977
3978 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003979# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003980 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3981 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003982 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003983 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003984# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003985 if (r->flag == 0) { /* '!' */
3986 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003987 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003988 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003989 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003990 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003991 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003992 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003993 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003994 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003995
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003996 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003997 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003998 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003999 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004000 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004001 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004002 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01004003 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004004 } else {
4005 /* "{...} fi" is ok. "{...} if" is not
4006 * Example:
4007 * if { echo foo; } then { echo bar; } fi */
4008 if (ctx->command->group)
4009 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004010 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004011
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004012 ctx->ctx_res_w = r->res;
4013 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004014 ctx->is_assignment = r->assignment_flag;
4015 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004016
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004017 if (ctx->old_flag & FLAG_END) {
4018 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004019
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004020 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004021 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004022 old = ctx->stack;
4023 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004024 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004025# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004026 /* At this point, the compound command's string is in
4027 * ctx->as_string... except for the leading keyword!
4028 * Consider this example: "echo a | if true; then echo a; fi"
4029 * ctx->as_string will contain "true; then echo a; fi",
4030 * with "if " remaining in old->as_string!
4031 */
4032 {
4033 char *str;
4034 int len = old->as_string.length;
4035 /* Concatenate halves */
4036 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004037 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004038 /* Find where leading keyword starts in first half */
4039 str = old->as_string.data + len;
4040 if (str > old->as_string.data)
4041 str--; /* skip whitespace after keyword */
4042 while (str > old->as_string.data && isalpha(str[-1]))
4043 str--;
4044 /* Ugh, we're done with this horrid hack */
4045 old->command->group_as_string = xstrdup(str);
4046 debug_printf_parse("pop, remembering as:'%s'\n",
4047 old->command->group_as_string);
4048 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004049# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004050 *ctx = *old; /* physical copy */
4051 free(old);
4052 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004053 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004054}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004055#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004056
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004057/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004058 * Normal return is 0. Syntax errors return 1.
4059 * Note: on return, word is reset, but not o_free'd!
4060 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004061static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004062{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004063 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004064
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004065 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4066 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004067 debug_printf_parse("done_word return 0: true null, ignored\n");
4068 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004069 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004070
Eric Andersen25f27032001-04-26 23:22:31 +00004071 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004072 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4073 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004074 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004075 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004076 * If the redirection operator is "<<" or "<<-", the word
4077 * that follows the redirection operator shall be
4078 * subjected to quote removal; it is unspecified whether
4079 * any of the other expansions occur. For the other
4080 * redirection operators, the word that follows the
4081 * redirection operator shall be subjected to tilde
4082 * expansion, parameter expansion, command substitution,
4083 * arithmetic expansion, and quote removal.
4084 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004085 * on the word by a non-interactive shell; an interactive
4086 * shell may perform it, but shall do so only when
4087 * the expansion would result in one word."
4088 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004089//bash does not do parameter/command substitution or arithmetic expansion
4090//for _heredoc_ redirection word: these constructs look for exact eof marker
4091// as written:
4092// <<EOF$t
4093// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004094// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4095
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004096 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004097 /* Cater for >\file case:
4098 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4099 * Same with heredocs:
4100 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4101 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004102 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4103 unbackslash(ctx->pending_redirect->rd_filename);
4104 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004105 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004106 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4107 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004108 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004109 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004110 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004111 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004112#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004113# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004114 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004115 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004116 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004117 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004118 /* ctx->ctx_res_w = RES_MATCH; */
4119 ctx->ctx_dsemicolon = 0;
4120 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004121# endif
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004122# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4123 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
4124 && strcmp(ctx->word.data, "]]") == 0
4125 ) {
4126 /* allow "[[ ]] >file" etc */
4127 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4128 } else
4129# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004130 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004131# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004132 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4133 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004134# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004135# if ENABLE_HUSH_CASE
4136 && ctx->ctx_res_w != RES_CASE
4137# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004138 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004139 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004140 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004141 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004142 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004143# if ENABLE_HUSH_LINENO_VAR
4144/* Case:
4145 * "while ...; do
4146 * cmd ..."
4147 * If we don't close the pipe _now_, immediately after "do", lineno logic
4148 * sees "cmd" as starting at "do" - i.e., at the previous line.
4149 */
4150 if (0
4151 IF_HUSH_IF(|| reserved->res == RES_THEN)
4152 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4153 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4154 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4155 ) {
4156 done_pipe(ctx, PIPE_SEQ);
4157 }
4158# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004159 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004160 debug_printf_parse("done_word return %d\n",
4161 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004162 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004163 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004164# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4165 if (strcmp(ctx->word.data, "[[") == 0) {
4166 command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
4167 } else
4168# endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02004169# if defined(CMD_SINGLEWORD_NOGLOB)
4170 if (0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004171 /* In bash, local/export/readonly are special, args
4172 * are assignments and therefore expansion of them
4173 * should be "one-word" expansion:
4174 * $ export i=`echo 'a b'` # one arg: "i=a b"
4175 * compare with:
4176 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4177 * ls: cannot access i=a: No such file or directory
4178 * ls: cannot access b: No such file or directory
4179 * Note: bash 3.2.33(1) does this only if export word
4180 * itself is not quoted:
4181 * $ export i=`echo 'aaa bbb'`; echo "$i"
4182 * aaa bbb
4183 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4184 * aaa
4185 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004186 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4187 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4188 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004189 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004190 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4191 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004192# else
4193 { /* empty block to pair "if ... else" */ }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004194# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004195 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004196#endif /* HAS_KEYWORDS */
4197
Denis Vlasenkobb929512009-04-16 10:59:40 +00004198 if (command->group) {
4199 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004200 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004201 debug_printf_parse("done_word return 1: syntax error, "
4202 "groups and arglists don't mix\n");
4203 return 1;
4204 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004205
4206 /* If this word wasn't an assignment, next ones definitely
4207 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004208 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4209 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004210 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004211 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004212 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004213 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004214 command->assignment_cnt++;
4215 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4216 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004217 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4218 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004219 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004220 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4221 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004222 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004223 }
Eric Andersen25f27032001-04-26 23:22:31 +00004224
Denis Vlasenko06810332007-05-21 23:30:54 +00004225#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004226 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004227 if (ctx->word.has_quoted_part
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02004228 || endofname(command->argv[0])[0] != '\0'
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004229 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004230 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004231 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004232 return 1;
4233 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004234 /* Force FOR to have just one word (variable name) */
4235 /* NB: basically, this makes hush see "for v in ..."
4236 * syntax as if it is "for v; in ...". FOR and IN become
4237 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004238 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004239 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004240#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004241#if ENABLE_HUSH_CASE
4242 /* Force CASE to have just one word */
4243 if (ctx->ctx_res_w == RES_CASE) {
4244 done_pipe(ctx, PIPE_SEQ);
4245 }
4246#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004247
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004248 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004249
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004250 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004251 return 0;
4252}
4253
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004254
4255/* Peek ahead in the input to find out if we have a "&n" construct,
4256 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004257 * Return:
4258 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4259 * REDIRFD_SYNTAX_ERR if syntax error,
4260 * REDIRFD_TO_FILE if no & was seen,
4261 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004262 */
4263#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004264#define parse_redir_right_fd(as_string, input) \
4265 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004266#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004267static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004268{
4269 int ch, d, ok;
4270
4271 ch = i_peek(input);
4272 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004273 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004274
4275 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004276 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004277 ch = i_peek(input);
4278 if (ch == '-') {
4279 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004280 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004281 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004282 }
4283 d = 0;
4284 ok = 0;
4285 while (ch != EOF && isdigit(ch)) {
4286 d = d*10 + (ch-'0');
4287 ok = 1;
4288 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004289 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004290 ch = i_peek(input);
4291 }
4292 if (ok) return d;
4293
4294//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4295
James Byrne69374872019-07-02 11:35:03 +02004296 bb_simple_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004297 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004298}
4299
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004300/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004301 */
4302static int parse_redirect(struct parse_context *ctx,
4303 int fd,
4304 redir_type style,
4305 struct in_str *input)
4306{
4307 struct command *command = ctx->command;
4308 struct redir_struct *redir;
4309 struct redir_struct **redirp;
4310 int dup_num;
4311
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004312 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004313 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004314 /* Check for a '>&1' type redirect */
4315 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4316 if (dup_num == REDIRFD_SYNTAX_ERR)
4317 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004318 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004319 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004320 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004321 if (dup_num) { /* <<-... */
4322 ch = i_getch(input);
4323 nommu_addchr(&ctx->as_string, ch);
4324 ch = i_peek(input);
4325 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004326 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004327
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004328 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004329 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004330 if (ch == '|') {
4331 /* >|FILE redirect ("clobbering" >).
4332 * Since we do not support "set -o noclobber" yet,
4333 * >| and > are the same for now. Just eat |.
4334 */
4335 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004336 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004337 }
4338 }
4339
4340 /* Create a new redir_struct and append it to the linked list */
4341 redirp = &command->redirects;
4342 while ((redir = *redirp) != NULL) {
4343 redirp = &(redir->next);
4344 }
4345 *redirp = redir = xzalloc(sizeof(*redir));
4346 /* redir->next = NULL; */
4347 /* redir->rd_filename = NULL; */
4348 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004349 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004350
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004351 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4352 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004353
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004354 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004355 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004356 /* Erik had a check here that the file descriptor in question
4357 * is legit; I postpone that to "run time"
4358 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004359 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4360 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004361 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004362#if 0 /* Instead we emit error message at run time */
4363 if (ctx->pending_redirect) {
4364 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004365 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004366 }
4367#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004368 /* Set ctx->pending_redirect, so we know what to do at the
4369 * end of the next parsed word. */
4370 ctx->pending_redirect = redir;
4371 }
4372 return 0;
4373}
4374
Eric Andersen25f27032001-04-26 23:22:31 +00004375/* If a redirect is immediately preceded by a number, that number is
4376 * supposed to tell which file descriptor to redirect. This routine
4377 * looks for such preceding numbers. In an ideal world this routine
4378 * needs to handle all the following classes of redirects...
4379 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4380 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4381 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4382 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004383 *
4384 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4385 * "2.7 Redirection
4386 * ... If n is quoted, the number shall not be recognized as part of
4387 * the redirection expression. For example:
4388 * echo \2>a
4389 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004390 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004391 *
4392 * A -1 return means no valid number was found,
4393 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004394 */
4395static int redirect_opt_num(o_string *o)
4396{
4397 int num;
4398
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004399 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004400 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004401 num = bb_strtou(o->data, NULL, 10);
4402 if (errno || num < 0)
4403 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004404 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004405 return num;
4406}
4407
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004408#if BB_MMU
4409#define fetch_till_str(as_string, input, word, skip_tabs) \
4410 fetch_till_str(input, word, skip_tabs)
4411#endif
4412static char *fetch_till_str(o_string *as_string,
4413 struct in_str *input,
4414 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004415 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004416{
4417 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004418 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004419 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004420 int ch;
4421
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004422 /* Starting with "" is necessary for this case:
4423 * cat <<EOF
4424 *
4425 * xxx
4426 * EOF
4427 */
4428 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4429
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004430 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004431
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004432 while (1) {
4433 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004434 if (ch != EOF)
4435 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004436 if (ch == '\n' || ch == EOF) {
4437 check_heredoc_end:
4438 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004439 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004440 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4441 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004442 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004443 return heredoc.data;
4444 }
4445 if (ch == '\n') {
4446 /* This is a new line.
4447 * Remember position and backslash-escaping status.
4448 */
4449 o_addchr(&heredoc, ch);
4450 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004451 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004452 past_EOL = heredoc.length;
4453 /* Get 1st char of next line, possibly skipping leading tabs */
4454 do {
4455 ch = i_getch(input);
4456 if (ch != EOF)
4457 nommu_addchr(as_string, ch);
4458 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4459 /* If this immediately ended the line,
4460 * go back to end-of-line checks.
4461 */
4462 if (ch == '\n')
4463 goto check_heredoc_end;
4464 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004465 } else {
4466 /* Backslash-line continuation in an unquoted
4467 * heredoc. This does not need special handling
4468 * for heredoc body (unquoted heredocs are
4469 * expanded on "execution" and that would take
4470 * care of this case too), but not the case
4471 * of line continuation *in terminator*:
4472 * cat <<EOF
4473 * Ok1
4474 * EO\
4475 * F
4476 */
4477 heredoc.data[--heredoc.length] = '\0';
4478 prev = 0; /* not '\' */
4479 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004480 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004481 }
4482 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004483 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004484 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004485 }
4486 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004487 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004488 if (prev == '\\' && ch == '\\')
4489 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004490 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004491 else
4492 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004493 }
4494}
4495
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004496/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4497 * and load them all. There should be exactly heredoc_cnt of them.
4498 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004499#if BB_MMU
4500#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4501 fetch_heredocs(pi, heredoc_cnt, input)
4502#endif
4503static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004504{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004505 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004506 int i;
4507 struct command *cmd = pi->cmds;
4508
Denys Vlasenko3675c372018-07-23 16:31:21 +02004509 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004510 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004511 cmd->argv ? cmd->argv[0] : "NONE"
4512 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004513 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004514 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004515
Denys Vlasenko3675c372018-07-23 16:31:21 +02004516 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004517 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004518 while (redir) {
4519 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004520 char *p;
4521
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004522 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004523 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004524 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004525 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004526 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004527 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004528 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004529 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004530 free(redir->rd_filename);
4531 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004532 heredoc_cnt--;
4533 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004534 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004535 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004536 if (cmd->group) {
4537 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4538 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4539 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4540 if (heredoc_cnt < 0)
4541 return heredoc_cnt; /* error */
4542 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004543 cmd++;
4544 }
4545 pi = pi->next;
4546 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004547 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004548}
4549
4550
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004551static int run_list(struct pipe *pi);
4552#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004553#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4554 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004555#endif
4556static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004557 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004558 struct in_str *input,
4559 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004560
Denys Vlasenko474cb202018-07-24 13:03:03 +02004561/* Returns number of heredocs not yet consumed,
4562 * or -1 on error.
4563 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004564static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004565 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004566{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004567 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004568 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004569 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004570#if BB_MMU
4571# define as_string NULL
4572#else
4573 char *as_string = NULL;
4574#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004575 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004576 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004577 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004578 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004579
4580 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004581#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004582 if (ch == '(' && !ctx->word.has_quoted_part) {
4583 if (ctx->word.length)
4584 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004585 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004586 if (!command->argv)
4587 goto skip; /* (... */
4588 if (command->argv[1]) { /* word word ... (... */
4589 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004590 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004591 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004592 /* it is "word(..." or "word (..." */
4593 do
4594 ch = i_getch(input);
4595 while (ch == ' ' || ch == '\t');
4596 if (ch != ')') {
4597 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004598 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004599 }
4600 nommu_addchr(&ctx->as_string, ch);
4601 do
4602 ch = i_getch(input);
4603 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004604 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004605 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004606 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004607 }
4608 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004609 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004610 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004611 }
4612#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004613
4614#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004615 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004616 || ctx->word.length /* word{... */
4617 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004618 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004619 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004620 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004621 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004622 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004623 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004624#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004625
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004626 IF_HUSH_FUNCTIONS(skip:)
4627
Denis Vlasenko240c2552009-04-03 03:45:05 +00004628 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004629 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004630 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004631 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4632 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004633 } else {
4634 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004635 ch = i_peek(input);
4636 if (ch != ' ' && ch != '\t' && ch != '\n'
4637 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4638 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004639 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004640 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004641 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004642 if (ch != '(') {
4643 ch = i_getch(input);
4644 nommu_addchr(&ctx->as_string, ch);
4645 }
Eric Andersen25f27032001-04-26 23:22:31 +00004646 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004647
Denys Vlasenko474cb202018-07-24 13:03:03 +02004648 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4649 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4650 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004651#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004652 if (as_string)
4653 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004654#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004655
4656 /* empty ()/{} or parse error? */
4657 if (!pipe_list || pipe_list == ERR_PTR) {
4658 /* parse_stream already emitted error msg */
4659 if (!BB_MMU)
4660 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004661 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004662 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004663 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004664 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004665#if !BB_MMU
4666 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4667 command->group_as_string = as_string;
4668 debug_printf_parse("end of group, remembering as:'%s'\n",
4669 command->group_as_string);
4670#endif
4671
4672#if ENABLE_HUSH_FUNCTIONS
4673 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4674 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4675 struct command *cmd2;
4676
4677 cmd2 = xzalloc(sizeof(*cmd2));
4678 cmd2->cmd_type = CMD_SUBSHELL;
4679 cmd2->group = pipe_list;
4680# if !BB_MMU
4681//UNTESTED!
4682 cmd2->group_as_string = command->group_as_string;
4683 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4684# endif
4685
4686 pipe_list = new_pipe();
4687 pipe_list->cmds = cmd2;
4688 pipe_list->num_cmds = 1;
4689 }
4690#endif
4691
4692 command->group = pipe_list;
4693
Denys Vlasenko474cb202018-07-24 13:03:03 +02004694 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4695 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004696 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004697#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004698}
4699
Denys Vlasenko0b883582016-12-23 16:49:07 +01004700#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004701/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004702/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004703static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004704{
4705 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004706 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004707 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004708 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004709 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004710 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004711 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004712 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004713 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004714 }
4715}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004716static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4717{
4718 while (1) {
4719 int ch = i_getch(input);
4720 if (ch == EOF) {
4721 syntax_error_unterm_ch('\'');
4722 return 0;
4723 }
4724 if (ch == '\'')
4725 return 1;
4726 o_addqchr(dest, ch);
4727 }
4728}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004729/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004730static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004731static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004732{
4733 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004734 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004735 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004736 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004737 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004738 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004739 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004740 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004741 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004742 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004743 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004744 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004745 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004746 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004747 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4748 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004749 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004750 continue;
4751 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004752 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004753 }
4754}
4755/* Process `cmd` - copy contents until "`" is seen. Complicated by
4756 * \` quoting.
4757 * "Within the backquoted style of command substitution, backslash
4758 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4759 * The search for the matching backquote shall be satisfied by the first
4760 * backquote found without a preceding backslash; during this search,
4761 * if a non-escaped backquote is encountered within a shell comment,
4762 * a here-document, an embedded command substitution of the $(command)
4763 * form, or a quoted string, undefined results occur. A single-quoted
4764 * or double-quoted string that begins, but does not end, within the
4765 * "`...`" sequence produces undefined results."
4766 * Example Output
4767 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4768 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004769static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004770{
4771 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004772 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004773 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004774 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004775 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004776 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4777 ch = i_getch(input);
4778 if (ch != '`'
4779 && ch != '$'
4780 && ch != '\\'
4781 && (!in_dquote || ch != '"')
4782 ) {
4783 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004784 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004785 }
4786 if (ch == EOF) {
4787 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004788 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004789 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004790 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004791 }
4792}
4793/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4794 * quoting and nested ()s.
4795 * "With the $(command) style of command substitution, all characters
4796 * following the open parenthesis to the matching closing parenthesis
4797 * constitute the command. Any valid shell script can be used for command,
4798 * except a script consisting solely of redirections which produces
4799 * unspecified results."
4800 * Example Output
4801 * echo $(echo '(TEST)' BEST) (TEST) BEST
4802 * echo $(echo 'TEST)' BEST) TEST) BEST
4803 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004804 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004805 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004806 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004807 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4808 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004809 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004810#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004811static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004812{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004813 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004814 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004815# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004816 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004817# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004818 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4819
Denys Vlasenko259747c2019-11-28 10:28:14 +01004820# if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004821 G.promptmode = 1; /* PS2 */
Denys Vlasenko259747c2019-11-28 10:28:14 +01004822# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004823 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4824
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004825 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004826 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004827 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004828 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004829 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004830 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004831 if (ch == end_ch
4832# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004833 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004834# endif
4835 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004836 if (!dbl)
4837 break;
4838 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004839 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004840 i_getch(input); /* eat second ')' */
4841 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004842 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004843 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004844 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004845 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004846 if (ch == '(' || ch == '{') {
4847 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004848 if (!add_till_closing_bracket(dest, input, ch))
4849 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004850 o_addchr(dest, ch);
4851 continue;
4852 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004853 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004854 if (!add_till_single_quote(dest, input))
4855 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004856 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004857 continue;
4858 }
4859 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004860 if (!add_till_double_quote(dest, input))
4861 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004862 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004863 continue;
4864 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004865 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004866 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4867 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004868 o_addchr(dest, ch);
4869 continue;
4870 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004871 if (ch == '\\') {
4872 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004873 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004874 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004875 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004876 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004877 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004878# if 0
Denys Vlasenko657086a2016-09-29 18:07:42 +02004879 if (ch == '\n') {
4880 /* "backslash+newline", ignore both */
4881 o_delchr(dest); /* undo insertion of '\' */
4882 continue;
4883 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004884# endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004885 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004886 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004887 continue;
4888 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004889 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004890 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004891 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004892}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004893#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004894
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004895/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004896#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004897#define parse_dollar(as_string, dest, input, quote_mask) \
4898 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004899#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004900#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004901static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004902 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004903 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004904{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004905 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004906
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004907 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004908 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004909 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004910 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004911 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004912 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004913 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004914 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004915 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004916 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004917 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004918 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004919 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004920 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004921 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004922 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004923 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004924 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004925 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004926 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004927 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004928 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004929 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004930 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004931 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004932 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004933 o_addchr(dest, ch | quote_mask);
4934 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004935 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004936 case '$': /* pid */
4937 case '!': /* last bg pid */
4938 case '?': /* last exit code */
4939 case '#': /* number of args */
4940 case '*': /* args */
4941 case '@': /* args */
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02004942 case '-': /* $- option flags set by set builtin or shell options (-i etc) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004943 goto make_one_char_var;
4944 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004945 char len_single_ch;
4946
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004947 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4948
Denys Vlasenko74369502010-05-21 19:52:01 +02004949 ch = i_getch(input); /* eat '{' */
4950 nommu_addchr(as_string, ch);
4951
Denys Vlasenko46e64982016-09-29 19:50:55 +02004952 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004953 /* It should be ${?}, or ${#var},
4954 * or even ${?+subst} - operator acting on a special variable,
4955 * or the beginning of variable name.
4956 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004957 if (ch == EOF
4958 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4959 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004960 bad_dollar_syntax:
4961 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004962 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4963 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004964 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004965 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004966 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004967 ch |= quote_mask;
4968
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004969 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004970 * However, this regresses some of our testsuite cases
4971 * which check invalid constructs like ${%}.
4972 * Oh well... let's check that the var name part is fine... */
4973
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004974 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004975 unsigned pos;
4976
Denys Vlasenko74369502010-05-21 19:52:01 +02004977 o_addchr(dest, ch);
4978 debug_printf_parse(": '%c'\n", ch);
4979
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004980 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004981 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004982 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004983 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004984
Denys Vlasenko74369502010-05-21 19:52:01 +02004985 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004986 unsigned end_ch;
4987 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004988 /* handle parameter expansions
4989 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4990 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004991 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4992 if (len_single_ch != '#'
4993 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4994 || i_peek(input) != '}'
4995 ) {
4996 goto bad_dollar_syntax;
4997 }
4998 /* else: it's "length of C" ${#C} op,
4999 * where C is a single char
5000 * special var name, e.g. ${#!}.
5001 */
5002 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005003 /* Eat everything until closing '}' (or ':') */
5004 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005005 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005006 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005007 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005008 ) {
5009 /* It's ${var:N[:M]} thing */
5010 end_ch = '}' * 0x100 + ':';
5011 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005012 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005013 && ch == '/'
5014 ) {
5015 /* It's ${var/[/]pattern[/repl]} thing */
5016 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
5017 i_getch(input);
5018 nommu_addchr(as_string, '/');
5019 ch = '\\';
5020 }
5021 end_ch = '}' * 0x100 + '/';
5022 }
5023 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02005024 /* The pattern can't be empty.
5025 * IOW: if the first char after "${v//" is a slash,
5026 * it does not terminate the pattern - it's the first char of the pattern:
5027 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
5028 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
5029 */
5030 if (i_peek(input) == '/') {
5031 o_addchr(dest, i_getch(input));
5032 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005033 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005034 if (!BB_MMU)
5035 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005036#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005037 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005038 if (last_ch == 0) /* error? */
5039 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005040#else
Denys Vlasenko259747c2019-11-28 10:28:14 +01005041# error Simple code to only allow ${var} is not implemented
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005042#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005043 if (as_string) {
5044 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005045 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005046 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005047
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005048 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5049 && (end_ch & 0xff00)
5050 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005051 /* close the first block: */
5052 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005053 /* while parsing N from ${var:N[:M]}
5054 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005055 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005056 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005057 end_ch = '}';
5058 goto again;
5059 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005060 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005061 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005062 /* it's ${var:N} - emulate :999999999 */
5063 o_addstr(dest, "999999999");
5064 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005065 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005066 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005067 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005068 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005069 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005070 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5071 break;
5072 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005073#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005074 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005075 unsigned pos;
5076
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005077 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005078 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005079# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005080 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005081 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005082 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005083 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01005084 o_addchr(dest, quote_mask | '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005085 if (!BB_MMU)
5086 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005087 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5088 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005089 if (as_string) {
5090 o_addstr(as_string, dest->data + pos);
5091 o_addchr(as_string, ')');
5092 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005093 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005094 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005095 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005096 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005097# endif
5098# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005099 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5100 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005101 if (!BB_MMU)
5102 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005103 if (!add_till_closing_bracket(dest, input, ')'))
5104 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005105 if (as_string) {
5106 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005107 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005108 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005109 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005110# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005111 break;
5112 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005113#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005114 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005115 goto make_var;
5116#if 0
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005117 /* TODO: $_: */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005118 /* $_ Shell or shell script name; or last argument of last command
5119 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5120 * but in command's env, set to full pathname used to invoke it */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005121 ch = i_getch(input);
5122 nommu_addchr(as_string, ch);
5123 ch = i_peek_and_eat_bkslash_nl(input);
5124 if (isalnum(ch)) { /* it's $_name or $_123 */
5125 ch = '_';
5126 goto make_var1;
5127 }
5128 /* else: it's $_ */
5129#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005130 default:
5131 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005132 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005133 debug_printf_parse("parse_dollar return 1 (ok)\n");
5134 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005135#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005136}
5137
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005138#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005139#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005140 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005141#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005142#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005143static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005144 o_string *dest,
5145 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005146 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005147{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005148 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005149 int next;
5150
5151 again:
5152 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005153 if (ch != EOF)
5154 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005155 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005156 debug_printf_parse("encode_string return 1 (ok)\n");
5157 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005158 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005159 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005160 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005161 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005162 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005163 }
5164 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005165 if (ch != '\n') {
5166 next = i_peek(input);
5167 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005168 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005169 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005170 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005171 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005172 /* Testcase: in interactive shell a file with
5173 * echo "unterminated string\<eof>
5174 * is sourced.
5175 */
5176 syntax_error_unterm_ch('"');
5177 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005178 }
5179 /* bash:
5180 * "The backslash retains its special meaning [in "..."]
5181 * only when followed by one of the following characters:
5182 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005183 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005184 * NB: in (unquoted) heredoc, above does not apply to ",
5185 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005186 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005187 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005188 ch = i_getch(input); /* eat next */
5189 if (ch == '\n')
5190 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005191 } /* else: ch remains == '\\', and we double it below: */
5192 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005193 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005194 goto again;
5195 }
5196 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005197 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5198 debug_printf_parse("encode_string return 0: "
5199 "parse_dollar returned 0 (error)\n");
5200 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005201 }
5202 goto again;
5203 }
5204#if ENABLE_HUSH_TICK
5205 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005206 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005207 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5208 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005209 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5210 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005211 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5212 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005213 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005214 }
5215#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005216 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005217 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005218#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005219}
5220
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005221/*
5222 * Scan input until EOF or end_trigger char.
5223 * Return a list of pipes to execute, or NULL on EOF
5224 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005225 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005226 * reset parsing machinery and start parsing anew,
5227 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005228 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005229static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005230 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005231 struct in_str *input,
5232 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005233{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005234 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005235 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005236
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005237 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005238 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005239 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005240 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005241 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005242 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005243
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005244 initialize_context(&ctx);
5245
5246 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5247 * Preventing this:
5248 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005249 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005250
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005251 /* We used to separate words on $IFS here. This was wrong.
5252 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005253 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005254 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005255
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005256 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005257 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005258 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005259 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005260 int ch;
5261 int next;
5262 int redir_fd;
5263 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005264
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005265 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005266 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005267 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005268 if (ch == EOF) {
5269 struct pipe *pi;
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005270#if ENABLE_FEATURE_EDITING
5271 if (G.flag_ctrlC) {
5272 /* testcase: interactively entering
5273 * 'qwe <cr> ^C
5274 * should not leave input in PS2 mode, waiting to close single quote.
5275 */
5276 G.flag_ctrlC = 0;
5277 goto parse_error;
5278 }
5279#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005280 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005281 syntax_error_unterm_str("here document");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005282 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005283 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005284 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005285 syntax_error_unterm_ch('(');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005286 goto parse_error_exitcode1;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005287 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005288 if (end_trigger == '}') {
5289 syntax_error_unterm_ch('{');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005290 goto parse_error_exitcode1;
Denys Vlasenko42246472016-11-07 16:22:35 +01005291 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005292
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005293 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005294 goto parse_error_exitcode1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005295 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005296 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005297 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005298 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005299 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005300 /* (this makes bare "&" cmd a no-op.
5301 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005302 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005303 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005304 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005305 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005306 pi = NULL;
5307 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005308#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005309 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005310 if (pstring)
5311 *pstring = ctx.as_string.data;
5312 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005313 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005314#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005315 // heredoc_cnt must be 0 here anyway
5316 //if (heredoc_cnt_ptr)
5317 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005318 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005319 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005320 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005321 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005322 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005323
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005324 /* Handle "'" and "\" first, as they won't play nice with
5325 * i_peek_and_eat_bkslash_nl() anyway:
5326 * echo z\\
5327 * and
5328 * echo '\
5329 * '
5330 * would break.
5331 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005332 if (ch == '\\') {
5333 ch = i_getch(input);
5334 if (ch == '\n')
5335 continue; /* drop \<newline>, get next char */
5336 nommu_addchr(&ctx.as_string, '\\');
5337 o_addchr(&ctx.word, '\\');
5338 if (ch == EOF) {
5339 /* Testcase: eval 'echo Ok\' */
5340 /* bash-4.3.43 was removing backslash,
5341 * but 4.4.19 retains it, most other shells too
5342 */
5343 continue; /* get next char */
5344 }
5345 /* Example: echo Hello \2>file
5346 * we need to know that word 2 is quoted
5347 */
5348 ctx.word.has_quoted_part = 1;
5349 nommu_addchr(&ctx.as_string, ch);
5350 o_addchr(&ctx.word, ch);
5351 continue; /* get next char */
5352 }
5353 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005354 if (ch == '\'') {
5355 ctx.word.has_quoted_part = 1;
5356 next = i_getch(input);
5357 if (next == '\'' && !ctx.pending_redirect)
5358 goto insert_empty_quoted_str_marker;
5359
5360 ch = next;
5361 while (1) {
5362 if (ch == EOF) {
5363 syntax_error_unterm_ch('\'');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005364 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005365 }
5366 nommu_addchr(&ctx.as_string, ch);
5367 if (ch == '\'')
5368 break;
5369 if (ch == SPECIAL_VAR_SYMBOL) {
5370 /* Convert raw ^C to corresponding special variable reference */
5371 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5372 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5373 }
5374 o_addqchr(&ctx.word, ch);
5375 ch = i_getch(input);
5376 }
5377 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005378 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005379
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005380 next = '\0';
5381 if (ch != '\n')
5382 next = i_peek_and_eat_bkslash_nl(input);
5383
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005384 is_special = "{}<>&|();#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005385 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005386 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005387#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
5388 if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
5389 /* In [[ ]], {}<>&|() are not special */
5390 is_special += 8;
5391 } else
5392#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005393 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005394 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005395 || ctx.word.length /* word{... - non-special */
5396 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005397 || (next != ';' /* }; - special */
5398 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005399 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005400 && next != '&' /* }& and }&& ... - special */
5401 && next != '|' /* }|| ... - special */
5402 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005403 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005404 ) {
5405 /* They are not special, skip "{}" */
5406 is_special += 2;
5407 }
5408 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005409 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005410
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005411 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005412 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005413 o_addQchr(&ctx.word, ch);
5414 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5415 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005416 && ch == '='
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02005417 && endofname(ctx.word.data)[0] == '='
Denis Vlasenko55789c62008-06-18 16:30:42 +00005418 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005419 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5420 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005421 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005422 continue;
5423 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005424
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005425 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005426#if ENABLE_HUSH_LINENO_VAR
5427/* Case:
5428 * "while ...; do<whitespace><newline>
5429 * cmd ..."
5430 * would think that "cmd" starts in <whitespace> -
5431 * i.e., at the previous line.
5432 * We need to skip all whitespace before newlines.
5433 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005434 while (ch != '\n') {
5435 next = i_peek(input);
5436 if (next != ' ' && next != '\t' && next != '\n')
5437 break; /* next char is not ws */
5438 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005439 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005440 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005441#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005442 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005443 goto parse_error_exitcode1;
Eric Andersenaac75e52001-04-30 18:18:45 +00005444 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005445 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005446 /* Is this a case when newline is simply ignored?
5447 * Some examples:
5448 * "cmd | <newline> cmd ..."
5449 * "case ... in <newline> word) ..."
5450 */
5451 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005452 && ctx.word.length == 0
5453 && !ctx.word.has_quoted_part
5454 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005455 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005456 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005457 * Without check #1, interactive shell
5458 * ignores even bare <newline>,
5459 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005460 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005461 * ps2> _ <=== wrong, should be ps1
5462 * Without check #2, "cmd & <newline>"
5463 * is similarly mistreated.
5464 * (BTW, this makes "cmd & cmd"
5465 * and "cmd && cmd" non-orthogonal.
5466 * Really, ask yourself, why
5467 * "cmd && <newline>" doesn't start
5468 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005469 * The only reason is that it might be
5470 * a "cmd1 && <nl> cmd2 &" construct,
5471 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005472 */
5473 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005474 if (pi->num_cmds != 0 /* check #1 */
5475 && pi->followup != PIPE_BG /* check #2 */
5476 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005477 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005478 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005479 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005480 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005481 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005482 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005483 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005484 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5485 if (heredoc_cnt != 0)
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005486 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005487 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005488 ctx.is_assignment = MAYBE_ASSIGNMENT;
5489 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005490 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005491 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005492 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005493 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005494 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005495
5496 /* "cmd}" or "cmd }..." without semicolon or &:
5497 * } is an ordinary char in this case, even inside { cmd; }
5498 * Pathological example: { ""}; } should exec "}" cmd
5499 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005500 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005501 if (ctx.word.length != 0 /* word} */
5502 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005503 ) {
5504 goto ordinary_char;
5505 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005506 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5507 /* Generally, there should be semicolon: "cmd; }"
5508 * However, bash allows to omit it if "cmd" is
5509 * a group. Examples:
5510 * { { echo 1; } }
5511 * {(echo 1)}
5512 * { echo 0 >&2 | { echo 1; } }
5513 * { while false; do :; done }
5514 * { case a in b) ;; esac }
5515 */
5516 if (ctx.command->group)
5517 goto term_group;
5518 goto ordinary_char;
5519 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005520 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005521 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005522 goto skip_end_trigger;
5523 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005524 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005525 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005526 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005527 && (ch != ';' || heredoc_cnt == 0)
5528#if ENABLE_HUSH_CASE
5529 && (ch != ')'
5530 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005531 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005532 )
5533#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005534 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005535 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005536 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005537 }
5538 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005539 ctx.is_assignment = MAYBE_ASSIGNMENT;
5540 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005541 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005542 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005543 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005544 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005545 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005546#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005547 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005548 if (pstring)
5549 *pstring = ctx.as_string.data;
5550 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005551 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005552#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005553 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5554 /* Example: bare "{ }", "()" */
5555 G.last_exitcode = 2; /* bash compat */
5556 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005557 goto parse_error;
Denys Vlasenko39701202017-08-02 19:44:05 +02005558 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005559 if (heredoc_cnt_ptr)
5560 *heredoc_cnt_ptr = heredoc_cnt;
5561 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005562 debug_printf_parse("parse_stream return %p: "
5563 "end_trigger char found\n",
5564 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005565 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005566 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005567 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005568 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005569
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005570 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005571 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005572
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005573 /* Catch <, > before deciding whether this word is
5574 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5575 switch (ch) {
5576 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005577 redir_fd = redirect_opt_num(&ctx.word);
5578 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005579 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005580 }
5581 redir_style = REDIRECT_OVERWRITE;
5582 if (next == '>') {
5583 redir_style = REDIRECT_APPEND;
5584 ch = i_getch(input);
5585 nommu_addchr(&ctx.as_string, ch);
5586 }
5587#if 0
5588 else if (next == '(') {
5589 syntax_error(">(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005590 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005591 }
5592#endif
5593 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005594 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005595 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005596 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005597 redir_fd = redirect_opt_num(&ctx.word);
5598 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005599 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005600 }
5601 redir_style = REDIRECT_INPUT;
5602 if (next == '<') {
5603 redir_style = REDIRECT_HEREDOC;
5604 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005605 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005606 ch = i_getch(input);
5607 nommu_addchr(&ctx.as_string, ch);
5608 } else if (next == '>') {
5609 redir_style = REDIRECT_IO;
5610 ch = i_getch(input);
5611 nommu_addchr(&ctx.as_string, ch);
5612 }
5613#if 0
5614 else if (next == '(') {
5615 syntax_error("<(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005616 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005617 }
5618#endif
5619 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005620 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005621 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005622 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005623 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005624 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005625 /* note: we do not add it to &ctx.as_string */
5626/* TODO: in bash:
5627 * comment inside $() goes to the next \n, even inside quoted string (!):
5628 * cmd "$(cmd2 #comment)" - syntax error
5629 * cmd "`cmd2 #comment`" - ok
5630 * We accept both (comment ends where command subst ends, in both cases).
5631 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005632 while (1) {
5633 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005634 if (ch == '\n') {
5635 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005636 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005637 }
5638 ch = i_getch(input);
5639 if (ch == EOF)
5640 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005641 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005642 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005643 }
5644 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005645 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005646 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005647
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005648 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005649 /* check that we are not in word in "a=1 2>word b=1": */
5650 && !ctx.pending_redirect
5651 ) {
5652 /* ch is a special char and thus this word
5653 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005654 ctx.is_assignment = NOT_ASSIGNMENT;
5655 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005656 }
5657
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005658 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5659
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005660 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005661 case SPECIAL_VAR_SYMBOL:
5662 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005663 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5664 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005665 /* fall through */
5666 case '#':
5667 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005668 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005669 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005670 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005671 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005672 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005673 "parse_dollar returned 0 (error)\n");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005674 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005675 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005676 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005677 case '"':
5678 ctx.word.has_quoted_part = 1;
5679 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005680 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005681 insert_empty_quoted_str_marker:
5682 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005683 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5684 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005685 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005686 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005687 if (ctx.is_assignment == NOT_ASSIGNMENT)
5688 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005689 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005690 goto parse_error_exitcode1;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005691 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005692 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005693#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005694 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005695 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005696
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005697 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5698 o_addchr(&ctx.word, '`');
5699 USE_FOR_NOMMU(pos = ctx.word.length;)
5700 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005701 goto parse_error_exitcode1;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005702# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005703 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005704 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005705# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005706 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5707 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005708 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005709 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005710#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005711 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005712#if ENABLE_HUSH_CASE
5713 case_semi:
5714#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005715 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005716 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005717 }
5718 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005719#if ENABLE_HUSH_CASE
5720 /* Eat multiple semicolons, detect
5721 * whether it means something special */
5722 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005723 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005724 if (ch != ';')
5725 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005726 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005727 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005728 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005729 ctx.ctx_dsemicolon = 1;
5730 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005731 break;
5732 }
5733 }
5734#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005735 new_cmd:
5736 /* We just finished a cmd. New one may start
5737 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005738 ctx.is_assignment = MAYBE_ASSIGNMENT;
5739 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005740 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005741 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005742 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005743 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005744 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005745 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005746 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005747 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005748 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005749 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005750 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005751 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005752 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005753 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005754 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005755 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005756 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005757#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005758 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005759 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005760#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005761 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005762 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005763 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005764 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005765 } else {
5766 /* we could pick up a file descriptor choice here
5767 * with redirect_opt_num(), but bash doesn't do it.
5768 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005769 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005770 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005771 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005772 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005773#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005774 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005775 if (ctx.ctx_res_w == RES_MATCH
5776 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005777 && ctx.word.length == 0 /* not word(... */
5778 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005779 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005780 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005781 }
5782#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005783 /* fall through */
5784 case '{': {
5785 int n = parse_group(&ctx, input, ch);
5786 if (n < 0) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005787 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005788 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005789 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5790 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005791 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005792 }
Eric Andersen25f27032001-04-26 23:22:31 +00005793 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005794#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005795 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005796 goto case_semi;
5797#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005798
Eric Andersen25f27032001-04-26 23:22:31 +00005799 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005800 /* proper use of this character is caught by end_trigger:
5801 * if we see {, we call parse_group(..., end_trigger='}')
5802 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005803 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005804 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005805 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005806 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005807 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005808 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005809 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005810 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005811
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005812 parse_error_exitcode1:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005813 G.last_exitcode = 1;
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005814 parse_error:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005815 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005816 struct parse_context *pctx;
5817 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005818
5819 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005820 * Sample for finding leaks on syntax error recovery path.
5821 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005822 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005823 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005824 * while if (true | { true;}); then echo ok; fi; do break; done
5825 * 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 +00005826 */
5827 pctx = &ctx;
5828 do {
5829 /* Update pipe/command counts,
5830 * otherwise freeing may miss some */
5831 done_pipe(pctx, PIPE_SEQ);
5832 debug_printf_clean("freeing list %p from ctx %p\n",
5833 pctx->list_head, pctx);
5834 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005835 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005836 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005837#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005838 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005839#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005840 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005841 if (pctx != &ctx) {
5842 free(pctx);
5843 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005844 IF_HAS_KEYWORDS(pctx = p2;)
5845 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005846
Denys Vlasenko474cb202018-07-24 13:03:03 +02005847 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005848#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005849 if (pstring)
5850 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005851#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005852 debug_leave();
5853 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005854 }
Eric Andersen25f27032001-04-26 23:22:31 +00005855}
5856
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005857
5858/*** Execution routines ***/
5859
5860/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005861#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005862#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005863 expand_string_to_string(str)
5864#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005865static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005866#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005867static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005868#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005869static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005870
5871/* expand_strvec_to_strvec() takes a list of strings, expands
5872 * all variable references within and returns a pointer to
5873 * a list of expanded strings, possibly with larger number
5874 * of strings. (Think VAR="a b"; echo $VAR).
5875 * This new list is allocated as a single malloc block.
5876 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005877 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005878 * Caller can deallocate entire list by single free(list). */
5879
Denys Vlasenko238081f2010-10-03 14:26:26 +02005880/* A horde of its helpers come first: */
5881
5882static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5883{
5884 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005885 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005886
Denys Vlasenko9e800222010-10-03 14:28:04 +02005887#if ENABLE_HUSH_BRACE_EXPANSION
5888 if (c == '{' || c == '}') {
5889 /* { -> \{, } -> \} */
5890 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005891 /* And now we want to add { or } and continue:
5892 * o_addchr(o, c);
5893 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005894 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005895 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005896 }
5897#endif
5898 o_addchr(o, c);
5899 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005900 /* \z -> \\\z; \<eol> -> \\<eol> */
5901 o_addchr(o, '\\');
5902 if (len) {
5903 len--;
5904 o_addchr(o, '\\');
5905 o_addchr(o, *str++);
5906 }
5907 }
5908 }
5909}
5910
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005911/* Store given string, finalizing the word and starting new one whenever
5912 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005913 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005914 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005915 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5916 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005917static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005918{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005919 int last_is_ifs = 0;
5920
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005921 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005922 int word_len;
5923
5924 if (!*str) /* EOL - do not finalize word */
5925 break;
5926 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005927 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005928 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005929 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005930 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005931 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005932 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005933 * Example: "v='\*'; echo b$v" prints "b\*"
5934 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005935 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005936 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005937 /*/ Why can't we do it easier? */
5938 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5939 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5940 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005941 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005942 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005943 if (!*str) /* EOL - do not finalize word */
5944 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005945 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005946
5947 /* We know str here points to at least one IFS char */
5948 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005949 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005950 if (!*str) /* EOL - do not finalize word */
5951 break;
5952
Denys Vlasenko96786362018-04-11 16:02:58 +02005953 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5954 && strchr(G.ifs, *str) /* the second check would fail */
5955 ) {
5956 /* This is a non-whitespace $IFS char */
5957 /* Skip it and IFS whitespace chars, start new word */
5958 str++;
5959 str += strspn(str, G.ifs_whitespace);
5960 goto new_word;
5961 }
5962
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005963 /* Start new word... but not always! */
5964 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005965 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005966 /*
5967 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005968 * here nothing precedes the space in $v expansion,
5969 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005970 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005971 * It's okay if this accesses the byte before first argv[]:
5972 * past call to o_save_ptr() cleared it to zero byte
5973 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005974 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005975 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005976 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005977 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005978 o_addchr(output, '\0');
5979 debug_print_list("expand_on_ifs", output, n);
5980 n = o_save_ptr(output, n);
5981 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005982 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005983
Denys Vlasenko168579a2018-07-19 13:45:54 +02005984 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005985 debug_print_list("expand_on_ifs[1]", output, n);
5986 return n;
5987}
5988
5989/* Helper to expand $((...)) and heredoc body. These act as if
5990 * they are in double quotes, with the exception that they are not :).
5991 * Just the rules are similar: "expand only $var and `cmd`"
5992 *
5993 * Returns malloced string.
5994 * As an optimization, we return NULL if expansion is not needed.
5995 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005996static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005997{
5998 char *exp_str;
5999 struct in_str input;
6000 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006001 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006002
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006003 cp = str;
6004 for (;;) {
6005 if (!*cp) return NULL; /* string has no special chars */
6006 if (*cp == '$') break;
6007 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006008#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006009 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006010#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006011 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006012 }
6013
6014 /* We need to expand. Example:
6015 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
6016 */
6017 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006018 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01006019//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006020 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02006021 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02006022 EXP_FLAG_ESC_GLOB_CHARS,
6023 /*unbackslash:*/ 1
6024 );
6025 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006026 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006027 return exp_str;
6028}
6029
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006030static const char *first_special_char_in_vararg(const char *cp)
6031{
6032 for (;;) {
6033 if (!*cp) return NULL; /* string has no special chars */
6034 if (*cp == '$') return cp;
6035 if (*cp == '\\') return cp;
6036 if (*cp == '\'') return cp;
6037 if (*cp == '"') return cp;
6038#if ENABLE_HUSH_TICK
6039 if (*cp == '`') return cp;
6040#endif
6041 /* dquoted "${x:+ARG}" should not glob, therefore
6042 * '*' et al require some non-literal processing: */
6043 if (*cp == '*') return cp;
6044 if (*cp == '?') return cp;
6045 if (*cp == '[') return cp;
6046 cp++;
6047 }
6048}
6049
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006050/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
6051 * These can contain single- and double-quoted strings,
6052 * and treated as if the ARG string is initially unquoted. IOW:
6053 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
6054 * a dquoted string: "${var#"zz"}"), the difference only comes later
6055 * (word splitting and globbing of the ${var...} result).
6056 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006057#if !BASH_PATTERN_SUBST
6058#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
6059 encode_then_expand_vararg(str, handle_squotes)
6060#endif
6061static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6062{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006063#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006064 const int do_unbackslash = 0;
6065#endif
6066 char *exp_str;
6067 struct in_str input;
6068 o_string dest = NULL_O_STRING;
6069
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006070 if (!first_special_char_in_vararg(str)) {
6071 /* string has no special chars */
6072 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006073 }
6074
Denys Vlasenkob762c782018-07-17 14:21:38 +02006075 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006076 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006077 exp_str = NULL;
6078
6079 for (;;) {
6080 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006081
6082 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006083 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6084 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006085
6086 if (!dest.o_expflags) {
6087 if (ch == EOF)
6088 break;
6089 if (handle_squotes && ch == '\'') {
6090 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006091 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006092 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006093 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006094 }
6095 if (ch == EOF) {
6096 syntax_error_unterm_ch('"');
6097 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006098 }
6099 if (ch == '"') {
6100 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6101 continue;
6102 }
6103 if (ch == '\\') {
6104 ch = i_getch(&input);
6105 if (ch == EOF) {
6106//example? error message? syntax_error_unterm_ch('"');
6107 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6108 goto ret;
6109 }
6110 o_addqchr(&dest, ch);
6111 continue;
6112 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006113 if (ch == '$') {
6114 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6115 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6116 goto ret;
6117 }
6118 continue;
6119 }
6120#if ENABLE_HUSH_TICK
6121 if (ch == '`') {
6122 //unsigned pos = dest->length;
6123 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6124 o_addchr(&dest, 0x80 | '`');
6125 if (!add_till_backquote(&dest, &input,
6126 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6127 )
6128 ) {
6129 goto ret; /* error */
6130 }
6131 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6132 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6133 continue;
6134 }
6135#endif
6136 o_addQchr(&dest, ch);
6137 } /* for (;;) */
6138
6139 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6140 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006141 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6142 do_unbackslash
6143 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006144 ret:
6145 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006146 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006147 return exp_str;
6148}
6149
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006150/* Expanding ARG in ${var+ARG}, ${var-ARG}
6151 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006152static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006153 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006154{
6155 struct in_str input;
6156 o_string dest = NULL_O_STRING;
6157
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006158 if (!first_special_char_in_vararg(str)
6159 && '\0' == str[strcspn(str, G.ifs)]
6160 ) {
6161 /* string has no special chars
6162 * && string has no $IFS chars
6163 */
Denys Vlasenko9e0adb92019-05-15 13:39:19 +02006164 if (dquoted) {
6165 /* Prints 1 (quoted expansion is a "" word, not nothing):
6166 * set -- "${notexist-}"; echo $#
6167 */
6168 output->has_quoted_part = 1;
6169 }
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006170 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006171 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006172
Denys Vlasenko294eb462018-07-20 16:18:59 +02006173 setup_string_in_str(&input, str);
6174
6175 for (;;) {
6176 int ch;
6177
6178 ch = i_getch(&input);
6179 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6180 __func__, ch, ch, dest.o_expflags);
6181
6182 if (!dest.o_expflags) {
6183 if (ch == EOF)
6184 break;
6185 if (!dquoted && strchr(G.ifs, ch)) {
6186 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6187 * do not assume we are at the start of the word (PREFIX above).
6188 */
6189 if (dest.data) {
6190 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006191 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006192 o_addchr(output, '\0');
6193 n = o_save_ptr(output, n); /* create next word */
6194 } else
6195 if (output->length != o_get_last_ptr(output, n)
6196 || output->has_quoted_part
6197 ) {
6198 /* For these cases:
6199 * f() { for i; do echo "|$i|"; done; }; x=x
6200 * f a${x:+ }b # 1st condition
6201 * |a|
6202 * |b|
6203 * f ""${x:+ }b # 2nd condition
6204 * ||
6205 * |b|
6206 */
6207 o_addchr(output, '\0');
6208 n = o_save_ptr(output, n); /* create next word */
6209 }
6210 continue;
6211 }
6212 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006213 if (!add_till_single_quote_dquoted(&dest, &input))
6214 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006215 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6216 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006217 continue;
6218 }
6219 }
6220 if (ch == EOF) {
6221 syntax_error_unterm_ch('"');
6222 goto ret; /* error */
6223 }
6224 if (ch == '"') {
6225 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006226 if (dest.o_expflags) {
6227 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6228 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6229 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006230 continue;
6231 }
6232 if (ch == '\\') {
6233 ch = i_getch(&input);
6234 if (ch == EOF) {
6235//example? error message? syntax_error_unterm_ch('"');
6236 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6237 goto ret;
6238 }
6239 o_addqchr(&dest, ch);
6240 continue;
6241 }
6242 if (ch == '$') {
6243 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6244 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6245 goto ret;
6246 }
6247 continue;
6248 }
6249#if ENABLE_HUSH_TICK
6250 if (ch == '`') {
6251 //unsigned pos = dest->length;
6252 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6253 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6254 if (!add_till_backquote(&dest, &input,
6255 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6256 )
6257 ) {
6258 goto ret; /* error */
6259 }
6260 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6261 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6262 continue;
6263 }
6264#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006265 if (dquoted) {
6266 /* Always glob-protect if in dquotes:
6267 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6268 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6269 */
6270 o_addqchr(&dest, ch);
6271 } else {
6272 /* Glob-protect only if char is quoted:
6273 * x=x; echo ${x:+/bin/c*} - prints many filenames
6274 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6275 */
6276 o_addQchr(&dest, ch);
6277 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006278 } /* for (;;) */
6279
6280 if (dest.data) {
6281 n = expand_vars_to_list(output, n, dest.data);
6282 }
6283 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006284 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006285 return n;
6286}
6287
Denys Vlasenko0b883582016-12-23 16:49:07 +01006288#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006289static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006290{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006291 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006292 arith_t res;
6293 char *exp_str;
6294
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006295 math_state.lookupvar = get_local_var_value;
6296 math_state.setvar = set_local_var_from_halves;
6297 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006298 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006299 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006300 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006301 if (errmsg_p)
6302 *errmsg_p = math_state.errmsg;
6303 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006304 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006305 return res;
6306}
6307#endif
6308
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006309#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006310/* ${var/[/]pattern[/repl]} helpers */
6311static char *strstr_pattern(char *val, const char *pattern, int *size)
6312{
6313 while (1) {
6314 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6315 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6316 if (end) {
6317 *size = end - val;
6318 return val;
6319 }
6320 if (*val == '\0')
6321 return NULL;
6322 /* Optimization: if "*pat" did not match the start of "string",
6323 * we know that "tring", "ring" etc will not match too:
6324 */
6325 if (pattern[0] == '*')
6326 return NULL;
6327 val++;
6328 }
6329}
6330static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6331{
6332 char *result = NULL;
6333 unsigned res_len = 0;
6334 unsigned repl_len = strlen(repl);
6335
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006336 /* Null pattern never matches, including if "var" is empty */
6337 if (!pattern[0])
6338 return result; /* NULL, no replaces happened */
6339
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006340 while (1) {
6341 int size;
6342 char *s = strstr_pattern(val, pattern, &size);
6343 if (!s)
6344 break;
6345
6346 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006347 strcpy(mempcpy(result + res_len, val, s - val), repl);
6348 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006349 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6350
6351 val = s + size;
6352 if (exp_op == '/')
6353 break;
6354 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006355 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006356 result = xrealloc(result, res_len + strlen(val) + 1);
6357 strcpy(result + res_len, val);
6358 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6359 }
6360 debug_printf_varexp("result:'%s'\n", result);
6361 return result;
6362}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006363#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006364
Denys Vlasenko168579a2018-07-19 13:45:54 +02006365static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006366 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006367{
6368 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6369 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6370 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6371 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006372 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006373 } else { /* quoted "$VAR" */
6374 output->has_quoted_part = 1;
6375 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6376 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6377 if (val && val[0])
6378 o_addQstr(output, val);
6379 }
6380 return n;
6381}
6382
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006383/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006384 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006385static NOINLINE int expand_one_var(o_string *output, int n,
6386 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006387{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006388 const char *val;
6389 char *to_be_freed;
6390 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006391 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006392 char exp_op;
6393 char exp_save = exp_save; /* for compiler */
6394 char *exp_saveptr; /* points to expansion operator */
6395 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006396 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006397
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006398 val = NULL;
6399 to_be_freed = NULL;
6400 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006401 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006402 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006403 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006404 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006405 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006406 exp_op = 0;
6407
Denys Vlasenkob762c782018-07-17 14:21:38 +02006408 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006409 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6410 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6411 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006412 ) {
6413 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006414 var++;
6415 exp_op = 'L';
6416 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006417 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006418 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006419 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006420 ) {
6421 /* ${?:0}, ${#[:]%0} etc */
6422 exp_saveptr = var + 1;
6423 } else {
6424 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6425 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6426 }
6427 exp_op = exp_save = *exp_saveptr;
6428 if (exp_op) {
6429 exp_word = exp_saveptr + 1;
6430 if (exp_op == ':') {
6431 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006432//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006433 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006434 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006435 ) {
6436 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6437 exp_op = ':';
6438 exp_word--;
6439 }
6440 }
6441 *exp_saveptr = '\0';
6442 } /* else: it's not an expansion op, but bare ${var} */
6443 }
6444
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006445 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006446 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006447 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006448 int nn = xatoi_positive(var);
6449 if (nn < G.global_argc)
6450 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006451 /* else val remains NULL: $N with too big N */
6452 } else {
6453 switch (var[0]) {
6454 case '$': /* pid */
6455 val = utoa(G.root_pid);
6456 break;
6457 case '!': /* bg pid */
6458 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6459 break;
6460 case '?': /* exitcode */
6461 val = utoa(G.last_exitcode);
6462 break;
6463 case '#': /* argc */
6464 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6465 break;
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006466 case '-': { /* active options */
6467 /* Check set_mode() to see what option chars we support */
6468 char *cp;
6469 val = cp = G.optstring_buf;
6470 if (G.o_opt[OPT_O_ERREXIT])
6471 *cp++ = 'e';
6472 if (G_interactive_fd)
6473 *cp++ = 'i';
6474 if (G_x_mode)
6475 *cp++ = 'x';
6476 /* If G.o_opt[OPT_O_NOEXEC] is true,
6477 * commands read but are not executed,
6478 * so $- can not execute too, 'n' is never seen in $-.
6479 */
Denys Vlasenkof3634582019-06-03 12:21:04 +02006480 if (G.opt_c)
6481 *cp++ = 'c';
Denys Vlasenkod8740b22019-05-19 19:11:21 +02006482 if (G.opt_s)
6483 *cp++ = 's';
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006484 *cp = '\0';
6485 break;
6486 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006487 default:
6488 val = get_local_var_value(var);
6489 }
6490 }
6491
6492 /* Handle any expansions */
6493 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006494 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006495 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006496 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006497 debug_printf_expand("%s\n", val);
6498 } else if (exp_op) {
6499 if (exp_op == '%' || exp_op == '#') {
6500 /* Standard-mandated substring removal ops:
6501 * ${parameter%word} - remove smallest suffix pattern
6502 * ${parameter%%word} - remove largest suffix pattern
6503 * ${parameter#word} - remove smallest prefix pattern
6504 * ${parameter##word} - remove largest prefix pattern
6505 *
6506 * Word is expanded to produce a glob pattern.
6507 * Then var's value is matched to it and matching part removed.
6508 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006509//FIXME: ${x#...${...}...}
6510//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6511//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006512 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006513 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006514 char *exp_exp_word;
6515 char *loc;
6516 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006517 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006518 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006519 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006520 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006521 if (exp_exp_word)
6522 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006523 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6524 /*
6525 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006526 * G.global_argv and results of utoa and get_local_var_value
6527 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006528 * scan_and_match momentarily stores NULs there.
6529 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006530 t = (char*)val;
6531 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006532 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 +02006533 free(exp_exp_word);
6534 if (loc) { /* match was found */
6535 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006536 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006537 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006538 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006539 }
6540 }
6541 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006542#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006543 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006544 /* It's ${var/[/]pattern[/repl]} thing.
6545 * Note that in encoded form it has TWO parts:
6546 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006547 * and if // is used, it is encoded as \:
6548 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006549 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006550 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006551 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006552 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006553 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006554 * >az >bz
6555 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6556 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6557 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6558 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006559 * (note that a*z _pattern_ is never globbed!)
6560 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006561 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006562 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006563 if (!pattern)
6564 pattern = xstrdup(exp_word);
6565 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6566 *p++ = SPECIAL_VAR_SYMBOL;
6567 exp_word = p;
6568 p = strchr(p, SPECIAL_VAR_SYMBOL);
6569 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006570 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006571 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6572 /* HACK ALERT. We depend here on the fact that
6573 * G.global_argv and results of utoa and get_local_var_value
6574 * are actually in writable memory:
6575 * replace_pattern momentarily stores NULs there. */
6576 t = (char*)val;
6577 to_be_freed = replace_pattern(t,
6578 pattern,
6579 (repl ? repl : exp_word),
6580 exp_op);
6581 if (to_be_freed) /* at least one replace happened */
6582 val = to_be_freed;
6583 free(pattern);
6584 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006585 } else {
6586 /* Empty variable always gives nothing */
6587 // "v=''; echo ${v/*/w}" prints "", not "w"
6588 /* Just skip "replace" part */
6589 *p++ = SPECIAL_VAR_SYMBOL;
6590 p = strchr(p, SPECIAL_VAR_SYMBOL);
6591 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006592 }
6593 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006594#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006595 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006596#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006597 /* It's ${var:N[:M]} bashism.
6598 * Note that in encoded form it has TWO parts:
6599 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6600 */
6601 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006602 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006603
Denys Vlasenko063847d2010-09-15 13:33:02 +02006604 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6605 if (errmsg)
6606 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006607 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6608 *p++ = SPECIAL_VAR_SYMBOL;
6609 exp_word = p;
6610 p = strchr(p, SPECIAL_VAR_SYMBOL);
6611 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006612 len = expand_and_evaluate_arith(exp_word, &errmsg);
6613 if (errmsg)
6614 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006615 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006616 if (beg < 0) {
6617 /* negative beg counts from the end */
6618 beg = (arith_t)strlen(val) + beg;
6619 if (beg < 0) /* ${v: -999999} is "" */
6620 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006621 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006622 debug_printf_varexp("from val:'%s'\n", val);
6623 if (len < 0) {
6624 /* in bash, len=-n means strlen()-n */
6625 len = (arith_t)strlen(val) - beg + len;
6626 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006627 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006628 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006629 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006630 arith_err:
6631 val = NULL;
6632 } else {
6633 /* Paranoia. What if user entered 9999999999999
6634 * which fits in arith_t but not int? */
6635 if (len >= INT_MAX)
6636 len = INT_MAX;
6637 val = to_be_freed = xstrndup(val + beg, len);
6638 }
6639 debug_printf_varexp("val:'%s'\n", val);
6640#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006641 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006642 val = NULL;
6643#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006644 } else { /* one of "-=+?" */
6645 /* Standard-mandated substitution ops:
6646 * ${var?word} - indicate error if unset
6647 * If var is unset, word (or a message indicating it is unset
6648 * if word is null) is written to standard error
6649 * and the shell exits with a non-zero exit status.
6650 * Otherwise, the value of var is substituted.
6651 * ${var-word} - use default value
6652 * If var is unset, word is substituted.
6653 * ${var=word} - assign and use default value
6654 * If var is unset, word is assigned to var.
6655 * In all cases, final value of var is substituted.
6656 * ${var+word} - use alternative value
6657 * If var is unset, null is substituted.
6658 * Otherwise, word is substituted.
6659 *
6660 * Word is subjected to tilde expansion, parameter expansion,
6661 * command substitution, and arithmetic expansion.
6662 * If word is not needed, it is not expanded.
6663 *
6664 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6665 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006666 *
6667 * Word-splitting and single quote behavior:
6668 *
6669 * $ f() { for i; do echo "|$i|"; done; };
6670 *
6671 * $ x=; f ${x:?'x y' z}
6672 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
6673 * $ x=; f "${x:?'x y' z}"
6674 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
6675 *
6676 * $ x=; f ${x:='x y' z}
6677 * |x|
6678 * |y|
6679 * |z|
6680 * $ x=; f "${x:='x y' z}"
6681 * |'x y' z|
6682 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006683 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006684 * |x y|
6685 * |z|
6686 * $ x=x; f "${x:+'x y' z}"
6687 * |'x y' z|
6688 *
6689 * $ x=; f ${x:-'x y' z}
6690 * |x y|
6691 * |z|
6692 * $ x=; f "${x:-'x y' z}"
6693 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006694 */
6695 int use_word = (!val || ((exp_save == ':') && !val[0]));
6696 if (exp_op == '+')
6697 use_word = !use_word;
6698 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6699 (exp_save == ':') ? "true" : "false", use_word);
6700 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006701 if (exp_op == '+' || exp_op == '-') {
6702 /* ${var+word} - use alternative value */
6703 /* ${var-word} - use default value */
6704 n = encode_then_append_var_plusminus(output, n, exp_word,
6705 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006706 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006707 val = NULL;
6708 } else {
6709 /* ${var?word} - indicate error if unset */
6710 /* ${var=word} - assign and use default value */
6711 to_be_freed = encode_then_expand_vararg(exp_word,
6712 /*handle_squotes:*/ !(arg0 & 0x80),
6713 /*unbackslash:*/ 0
6714 );
6715 if (to_be_freed)
6716 exp_word = to_be_freed;
6717 if (exp_op == '?') {
6718 /* mimic bash message */
6719 msg_and_die_if_script("%s: %s",
6720 var,
6721 exp_word[0]
6722 ? exp_word
6723 : "parameter null or not set"
6724 /* ash has more specific messages, a-la: */
6725 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6726 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006727//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006728//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006729// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6730// bash: x: x y z
6731// $
6732// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006733 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006734 val = exp_word;
6735 }
6736 if (exp_op == '=') {
6737 /* ${var=[word]} or ${var:=[word]} */
6738 if (isdigit(var[0]) || var[0] == '#') {
6739 /* mimic bash message */
6740 msg_and_die_if_script("$%s: cannot assign in this way", var);
6741 val = NULL;
6742 } else {
6743 char *new_var = xasprintf("%s=%s", var, val);
6744 set_local_var(new_var, /*flag:*/ 0);
6745 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006746 }
6747 }
6748 }
6749 } /* one of "-=+?" */
6750
6751 *exp_saveptr = exp_save;
6752 } /* if (exp_op) */
6753
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006754 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006755 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006756
Denys Vlasenko168579a2018-07-19 13:45:54 +02006757 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006758
6759 free(to_be_freed);
6760 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006761}
6762
6763/* Expand all variable references in given string, adding words to list[]
6764 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6765 * to be filled). This routine is extremely tricky: has to deal with
6766 * variables/parameters with whitespace, $* and $@, and constructs like
6767 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006768static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006769{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006770 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006771 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006772 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006773 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006774 char *p;
6775
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006776 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6777 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006778 debug_print_list("expand_vars_to_list[0]", output, n);
6779
6780 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6781 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006782#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006783 char arith_buf[sizeof(arith_t)*3 + 2];
6784#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006785
Denys Vlasenko168579a2018-07-19 13:45:54 +02006786 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006787 o_addchr(output, '\0');
6788 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006789 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006790 }
6791
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006792 o_addblock(output, arg, p - arg);
6793 debug_print_list("expand_vars_to_list[1]", output, n);
6794 arg = ++p;
6795 p = strchr(p, SPECIAL_VAR_SYMBOL);
6796
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006797 /* Fetch special var name (if it is indeed one of them)
6798 * and quote bit, force the bit on if singleword expansion -
6799 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006800 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006801
6802 /* Is this variable quoted and thus expansion can't be null?
6803 * "$@" is special. Even if quoted, it can still
6804 * expand to nothing (not even an empty string),
6805 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006806 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006807 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006808
6809 switch (first_ch & 0x7f) {
6810 /* Highest bit in first_ch indicates that var is double-quoted */
6811 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006812 case '@': {
6813 int i;
6814 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006815 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006816 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006817 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006818 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006819 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006820 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006821 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6822 if (G.global_argv[i++][0] && G.global_argv[i]) {
6823 /* this argv[] is not empty and not last:
6824 * put terminating NUL, start new word */
6825 o_addchr(output, '\0');
6826 debug_print_list("expand_vars_to_list[2]", output, n);
6827 n = o_save_ptr(output, n);
6828 debug_print_list("expand_vars_to_list[3]", output, n);
6829 }
6830 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006831 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006832 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006833 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006834 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006835 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006836 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006837 while (1) {
6838 o_addQstr(output, G.global_argv[i]);
6839 if (++i >= G.global_argc)
6840 break;
6841 o_addchr(output, '\0');
6842 debug_print_list("expand_vars_to_list[4]", output, n);
6843 n = o_save_ptr(output, n);
6844 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006845 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006846 while (1) {
6847 o_addQstr(output, G.global_argv[i]);
6848 if (!G.global_argv[++i])
6849 break;
6850 if (G.ifs[0])
6851 o_addchr(output, G.ifs[0]);
6852 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006853 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006854 }
6855 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006856 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006857 case SPECIAL_VAR_SYMBOL: {
6858 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006859 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006860 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006861 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006862 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006863 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006864 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006865 case SPECIAL_VAR_QUOTED_SVS:
6866 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006867 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006868 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006869 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006870 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006871#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006872 case '`': {
6873 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006874 o_string subst_result = NULL_O_STRING;
6875
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006876 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006877 arg++;
6878 /* Can't just stuff it into output o_string,
6879 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006880 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006881 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6882 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006883 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006884 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006885 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006886 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006887 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006888 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006889#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006890#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006891 case '+': {
6892 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006893 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006894
6895 arg++; /* skip '+' */
6896 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6897 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006898 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006899 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6900 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01006901 if (res < 0
6902 && first_ch == (char)('+'|0x80)
6903 /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
6904 ) {
6905 /* Quoted negative ariths, like filename[0"$((-9))"],
6906 * should not be interpreted as glob ranges.
6907 * Convert leading '-' to '\-':
6908 */
6909 o_grow_by(output, 1);
6910 output->data[output->length++] = '\\';
6911 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006912 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006913 break;
6914 }
6915#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006916 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006917 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006918 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006919 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006920 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6921
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006922 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6923 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006924 if (*p != SPECIAL_VAR_SYMBOL)
6925 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006926 arg = ++p;
6927 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6928
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006929 if (*arg) {
6930 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006931 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006932 o_addchr(output, '\0');
6933 n = o_save_ptr(output, n);
6934 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006935 debug_print_list("expand_vars_to_list[a]", output, n);
6936 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006937 * if needed (much earlier), do not use o_addQstr here!
6938 */
6939 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006940 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006941 } else
6942 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006943 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6944 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006945 ) {
6946 n--;
6947 /* allow to reuse list[n] later without re-growth */
6948 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006949 }
6950
6951 return n;
6952}
6953
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006954static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006955{
6956 int n;
6957 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006958 o_string output = NULL_O_STRING;
6959
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006960 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006961
6962 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006963 for (;;) {
6964 /* go to next list[n] */
6965 output.ended_in_ifs = 0;
6966 n = o_save_ptr(&output, n);
6967
6968 if (!*argv)
6969 break;
6970
6971 /* expand argv[i] */
6972 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006973 /* if (!output->has_empty_slot) -- need this?? */
6974 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006975 }
6976 debug_print_list("expand_variables", &output, n);
6977
6978 /* output.data (malloced in one block) gets returned in "list" */
6979 list = o_finalize_list(&output, n);
6980 debug_print_strings("expand_variables[1]", list);
6981 return list;
6982}
6983
6984static char **expand_strvec_to_strvec(char **argv)
6985{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006986 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006987}
6988
Denys Vlasenkod2241f52020-10-31 03:34:07 +01006989#if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006990static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6991{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006992 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006993}
6994#endif
6995
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006996/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006997 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006998 *
6999 * NB: should NOT do globbing!
7000 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
7001 */
Denys Vlasenko34179952018-04-11 13:47:59 +02007002static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007003{
Denys Vlasenko637982f2017-07-06 01:52:23 +02007004#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007005 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02007006 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007007#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007008 char *argv[2], **list;
7009
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007010 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007011 /* This is generally an optimization, but it also
7012 * handles "", which otherwise trips over !list[0] check below.
7013 * (is this ever happens that we actually get str="" here?)
7014 */
7015 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
7016 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007017 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007018 return xstrdup(str);
7019 }
7020
7021 argv[0] = (char*)str;
7022 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02007023 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02007024 if (!list[0]) {
7025 /* Example where it happens:
7026 * x=; echo ${x:-"$@"}
7027 */
7028 ((char*)list)[0] = '\0';
7029 } else {
7030 if (HUSH_DEBUG)
7031 if (list[1])
James Byrne69374872019-07-02 11:35:03 +02007032 bb_simple_error_msg_and_die("BUG in varexp2");
Denys Vlasenko2e711012018-07-18 16:02:25 +02007033 /* actually, just move string 2*sizeof(char*) bytes back */
7034 overlapping_strcpy((char*)list, list[0]);
7035 if (do_unbackslash)
7036 unbackslash((char*)list);
7037 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007038 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007039 return (char*)list;
7040}
7041
Denys Vlasenkoabf75562018-04-02 17:25:18 +02007042#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007043static char* expand_strvec_to_string(char **argv)
7044{
7045 char **list;
7046
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007047 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007048 /* Convert all NULs to spaces */
7049 if (list[0]) {
7050 int n = 1;
7051 while (list[n]) {
7052 if (HUSH_DEBUG)
7053 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
7054 bb_error_msg_and_die("BUG in varexp3");
7055 /* bash uses ' ' regardless of $IFS contents */
7056 list[n][-1] = ' ';
7057 n++;
7058 }
7059 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02007060 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007061 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
7062 return (char*)list;
7063}
Denys Vlasenko1f191122018-01-11 13:17:30 +01007064#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007065
7066static char **expand_assignments(char **argv, int count)
7067{
7068 int i;
7069 char **p;
7070
7071 G.expanded_assignments = p = NULL;
7072 /* Expand assignments into one string each */
7073 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02007074 p = add_string_to_strings(p,
7075 expand_string_to_string(argv[i],
7076 EXP_FLAG_ESC_GLOB_CHARS,
7077 /*unbackslash:*/ 1
7078 )
7079 );
7080 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007081 }
7082 G.expanded_assignments = NULL;
7083 return p;
7084}
7085
7086
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007087static void switch_off_special_sigs(unsigned mask)
7088{
7089 unsigned sig = 0;
7090 while ((mask >>= 1) != 0) {
7091 sig++;
7092 if (!(mask & 1))
7093 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007094#if ENABLE_HUSH_TRAP
7095 if (G_traps) {
7096 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007097 /* trap is '', has to remain SIG_IGN */
7098 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007099 free(G_traps[sig]);
7100 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007101 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007102#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007103 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007104 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007105 }
7106}
7107
Denys Vlasenkob347df92011-08-09 22:49:15 +02007108#if BB_MMU
7109/* never called */
7110void re_execute_shell(char ***to_free, const char *s,
7111 char *g_argv0, char **g_argv,
7112 char **builtin_argv) NORETURN;
7113
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007114static void reset_traps_to_defaults(void)
7115{
7116 /* This function is always called in a child shell
7117 * after fork (not vfork, NOMMU doesn't use this function).
7118 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007119 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007120 unsigned mask;
7121
7122 /* Child shells are not interactive.
7123 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7124 * Testcase: (while :; do :; done) + ^Z should background.
7125 * Same goes for SIGTERM, SIGHUP, SIGINT.
7126 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007127 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007128 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007129 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007130
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007131 /* Switch off special sigs */
7132 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007133# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007134 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007135# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007136 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007137 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7138 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007139
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007140# if ENABLE_HUSH_TRAP
7141 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007142 return;
7143
7144 /* Reset all sigs to default except ones with empty traps */
7145 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007146 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007147 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007148 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007149 continue; /* empty trap: has to remain SIG_IGN */
7150 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007151 free(G_traps[sig]);
7152 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007153 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007154 if (sig == 0)
7155 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007156 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007157 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007158# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007159}
7160
7161#else /* !BB_MMU */
7162
7163static void re_execute_shell(char ***to_free, const char *s,
7164 char *g_argv0, char **g_argv,
7165 char **builtin_argv) NORETURN;
7166static void re_execute_shell(char ***to_free, const char *s,
7167 char *g_argv0, char **g_argv,
7168 char **builtin_argv)
7169{
7170# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7171 /* delims + 2 * (number of bytes in printed hex numbers) */
7172 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7173 char *heredoc_argv[4];
7174 struct variable *cur;
7175# if ENABLE_HUSH_FUNCTIONS
7176 struct function *funcp;
7177# endif
7178 char **argv, **pp;
7179 unsigned cnt;
7180 unsigned long long empty_trap_mask;
7181
7182 if (!g_argv0) { /* heredoc */
7183 argv = heredoc_argv;
7184 argv[0] = (char *) G.argv0_for_re_execing;
7185 argv[1] = (char *) "-<";
7186 argv[2] = (char *) s;
7187 argv[3] = NULL;
7188 pp = &argv[3]; /* used as pointer to empty environment */
7189 goto do_exec;
7190 }
7191
7192 cnt = 0;
7193 pp = builtin_argv;
7194 if (pp) while (*pp++)
7195 cnt++;
7196
7197 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007198 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007199 int sig;
7200 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007201 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007202 empty_trap_mask |= 1LL << sig;
7203 }
7204 }
7205
7206 sprintf(param_buf, NOMMU_HACK_FMT
7207 , (unsigned) G.root_pid
7208 , (unsigned) G.root_ppid
7209 , (unsigned) G.last_bg_pid
7210 , (unsigned) G.last_exitcode
7211 , cnt
7212 , empty_trap_mask
7213 IF_HUSH_LOOPS(, G.depth_of_loop)
7214 );
7215# undef NOMMU_HACK_FMT
7216 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7217 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7218 */
7219 cnt += 6;
7220 for (cur = G.top_var; cur; cur = cur->next) {
7221 if (!cur->flg_export || cur->flg_read_only)
7222 cnt += 2;
7223 }
7224# if ENABLE_HUSH_FUNCTIONS
7225 for (funcp = G.top_func; funcp; funcp = funcp->next)
7226 cnt += 3;
7227# endif
7228 pp = g_argv;
7229 while (*pp++)
7230 cnt++;
7231 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7232 *pp++ = (char *) G.argv0_for_re_execing;
7233 *pp++ = param_buf;
7234 for (cur = G.top_var; cur; cur = cur->next) {
7235 if (strcmp(cur->varstr, hush_version_str) == 0)
7236 continue;
7237 if (cur->flg_read_only) {
7238 *pp++ = (char *) "-R";
7239 *pp++ = cur->varstr;
7240 } else if (!cur->flg_export) {
7241 *pp++ = (char *) "-V";
7242 *pp++ = cur->varstr;
7243 }
7244 }
7245# if ENABLE_HUSH_FUNCTIONS
7246 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7247 *pp++ = (char *) "-F";
7248 *pp++ = funcp->name;
7249 *pp++ = funcp->body_as_string;
7250 }
7251# endif
7252 /* We can pass activated traps here. Say, -Tnn:trap_string
7253 *
7254 * However, POSIX says that subshells reset signals with traps
7255 * to SIG_DFL.
7256 * I tested bash-3.2 and it not only does that with true subshells
7257 * of the form ( list ), but with any forked children shells.
7258 * I set trap "echo W" WINCH; and then tried:
7259 *
7260 * { echo 1; sleep 20; echo 2; } &
7261 * while true; do echo 1; sleep 20; echo 2; break; done &
7262 * true | { echo 1; sleep 20; echo 2; } | cat
7263 *
7264 * In all these cases sending SIGWINCH to the child shell
7265 * did not run the trap. If I add trap "echo V" WINCH;
7266 * _inside_ group (just before echo 1), it works.
7267 *
7268 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007269 */
7270 *pp++ = (char *) "-c";
7271 *pp++ = (char *) s;
7272 if (builtin_argv) {
7273 while (*++builtin_argv)
7274 *pp++ = *builtin_argv;
7275 *pp++ = (char *) "";
7276 }
7277 *pp++ = g_argv0;
7278 while (*g_argv)
7279 *pp++ = *g_argv++;
7280 /* *pp = NULL; - is already there */
7281 pp = environ;
7282
7283 do_exec:
7284 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007285 /* Don't propagate SIG_IGN to the child */
7286 if (SPECIAL_JOBSTOP_SIGS != 0)
7287 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007288 execve(bb_busybox_exec_path, argv, pp);
7289 /* Fallback. Useful for init=/bin/hush usage etc */
7290 if (argv[0][0] == '/')
7291 execve(argv[0], argv, pp);
7292 xfunc_error_retval = 127;
James Byrne69374872019-07-02 11:35:03 +02007293 bb_simple_error_msg_and_die("can't re-execute the shell");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007294}
7295#endif /* !BB_MMU */
7296
7297
7298static int run_and_free_list(struct pipe *pi);
7299
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007300/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007301 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7302 * end_trigger controls how often we stop parsing
7303 * NUL: parse all, execute, return
7304 * ';': parse till ';' or newline, execute, repeat till EOF
7305 */
7306static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007307{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007308 /* Why we need empty flag?
7309 * An obscure corner case "false; ``; echo $?":
7310 * empty command in `` should still set $? to 0.
7311 * But we can't just set $? to 0 at the start,
7312 * this breaks "false; echo `echo $?`" case.
7313 */
7314 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007315 while (1) {
7316 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007317
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007318#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007319 if (end_trigger == ';') {
7320 G.promptmode = 0; /* PS1 */
7321 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7322 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007323#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007324 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007325 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7326 /* If we are in "big" script
7327 * (not in `cmd` or something similar)...
7328 */
7329 if (pipe_list == ERR_PTR && end_trigger == ';') {
7330 /* Discard cached input (rest of line) */
7331 int ch = inp->last_char;
7332 while (ch != EOF && ch != '\n') {
7333 //bb_error_msg("Discarded:'%c'", ch);
7334 ch = i_getch(inp);
7335 }
7336 /* Force prompt */
7337 inp->p = NULL;
7338 /* This stream isn't empty */
7339 empty = 0;
7340 continue;
7341 }
7342 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007343 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007344 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007345 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007346 debug_print_tree(pipe_list, 0);
7347 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7348 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007349 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007350 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007351 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007352 }
Eric Andersen25f27032001-04-26 23:22:31 +00007353}
7354
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007355static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007356{
7357 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007358 //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007359
Eric Andersen25f27032001-04-26 23:22:31 +00007360 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007361 parse_and_run_stream(&input, '\0');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007362 //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007363}
7364
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007365static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007366{
Eric Andersen25f27032001-04-26 23:22:31 +00007367 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007368 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007369
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007370 IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007371 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007372 parse_and_run_stream(&input, ';');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007373 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007374}
7375
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007376#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007377static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007378{
7379 pid_t pid;
7380 int channel[2];
7381# if !BB_MMU
7382 char **to_free = NULL;
7383# endif
7384
7385 xpipe(channel);
7386 pid = BB_MMU ? xfork() : xvfork();
7387 if (pid == 0) { /* child */
7388 disable_restore_tty_pgrp_on_exit();
7389 /* Process substitution is not considered to be usual
7390 * 'command execution'.
7391 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7392 */
7393 bb_signals(0
7394 + (1 << SIGTSTP)
7395 + (1 << SIGTTIN)
7396 + (1 << SIGTTOU)
7397 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007398 close(channel[0]); /* NB: close _first_, then move fd! */
7399 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007400# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007401 /* Awful hack for `trap` or $(trap).
7402 *
7403 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7404 * contains an example where "trap" is executed in a subshell:
7405 *
7406 * save_traps=$(trap)
7407 * ...
7408 * eval "$save_traps"
7409 *
7410 * Standard does not say that "trap" in subshell shall print
7411 * parent shell's traps. It only says that its output
7412 * must have suitable form, but then, in the above example
7413 * (which is not supposed to be normative), it implies that.
7414 *
7415 * bash (and probably other shell) does implement it
7416 * (traps are reset to defaults, but "trap" still shows them),
7417 * but as a result, "trap" logic is hopelessly messed up:
7418 *
7419 * # trap
7420 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7421 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7422 * # true | trap <--- trap is in subshell - no output (ditto)
7423 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7424 * trap -- 'echo Ho' SIGWINCH
7425 * # echo `(trap)` <--- in subshell in subshell - output
7426 * trap -- 'echo Ho' SIGWINCH
7427 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7428 * trap -- 'echo Ho' SIGWINCH
7429 *
7430 * The rules when to forget and when to not forget traps
7431 * get really complex and nonsensical.
7432 *
7433 * Our solution: ONLY bare $(trap) or `trap` is special.
7434 */
7435 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007436 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007437 && skip_whitespace(s + 4)[0] == '\0'
7438 ) {
7439 static const char *const argv[] = { NULL, NULL };
7440 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007441 fflush_all(); /* important */
7442 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007443 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007444# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007445# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007446 /* Prevent it from trying to handle ctrl-z etc */
7447 IF_HUSH_JOB(G.run_list_level = 1;)
7448 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007449 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007450 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007451 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007452 parse_and_run_string(s);
7453 _exit(G.last_exitcode);
7454# else
7455 /* We re-execute after vfork on NOMMU. This makes this script safe:
7456 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7457 * huge=`cat BIG` # was blocking here forever
7458 * echo OK
7459 */
7460 re_execute_shell(&to_free,
7461 s,
7462 G.global_argv[0],
7463 G.global_argv + 1,
7464 NULL);
7465# endif
7466 }
7467
7468 /* parent */
7469 *pid_p = pid;
7470# if ENABLE_HUSH_FAST
7471 G.count_SIGCHLD++;
7472//bb_error_msg("[%d] fork in generate_stream_from_string:"
7473// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7474// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7475# endif
7476 enable_restore_tty_pgrp_on_exit();
7477# if !BB_MMU
7478 free(to_free);
7479# endif
7480 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007481 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007482}
7483
7484/* Return code is exit status of the process that is run. */
7485static int process_command_subs(o_string *dest, const char *s)
7486{
7487 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007488 pid_t pid;
7489 int status, ch, eol_cnt;
7490
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007491 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007492
7493 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007494 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007495 while ((ch = getc(fp)) != EOF) {
7496 if (ch == '\0')
7497 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007498 if (ch == '\n') {
7499 eol_cnt++;
7500 continue;
7501 }
7502 while (eol_cnt) {
7503 o_addchr(dest, '\n');
7504 eol_cnt--;
7505 }
7506 o_addQchr(dest, ch);
7507 }
7508
7509 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007510 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007511 /* We need to extract exitcode. Test case
7512 * "true; echo `sleep 1; false` $?"
7513 * should print 1 */
7514 safe_waitpid(pid, &status, 0);
7515 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7516 return WEXITSTATUS(status);
7517}
7518#endif /* ENABLE_HUSH_TICK */
7519
7520
7521static void setup_heredoc(struct redir_struct *redir)
7522{
7523 struct fd_pair pair;
7524 pid_t pid;
7525 int len, written;
7526 /* the _body_ of heredoc (misleading field name) */
7527 const char *heredoc = redir->rd_filename;
7528 char *expanded;
7529#if !BB_MMU
7530 char **to_free;
7531#endif
7532
7533 expanded = NULL;
7534 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007535 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007536 if (expanded)
7537 heredoc = expanded;
7538 }
7539 len = strlen(heredoc);
7540
7541 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7542 xpiped_pair(pair);
7543 xmove_fd(pair.rd, redir->rd_fd);
7544
7545 /* Try writing without forking. Newer kernels have
7546 * dynamically growing pipes. Must use non-blocking write! */
7547 ndelay_on(pair.wr);
7548 while (1) {
7549 written = write(pair.wr, heredoc, len);
7550 if (written <= 0)
7551 break;
7552 len -= written;
7553 if (len == 0) {
7554 close(pair.wr);
7555 free(expanded);
7556 return;
7557 }
7558 heredoc += written;
7559 }
7560 ndelay_off(pair.wr);
7561
7562 /* Okay, pipe buffer was not big enough */
7563 /* Note: we must not create a stray child (bastard? :)
7564 * for the unsuspecting parent process. Child creates a grandchild
7565 * and exits before parent execs the process which consumes heredoc
7566 * (that exec happens after we return from this function) */
7567#if !BB_MMU
7568 to_free = NULL;
7569#endif
7570 pid = xvfork();
7571 if (pid == 0) {
7572 /* child */
7573 disable_restore_tty_pgrp_on_exit();
7574 pid = BB_MMU ? xfork() : xvfork();
7575 if (pid != 0)
7576 _exit(0);
7577 /* grandchild */
7578 close(redir->rd_fd); /* read side of the pipe */
7579#if BB_MMU
7580 full_write(pair.wr, heredoc, len); /* may loop or block */
7581 _exit(0);
7582#else
7583 /* Delegate blocking writes to another process */
7584 xmove_fd(pair.wr, STDOUT_FILENO);
7585 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7586#endif
7587 }
7588 /* parent */
7589#if ENABLE_HUSH_FAST
7590 G.count_SIGCHLD++;
7591//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7592#endif
7593 enable_restore_tty_pgrp_on_exit();
7594#if !BB_MMU
7595 free(to_free);
7596#endif
7597 close(pair.wr);
7598 free(expanded);
7599 wait(NULL); /* wait till child has died */
7600}
7601
Denys Vlasenko2db74612017-07-07 22:07:28 +02007602struct squirrel {
7603 int orig_fd;
7604 int moved_to;
7605 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7606 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7607};
7608
Denys Vlasenko621fc502017-07-24 12:42:17 +02007609static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7610{
7611 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7612 sq[i].orig_fd = orig;
7613 sq[i].moved_to = moved;
7614 sq[i+1].orig_fd = -1; /* end marker */
7615 return sq;
7616}
7617
Denys Vlasenko2db74612017-07-07 22:07:28 +02007618static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7619{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007620 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007621 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007622
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007623 i = 0;
7624 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007625 /* If we collide with an already moved fd... */
7626 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007627 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007628 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7629 if (sq[i].moved_to < 0) /* what? */
7630 xfunc_die();
7631 return sq;
7632 }
7633 if (fd == sq[i].orig_fd) {
7634 /* Example: echo Hello >/dev/null 1>&2 */
7635 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7636 return sq;
7637 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007638 }
7639
Denys Vlasenko2db74612017-07-07 22:07:28 +02007640 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007641 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007642 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7643 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007644 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007645 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007646}
7647
Denys Vlasenko657e9002017-07-30 23:34:04 +02007648static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7649{
7650 int i;
7651
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007652 i = 0;
7653 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007654 /* If we collide with an already moved fd... */
7655 if (fd == sq[i].orig_fd) {
7656 /* Examples:
7657 * "echo 3>FILE 3>&- 3>FILE"
7658 * "echo 3>&- 3>FILE"
7659 * No need for last redirect to insert
7660 * another "need to close 3" indicator.
7661 */
7662 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7663 return sq;
7664 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007665 }
7666
7667 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7668 return append_squirrel(sq, i, fd, -1);
7669}
7670
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007671/* fd: redirect wants this fd to be used (e.g. 3>file).
7672 * Move all conflicting internally used fds,
7673 * and remember them so that we can restore them later.
7674 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007675static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007676{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007677 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7678 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007679
7680#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko21806562019-11-01 14:16:07 +01007681 if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
7682 && fd == G_interactive_fd
7683 ) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007684 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007685 G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
7686 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 +02007687 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007688 }
7689#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007690 /* Are we called from setup_redirects(squirrel==NULL)
7691 * in redirect in a [v]forked child?
7692 */
7693 if (sqp == NULL) {
7694 /* No need to move script fds.
7695 * For NOMMU case, it's actively wrong: we'd change ->fd
7696 * fields in memory for the parent, but parent's fds
Denys Vlasenko21806562019-11-01 14:16:07 +01007697 * aren't moved, it would use wrong fd!
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007698 * Reproducer: "cmd 3>FILE" in script.
7699 * If we would call move_HFILEs_on_redirect(), child would:
7700 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7701 * close(3) = 0
7702 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7703 */
7704 //bb_error_msg("sqp == NULL: [v]forked child");
7705 return 0;
7706 }
7707
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007708 /* If this one of script's fds? */
7709 if (move_HFILEs_on_redirect(fd, avoid_fd))
7710 return 1; /* yes. "we closed fd" (actually moved it) */
7711
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007712 /* Are we called for "exec 3>FILE"? Came through
7713 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7714 * This case used to fail for this script:
7715 * exec 3>FILE
7716 * echo Ok
7717 * ...100000 more lines...
7718 * echo Ok
7719 * as follows:
7720 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7721 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7722 * dup2(4, 3) = 3
7723 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7724 * close(4) = 0
7725 * write(1, "Ok\n", 3) = 3
7726 * ... = 3
7727 * write(1, "Ok\n", 3) = 3
7728 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7729 * ^^^^^^^^ oops, wrong fd!!!
7730 * With this case separate from sqp == NULL and *after* move_HFILEs,
7731 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007732 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007733 if (sqp == ERR_PTR) {
7734 /* Don't preserve redirected fds: exec is _meant_ to change these */
7735 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007736 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007737 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007738
Denys Vlasenko2db74612017-07-07 22:07:28 +02007739 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7740 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7741 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007742}
7743
Denys Vlasenko2db74612017-07-07 22:07:28 +02007744static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007745{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007746 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007747 int i;
7748 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007749 if (sq[i].moved_to >= 0) {
7750 /* We simply die on error */
7751 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7752 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7753 } else {
7754 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7755 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7756 close(sq[i].orig_fd);
7757 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007758 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007759 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007760 }
Denys Vlasenko21806562019-11-01 14:16:07 +01007761 if (G.HFILE_stdin
7762 && G.HFILE_stdin->fd != STDIN_FILENO
7763 ) {
7764 /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
7765 * Redirect moves ->fd to e.g. 10,
7766 * and it is not restored above (we do not restore script fds
7767 * after redirects, we just use new, "moved" fds).
7768 * However for stdin, get_user_input() -> read_line_input(),
7769 * and read builtin, depend on fd == STDIN_FILENO.
7770 */
7771 debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
7772 xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
7773 G.HFILE_stdin->fd = STDIN_FILENO;
7774 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007775
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007776 /* If moved, G_interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007777}
7778
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007779#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007780static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007781{
7782 if (G_interactive_fd)
7783 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007784 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007785}
7786#endif
7787
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007788static int internally_opened_fd(int fd, struct squirrel *sq)
7789{
7790 int i;
7791
7792#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007793 if (fd == G_interactive_fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007794 return 1;
7795#endif
7796 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007797 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007798 return 1;
7799
7800 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7801 if (fd == sq[i].moved_to)
7802 return 1;
7803 }
7804 return 0;
7805}
7806
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007807/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7808 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007809static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007810{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007811 struct redir_struct *redir;
7812
7813 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007814 int newfd;
7815 int closed;
7816
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007817 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007818 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007819 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007820 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7821 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007822 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007823 redir->rd_filename);
7824 setup_heredoc(redir);
7825 continue;
7826 }
7827
7828 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007829 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007830 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007831 int mode;
7832
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007833 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007834 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007835 * "cmd >" (no filename)
7836 * "cmd > <file" (2nd redirect starts too early)
7837 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007838 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007839 continue;
7840 }
7841 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007842 p = expand_string_to_string(redir->rd_filename,
7843 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007844 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007845 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007846 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007847 /* Error message from open_or_warn can be lost
7848 * if stderr has been redirected, but bash
7849 * and ash both lose it as well
7850 * (though zsh doesn't!)
7851 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007852 return 1;
7853 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007854 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007855 /* open() gave us precisely the fd we wanted.
7856 * This means that this fd was not busy
7857 * (not opened to anywhere).
7858 * Remember to close it on restore:
7859 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007860 *sqp = add_squirrel_closed(*sqp, newfd);
7861 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007862 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007863 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007864 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7865 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007866 }
7867
Denys Vlasenko657e9002017-07-30 23:34:04 +02007868 if (newfd == redir->rd_fd)
7869 continue;
7870
7871 /* if "N>FILE": move newfd to redir->rd_fd */
7872 /* if "N>&M": dup newfd to redir->rd_fd */
7873 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7874
7875 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7876 if (newfd == REDIRFD_CLOSE) {
7877 /* "N>&-" means "close me" */
7878 if (!closed) {
7879 /* ^^^ optimization: saving may already
7880 * have closed it. If not... */
7881 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007882 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007883 /* Sometimes we do another close on restore, getting EBADF.
7884 * Consider "echo 3>FILE 3>&-"
7885 * first redirect remembers "need to close 3",
7886 * and second redirect closes 3! Restore code then closes 3 again.
7887 */
7888 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007889 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007890 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007891 //errno = EBADF;
7892 //bb_perror_msg_and_die("can't duplicate file descriptor");
7893 newfd = -1; /* same effect as code above */
7894 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007895 xdup2(newfd, redir->rd_fd);
7896 if (redir->rd_dup == REDIRFD_TO_FILE)
7897 /* "rd_fd > FILE" */
7898 close(newfd);
7899 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007900 }
7901 }
7902 return 0;
7903}
7904
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007905static char *find_in_path(const char *arg)
7906{
7907 char *ret = NULL;
7908 const char *PATH = get_local_var_value("PATH");
7909
7910 if (!PATH)
7911 return NULL;
7912
7913 while (1) {
7914 const char *end = strchrnul(PATH, ':');
7915 int sz = end - PATH; /* must be int! */
7916
7917 free(ret);
7918 if (sz != 0) {
7919 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7920 } else {
7921 /* We have xxx::yyyy in $PATH,
7922 * it means "use current dir" */
7923 ret = xstrdup(arg);
7924 }
7925 if (access(ret, F_OK) == 0)
7926 break;
7927
7928 if (*end == '\0') {
7929 free(ret);
7930 return NULL;
7931 }
7932 PATH = end + 1;
7933 }
7934
7935 return ret;
7936}
7937
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007938static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007939 const struct built_in_command *x,
7940 const struct built_in_command *end)
7941{
7942 while (x != end) {
7943 if (strcmp(name, x->b_cmd) != 0) {
7944 x++;
7945 continue;
7946 }
7947 debug_printf_exec("found builtin '%s'\n", name);
7948 return x;
7949 }
7950 return NULL;
7951}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007952static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007953{
7954 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7955}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007956static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007957{
7958 const struct built_in_command *x = find_builtin1(name);
7959 if (x)
7960 return x;
7961 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7962}
7963
Denys Vlasenkod5314e72020-06-24 09:31:30 +02007964#if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
Ron Yorston9e2a5662020-01-21 16:01:58 +00007965static const char * FAST_FUNC get_builtin_name(int i)
7966{
7967 if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
7968 return bltins1[i].b_cmd;
7969 }
7970 i -= ARRAY_SIZE(bltins1);
7971 if (i < ARRAY_SIZE(bltins2)) {
7972 return bltins2[i].b_cmd;
7973 }
7974 return NULL;
7975}
7976#endif
7977
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007978static void remove_nested_vars(void)
7979{
7980 struct variable *cur;
7981 struct variable **cur_pp;
7982
7983 cur_pp = &G.top_var;
7984 while ((cur = *cur_pp) != NULL) {
7985 if (cur->var_nest_level <= G.var_nest_level) {
7986 cur_pp = &cur->next;
7987 continue;
7988 }
7989 /* Unexport */
7990 if (cur->flg_export) {
7991 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7992 bb_unsetenv(cur->varstr);
7993 }
7994 /* Remove from global list */
7995 *cur_pp = cur->next;
7996 /* Free */
7997 if (!cur->max_len) {
7998 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7999 free(cur->varstr);
8000 }
8001 free(cur);
8002 }
8003}
8004
8005static void enter_var_nest_level(void)
8006{
8007 G.var_nest_level++;
8008 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
8009
8010 /* Try: f() { echo -n .; f; }; f
8011 * struct variable::var_nest_level is uint16_t,
8012 * thus limiting recursion to < 2^16.
8013 * In any case, with 8 Mbyte stack SEGV happens
8014 * not too long after 2^16 recursions anyway.
8015 */
8016 if (G.var_nest_level > 0xff00)
8017 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
8018}
8019
8020static void leave_var_nest_level(void)
8021{
8022 G.var_nest_level--;
8023 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
8024 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
James Byrne69374872019-07-02 11:35:03 +02008025 bb_simple_error_msg_and_die("BUG: nesting underflow");
Denys Vlasenko99496dc2018-06-26 15:36:58 +02008026
8027 remove_nested_vars();
8028}
8029
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008030#if ENABLE_HUSH_FUNCTIONS
8031static struct function **find_function_slot(const char *name)
8032{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008033 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008034 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008035
8036 while ((funcp = *funcpp) != NULL) {
8037 if (strcmp(name, funcp->name) == 0) {
8038 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008039 break;
8040 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008041 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008042 }
8043 return funcpp;
8044}
8045
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008046static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008047{
8048 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008049 return funcp;
8050}
8051
8052/* Note: takes ownership on name ptr */
8053static struct function *new_function(char *name)
8054{
8055 struct function **funcpp = find_function_slot(name);
8056 struct function *funcp = *funcpp;
8057
8058 if (funcp != NULL) {
8059 struct command *cmd = funcp->parent_cmd;
8060 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
8061 if (!cmd) {
8062 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
8063 free(funcp->name);
8064 /* Note: if !funcp->body, do not free body_as_string!
8065 * This is a special case of "-F name body" function:
8066 * body_as_string was not malloced! */
8067 if (funcp->body) {
8068 free_pipe_list(funcp->body);
8069# if !BB_MMU
8070 free(funcp->body_as_string);
8071# endif
8072 }
8073 } else {
8074 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
8075 cmd->argv[0] = funcp->name;
8076 cmd->group = funcp->body;
8077# if !BB_MMU
8078 cmd->group_as_string = funcp->body_as_string;
8079# endif
8080 }
8081 } else {
8082 debug_printf_exec("remembering new function '%s'\n", name);
8083 funcp = *funcpp = xzalloc(sizeof(*funcp));
8084 /*funcp->next = NULL;*/
8085 }
8086
8087 funcp->name = name;
8088 return funcp;
8089}
8090
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008091# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008092static void unset_func(const char *name)
8093{
8094 struct function **funcpp = find_function_slot(name);
8095 struct function *funcp = *funcpp;
8096
8097 if (funcp != NULL) {
8098 debug_printf_exec("freeing function '%s'\n", funcp->name);
8099 *funcpp = funcp->next;
8100 /* funcp is unlinked now, deleting it.
8101 * Note: if !funcp->body, the function was created by
8102 * "-F name body", do not free ->body_as_string
8103 * and ->name as they were not malloced. */
8104 if (funcp->body) {
8105 free_pipe_list(funcp->body);
8106 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008107# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008108 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008109# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008110 }
8111 free(funcp);
8112 }
8113}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008114# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008115
8116# if BB_MMU
8117#define exec_function(to_free, funcp, argv) \
8118 exec_function(funcp, argv)
8119# endif
8120static void exec_function(char ***to_free,
8121 const struct function *funcp,
8122 char **argv) NORETURN;
8123static void exec_function(char ***to_free,
8124 const struct function *funcp,
8125 char **argv)
8126{
8127# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008128 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008129
8130 argv[0] = G.global_argv[0];
8131 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008132 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008133
8134// Example when we are here: "cmd | func"
8135// func will run with saved-redirect fds open.
8136// $ f() { echo /proc/self/fd/*; }
8137// $ true | f
8138// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8139// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8140// Same in script:
8141// $ . ./SCRIPT
8142// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8143// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8144// They are CLOEXEC so external programs won't see them, but
8145// for "more correctness" we might want to close those extra fds here:
8146//? close_saved_fds_and_FILE_fds();
8147
Denys Vlasenko332e4112018-04-04 22:32:59 +02008148 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008149 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008150 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008151 IF_HUSH_LOCAL(G.func_nest_level++;)
8152
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008153 /* On MMU, funcp->body is always non-NULL */
8154 n = run_list(funcp->body);
8155 fflush_all();
8156 _exit(n);
8157# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008158//? close_saved_fds_and_FILE_fds();
8159
8160//TODO: check whether "true | func_with_return" works
8161
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008162 re_execute_shell(to_free,
8163 funcp->body_as_string,
8164 G.global_argv[0],
8165 argv + 1,
8166 NULL);
8167# endif
8168}
8169
8170static int run_function(const struct function *funcp, char **argv)
8171{
8172 int rc;
8173 save_arg_t sv;
8174 smallint sv_flg;
8175
8176 save_and_replace_G_args(&sv, argv);
8177
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008178 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008179 sv_flg = G_flag_return_in_progress;
8180 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008181
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008182 /* Make "local" variables properly shadow previous ones */
8183 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008184 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008185
8186 /* On MMU, funcp->body is always non-NULL */
8187# if !BB_MMU
8188 if (!funcp->body) {
8189 /* Function defined by -F */
8190 parse_and_run_string(funcp->body_as_string);
8191 rc = G.last_exitcode;
8192 } else
8193# endif
8194 {
8195 rc = run_list(funcp->body);
8196 }
8197
Denys Vlasenko332e4112018-04-04 22:32:59 +02008198 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008199 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008200
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008201 G_flag_return_in_progress = sv_flg;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01008202# if ENABLE_HUSH_TRAP
8203 debug_printf_exec("G.return_exitcode=-1\n");
8204 G.return_exitcode = -1; /* invalidate stashed return value */
8205# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008206
8207 restore_G_args(&sv, argv);
8208
8209 return rc;
8210}
8211#endif /* ENABLE_HUSH_FUNCTIONS */
8212
8213
8214#if BB_MMU
8215#define exec_builtin(to_free, x, argv) \
8216 exec_builtin(x, argv)
8217#else
8218#define exec_builtin(to_free, x, argv) \
8219 exec_builtin(to_free, argv)
8220#endif
8221static void exec_builtin(char ***to_free,
8222 const struct built_in_command *x,
8223 char **argv) NORETURN;
8224static void exec_builtin(char ***to_free,
8225 const struct built_in_command *x,
8226 char **argv)
8227{
8228#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008229 int rcode;
8230 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008231//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008232 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008233 fflush_all();
8234 _exit(rcode);
8235#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008236 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008237 /* On NOMMU, we must never block!
8238 * Example: { sleep 99 | read line; } & echo Ok
8239 */
8240 re_execute_shell(to_free,
8241 argv[0],
8242 G.global_argv[0],
8243 G.global_argv + 1,
8244 argv);
8245#endif
8246}
8247
8248
8249static void execvp_or_die(char **argv) NORETURN;
8250static void execvp_or_die(char **argv)
8251{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008252 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008253 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008254 /* Don't propagate SIG_IGN to the child */
8255 if (SPECIAL_JOBSTOP_SIGS != 0)
8256 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008257 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008258 e = 2;
8259 if (errno == EACCES) e = 126;
8260 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008261 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008262 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008263}
8264
8265#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008266static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008267{
8268 unsigned len;
8269 const char *cp;
8270
8271 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008272
8273 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8274 /* test a char with: bash -c 'set -x; echo "CH"' */
8275 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8276 " " "\001\002\003\004\005\006\007"
8277 "\010\011\012\013\014\015\016\017"
8278 "\020\021\022\023\024\025\026\027"
8279 "\030\031\032\033\034\035\036\037"
8280 )
8281 ] == '\0'
8282 ) {
8283 /* string has no special chars */
8284 x_mode_addstr(str);
8285 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008286 }
8287
8288 cp = str;
8289 for (;;) {
8290 /* print '....' up to EOL or first squote */
8291 len = (int)(strchrnul(cp, '\'') - cp);
8292 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008293 x_mode_addchr('\'');
8294 x_mode_addblock(cp, len);
8295 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008296 cp += len;
8297 }
8298 if (*cp == '\0')
8299 break;
8300 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008301 x_mode_addchr('\\');
8302 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008303 cp++;
8304 }
8305}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008306static void dump_cmd_in_x_mode(char **argv)
8307{
8308 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008309 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008310
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008311 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008312 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008313 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008314 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008315 x_mode_addchr(' ');
8316 if (argv[n][0] == '\0') {
8317 x_mode_addchr('\'');
8318 x_mode_addchr('\'');
8319 } else {
8320 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008321 }
8322 n++;
8323 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008324 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008325 }
8326}
8327#else
8328# define dump_cmd_in_x_mode(argv) ((void)0)
8329#endif
8330
Denys Vlasenko57000292018-01-12 14:41:45 +01008331#if ENABLE_HUSH_COMMAND
8332static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8333{
8334 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008335
Denys Vlasenko57000292018-01-12 14:41:45 +01008336 if (!opt_vV)
8337 return;
8338
8339 to_free = NULL;
8340 if (!explanation) {
8341 char *path = getenv("PATH");
8342 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008343 if (!explanation)
8344 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008345 if (opt_vV != 'V')
8346 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8347 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008348 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008349 free(to_free);
8350 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008351 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008352}
8353#else
8354# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8355#endif
8356
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008357#if BB_MMU
8358#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8359 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8360#define pseudo_exec(nommu_save, command, argv_expanded) \
8361 pseudo_exec(command, argv_expanded)
8362#endif
8363
8364/* Called after [v]fork() in run_pipe, or from builtin_exec.
8365 * Never returns.
8366 * Don't exit() here. If you don't exec, use _exit instead.
8367 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008368 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008369 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008370static void pseudo_exec_argv(nommu_save_t *nommu_save,
8371 char **argv, int assignment_cnt,
8372 char **argv_expanded) NORETURN;
8373static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8374 char **argv, int assignment_cnt,
8375 char **argv_expanded)
8376{
Denys Vlasenko57000292018-01-12 14:41:45 +01008377 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008378 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008379 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008380 IF_HUSH_COMMAND(char opt_vV = 0;)
8381 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008382
8383 new_env = expand_assignments(argv, assignment_cnt);
8384 dump_cmd_in_x_mode(new_env);
8385
8386 if (!argv[assignment_cnt]) {
8387 /* Case when we are here: ... | var=val | ...
8388 * (note that we do not exit early, i.e., do not optimize out
8389 * expand_assignments(): think about ... | var=`sleep 1` | ...
8390 */
8391 free_strings(new_env);
8392 _exit(EXIT_SUCCESS);
8393 }
8394
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008395 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008396#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008397 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008398#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008399 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008400 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008401#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008402 set_vars_and_save_old(new_env);
8403 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008404
8405 if (argv_expanded) {
8406 argv = argv_expanded;
8407 } else {
8408 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8409#if !BB_MMU
8410 nommu_save->argv = argv;
8411#endif
8412 }
8413 dump_cmd_in_x_mode(argv);
8414
8415#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8416 if (strchr(argv[0], '/') != NULL)
8417 goto skip;
8418#endif
8419
Denys Vlasenko75481d32017-07-31 05:27:09 +02008420#if ENABLE_HUSH_FUNCTIONS
8421 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008422 funcp = find_function(argv[0]);
8423 if (funcp)
8424 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008425#endif
8426
Denys Vlasenko57000292018-01-12 14:41:45 +01008427#if ENABLE_HUSH_COMMAND
8428 /* "command BAR": run BAR without looking it up among functions
8429 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8430 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8431 */
8432 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8433 char *p;
8434
8435 argv++;
8436 p = *argv;
8437 if (p[0] != '-' || !p[1])
8438 continue; /* bash allows "command command command [-OPT] BAR" */
8439
8440 for (;;) {
8441 p++;
8442 switch (*p) {
8443 case '\0':
8444 argv++;
8445 p = *argv;
8446 if (p[0] != '-' || !p[1])
8447 goto after_opts;
8448 continue; /* next arg is also -opts, process it too */
8449 case 'v':
8450 case 'V':
8451 opt_vV = *p;
8452 continue;
8453 default:
8454 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8455 }
8456 }
8457 }
8458 after_opts:
8459# if ENABLE_HUSH_FUNCTIONS
8460 if (opt_vV && find_function(argv[0]))
8461 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8462# endif
8463#endif
8464
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008465 /* Check if the command matches any of the builtins.
8466 * Depending on context, this might be redundant. But it's
8467 * easier to waste a few CPU cycles than it is to figure out
8468 * if this is one of those cases.
8469 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008470 /* Why "BB_MMU ? :" difference in logic? -
8471 * On NOMMU, it is more expensive to re-execute shell
8472 * just in order to run echo or test builtin.
8473 * It's better to skip it here and run corresponding
8474 * non-builtin later. */
8475 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8476 if (x) {
8477 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8478 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008479 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008480
8481#if ENABLE_FEATURE_SH_STANDALONE
8482 /* Check if the command matches any busybox applets */
8483 {
8484 int a = find_applet_by_name(argv[0]);
8485 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008486 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008487# if BB_MMU /* see above why on NOMMU it is not allowed */
8488 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008489 /* Do not leak open fds from opened script files etc.
8490 * Testcase: interactive "ls -l /proc/self/fd"
8491 * should not show tty fd open.
8492 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008493 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008494//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008495//This casuses test failures in
8496//redir_children_should_not_see_saved_fd_2.tests
8497//redir_children_should_not_see_saved_fd_3.tests
8498//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008499 /* Without this, "rm -i FILE" can't be ^C'ed: */
8500 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008501 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008502 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008503 }
8504# endif
8505 /* Re-exec ourselves */
8506 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008507 /* Don't propagate SIG_IGN to the child */
8508 if (SPECIAL_JOBSTOP_SIGS != 0)
8509 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008510 execv(bb_busybox_exec_path, argv);
8511 /* If they called chroot or otherwise made the binary no longer
8512 * executable, fall through */
8513 }
8514 }
8515#endif
8516
8517#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8518 skip:
8519#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008520 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008521 execvp_or_die(argv);
8522}
8523
8524/* Called after [v]fork() in run_pipe
8525 */
8526static void pseudo_exec(nommu_save_t *nommu_save,
8527 struct command *command,
8528 char **argv_expanded) NORETURN;
8529static void pseudo_exec(nommu_save_t *nommu_save,
8530 struct command *command,
8531 char **argv_expanded)
8532{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008533#if ENABLE_HUSH_FUNCTIONS
8534 if (command->cmd_type == CMD_FUNCDEF) {
8535 /* Ignore funcdefs in pipes:
8536 * true | f() { cmd }
8537 */
8538 _exit(0);
8539 }
8540#endif
8541
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008542 if (command->argv) {
8543 pseudo_exec_argv(nommu_save, command->argv,
8544 command->assignment_cnt, argv_expanded);
8545 }
8546
8547 if (command->group) {
8548 /* Cases when we are here:
8549 * ( list )
8550 * { list } &
8551 * ... | ( list ) | ...
8552 * ... | { list } | ...
8553 */
8554#if BB_MMU
8555 int rcode;
8556 debug_printf_exec("pseudo_exec: run_list\n");
8557 reset_traps_to_defaults();
8558 rcode = run_list(command->group);
8559 /* OK to leak memory by not calling free_pipe_list,
8560 * since this process is about to exit */
8561 _exit(rcode);
8562#else
8563 re_execute_shell(&nommu_save->argv_from_re_execing,
8564 command->group_as_string,
8565 G.global_argv[0],
8566 G.global_argv + 1,
8567 NULL);
8568#endif
8569 }
8570
8571 /* Case when we are here: ... | >file */
8572 debug_printf_exec("pseudo_exec'ed null command\n");
8573 _exit(EXIT_SUCCESS);
8574}
8575
8576#if ENABLE_HUSH_JOB
8577static const char *get_cmdtext(struct pipe *pi)
8578{
8579 char **argv;
8580 char *p;
8581 int len;
8582
8583 /* This is subtle. ->cmdtext is created only on first backgrounding.
8584 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8585 * On subsequent bg argv is trashed, but we won't use it */
8586 if (pi->cmdtext)
8587 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008588
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008589 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008590 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008591 pi->cmdtext = xzalloc(1);
8592 return pi->cmdtext;
8593 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008594 len = 0;
8595 do {
8596 len += strlen(*argv) + 1;
8597 } while (*++argv);
8598 p = xmalloc(len);
8599 pi->cmdtext = p;
8600 argv = pi->cmds[0].argv;
8601 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008602 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008603 *p++ = ' ';
8604 } while (*++argv);
8605 p[-1] = '\0';
8606 return pi->cmdtext;
8607}
8608
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008609static void remove_job_from_table(struct pipe *pi)
8610{
8611 struct pipe *prev_pipe;
8612
8613 if (pi == G.job_list) {
8614 G.job_list = pi->next;
8615 } else {
8616 prev_pipe = G.job_list;
8617 while (prev_pipe->next != pi)
8618 prev_pipe = prev_pipe->next;
8619 prev_pipe->next = pi->next;
8620 }
8621 G.last_jobid = 0;
8622 if (G.job_list)
8623 G.last_jobid = G.job_list->jobid;
8624}
8625
8626static void delete_finished_job(struct pipe *pi)
8627{
8628 remove_job_from_table(pi);
8629 free_pipe(pi);
8630}
8631
8632static void clean_up_last_dead_job(void)
8633{
8634 if (G.job_list && !G.job_list->alive_cmds)
8635 delete_finished_job(G.job_list);
8636}
8637
Denys Vlasenko16096292017-07-10 10:00:28 +02008638static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008639{
8640 struct pipe *job, **jobp;
8641 int i;
8642
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008643 clean_up_last_dead_job();
8644
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008645 /* Find the end of the list, and find next job ID to use */
8646 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008647 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008648 while ((job = *jobp) != NULL) {
8649 if (job->jobid > i)
8650 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008651 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008652 }
8653 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008654
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008655 /* Create a new job struct at the end */
8656 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008657 job->next = NULL;
8658 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8659 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8660 for (i = 0; i < pi->num_cmds; i++) {
8661 job->cmds[i].pid = pi->cmds[i].pid;
8662 /* all other fields are not used and stay zero */
8663 }
8664 job->cmdtext = xstrdup(get_cmdtext(pi));
8665
8666 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008667 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008668 G.last_jobid = job->jobid;
8669}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008670#endif /* JOB */
8671
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008672static int job_exited_or_stopped(struct pipe *pi)
8673{
8674 int rcode, i;
8675
8676 if (pi->alive_cmds != pi->stopped_cmds)
8677 return -1;
8678
8679 /* All processes in fg pipe have exited or stopped */
8680 rcode = 0;
8681 i = pi->num_cmds;
8682 while (--i >= 0) {
8683 rcode = pi->cmds[i].cmd_exitcode;
8684 /* usually last process gives overall exitstatus,
8685 * but with "set -o pipefail", last *failed* process does */
8686 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8687 break;
8688 }
8689 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8690 return rcode;
8691}
8692
Denys Vlasenko7e675362016-10-28 21:57:31 +02008693static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008694{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008695#if ENABLE_HUSH_JOB
8696 struct pipe *pi;
8697#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008698 int i, dead;
8699
8700 dead = WIFEXITED(status) || WIFSIGNALED(status);
8701
8702#if DEBUG_JOBS
8703 if (WIFSTOPPED(status))
8704 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8705 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8706 if (WIFSIGNALED(status))
8707 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8708 childpid, WTERMSIG(status), WEXITSTATUS(status));
8709 if (WIFEXITED(status))
8710 debug_printf_jobs("pid %d exited, exitcode %d\n",
8711 childpid, WEXITSTATUS(status));
8712#endif
8713 /* Were we asked to wait for a fg pipe? */
8714 if (fg_pipe) {
8715 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008716
Denys Vlasenko7e675362016-10-28 21:57:31 +02008717 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008718 int rcode;
8719
Denys Vlasenko7e675362016-10-28 21:57:31 +02008720 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8721 if (fg_pipe->cmds[i].pid != childpid)
8722 continue;
8723 if (dead) {
8724 int ex;
8725 fg_pipe->cmds[i].pid = 0;
8726 fg_pipe->alive_cmds--;
8727 ex = WEXITSTATUS(status);
8728 /* bash prints killer signal's name for *last*
8729 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8730 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8731 */
8732 if (WIFSIGNALED(status)) {
8733 int sig = WTERMSIG(status);
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008734 if (G.run_list_level == 1
8735 /* ^^^^^ Do not print in nested contexts, example:
8736 * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
8737 */
8738 && i == fg_pipe->num_cmds-1
8739 ) {
Denys Vlasenkoe16f7eb2020-10-24 04:26:43 +02008740 /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
8741 puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008742 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008743 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8744 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8745 * Maybe we need to use sig | 128? */
8746 ex = sig + 128;
8747 }
8748 fg_pipe->cmds[i].cmd_exitcode = ex;
8749 } else {
8750 fg_pipe->stopped_cmds++;
8751 }
8752 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8753 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008754 rcode = job_exited_or_stopped(fg_pipe);
8755 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008756/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8757 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8758 * and "killall -STOP cat" */
8759 if (G_interactive_fd) {
8760#if ENABLE_HUSH_JOB
8761 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008762 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008763#endif
8764 return rcode;
8765 }
8766 if (fg_pipe->alive_cmds == 0)
8767 return rcode;
8768 }
8769 /* There are still running processes in the fg_pipe */
8770 return -1;
8771 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008772 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008773 }
8774
8775#if ENABLE_HUSH_JOB
8776 /* We were asked to wait for bg or orphaned children */
8777 /* No need to remember exitcode in this case */
8778 for (pi = G.job_list; pi; pi = pi->next) {
8779 for (i = 0; i < pi->num_cmds; i++) {
8780 if (pi->cmds[i].pid == childpid)
8781 goto found_pi_and_prognum;
8782 }
8783 }
8784 /* Happens when shell is used as init process (init=/bin/sh) */
8785 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8786 return -1; /* this wasn't a process from fg_pipe */
8787
8788 found_pi_and_prognum:
8789 if (dead) {
8790 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008791 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008792 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008793 rcode = 128 + WTERMSIG(status);
8794 pi->cmds[i].cmd_exitcode = rcode;
8795 if (G.last_bg_pid == pi->cmds[i].pid)
8796 G.last_bg_pid_exitcode = rcode;
8797 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008798 pi->alive_cmds--;
8799 if (!pi->alive_cmds) {
Denys Vlasenko259747c2019-11-28 10:28:14 +01008800# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008801 G.dead_job_exitcode = job_exited_or_stopped(pi);
Denys Vlasenko259747c2019-11-28 10:28:14 +01008802# endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008803 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008804 printf(JOB_STATUS_FORMAT, pi->jobid,
8805 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008806 delete_finished_job(pi);
8807 } else {
8808/*
8809 * bash deletes finished jobs from job table only in interactive mode,
8810 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8811 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8812 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8813 * We only retain one "dead" job, if it's the single job on the list.
8814 * This covers most of real-world scenarios where this is useful.
8815 */
8816 if (pi != G.job_list)
8817 delete_finished_job(pi);
8818 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008819 }
8820 } else {
8821 /* child stopped */
8822 pi->stopped_cmds++;
8823 }
8824#endif
8825 return -1; /* this wasn't a process from fg_pipe */
8826}
8827
8828/* Check to see if any processes have exited -- if they have,
8829 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008830 *
8831 * If non-NULL fg_pipe: wait for its completion or stop.
8832 * Return its exitcode or zero if stopped.
8833 *
8834 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8835 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8836 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8837 * or 0 if no children changed status.
8838 *
8839 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8840 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8841 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008842 */
8843static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8844{
8845 int attributes;
8846 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008847 int rcode = 0;
8848
8849 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8850
8851 attributes = WUNTRACED;
8852 if (fg_pipe == NULL)
8853 attributes |= WNOHANG;
8854
8855 errno = 0;
8856#if ENABLE_HUSH_FAST
8857 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8858//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8859//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8860 /* There was neither fork nor SIGCHLD since last waitpid */
8861 /* Avoid doing waitpid syscall if possible */
8862 if (!G.we_have_children) {
8863 errno = ECHILD;
8864 return -1;
8865 }
8866 if (fg_pipe == NULL) { /* is WNOHANG set? */
8867 /* We have children, but they did not exit
8868 * or stop yet (we saw no SIGCHLD) */
8869 return 0;
8870 }
8871 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8872 }
8873#endif
8874
8875/* Do we do this right?
8876 * bash-3.00# sleep 20 | false
8877 * <ctrl-Z pressed>
8878 * [3]+ Stopped sleep 20 | false
8879 * bash-3.00# echo $?
8880 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8881 * [hush 1.14.0: yes we do it right]
8882 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008883 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008884 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008885#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008886 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008887 i = G.count_SIGCHLD;
8888#endif
8889 childpid = waitpid(-1, &status, attributes);
8890 if (childpid <= 0) {
8891 if (childpid && errno != ECHILD)
James Byrne69374872019-07-02 11:35:03 +02008892 bb_simple_perror_msg("waitpid");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008893#if ENABLE_HUSH_FAST
8894 else { /* Until next SIGCHLD, waitpid's are useless */
8895 G.we_have_children = (childpid == 0);
8896 G.handled_SIGCHLD = i;
8897//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8898 }
8899#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008900 /* ECHILD (no children), or 0 (no change in children status) */
8901 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008902 break;
8903 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008904 rcode = process_wait_result(fg_pipe, childpid, status);
8905 if (rcode >= 0) {
8906 /* fg_pipe exited or stopped */
8907 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008908 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008909 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008910 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008911 rcode = WEXITSTATUS(status);
8912 if (WIFSIGNALED(status))
8913 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008914 if (WIFSTOPPED(status))
8915 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8916 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008917 rcode++;
8918 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008919 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008920#if ENABLE_HUSH_BASH_COMPAT
8921 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
8922 && G.dead_job_exitcode >= 0 /* some job did finish */
8923 ) {
8924 debug_printf_exec("waitfor_pid:-1\n");
8925 rcode = G.dead_job_exitcode + 1;
8926 break;
8927 }
8928#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008929 /* This wasn't one of our processes, or */
8930 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008931 } /* while (waitpid succeeds)... */
8932
8933 return rcode;
8934}
8935
8936#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008937static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008938{
8939 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008940 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008941 if (G_saved_tty_pgrp) {
8942 /* Job finished, move the shell to the foreground */
8943 p = getpgrp(); /* our process group id */
8944 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8945 tcsetpgrp(G_interactive_fd, p);
8946 }
8947 return rcode;
8948}
8949#endif
8950
8951/* Start all the jobs, but don't wait for anything to finish.
8952 * See checkjobs().
8953 *
8954 * Return code is normally -1, when the caller has to wait for children
8955 * to finish to determine the exit status of the pipe. If the pipe
8956 * is a simple builtin command, however, the action is done by the
8957 * time run_pipe returns, and the exit code is provided as the
8958 * return value.
8959 *
8960 * Returns -1 only if started some children. IOW: we have to
8961 * mask out retvals of builtins etc with 0xff!
8962 *
8963 * The only case when we do not need to [v]fork is when the pipe
8964 * is single, non-backgrounded, non-subshell command. Examples:
8965 * cmd ; ... { list } ; ...
8966 * cmd && ... { list } && ...
8967 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008968 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008969 * or (if SH_STANDALONE) an applet, and we can run the { list }
8970 * with run_list. If it isn't one of these, we fork and exec cmd.
8971 *
8972 * Cases when we must fork:
8973 * non-single: cmd | cmd
8974 * backgrounded: cmd & { list } &
8975 * subshell: ( list ) [&]
8976 */
8977#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008978#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
8979 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008980#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008981static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008982 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008983 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008984 char **argv_expanded)
8985{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008986 /* Assignments occur before redirects. Try:
8987 * a=`sleep 1` sleep 2 3>/qwe/rty
8988 */
8989
8990 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8991 dump_cmd_in_x_mode(new_env);
8992 dump_cmd_in_x_mode(argv_expanded);
8993 /* this takes ownership of new_env[i] elements, and frees new_env: */
8994 set_vars_and_save_old(new_env);
8995
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008996 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008997}
8998static NOINLINE int run_pipe(struct pipe *pi)
8999{
9000 static const char *const null_ptr = NULL;
9001
9002 int cmd_no;
9003 int next_infd;
9004 struct command *command;
9005 char **argv_expanded;
9006 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02009007 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009008 int rcode;
9009
9010 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
9011 debug_enter();
9012
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009013 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
9014 * Result should be 3 lines: q w e, qwe, q w e
9015 */
Denys Vlasenko96786362018-04-11 16:02:58 +02009016 if (G.ifs_whitespace != G.ifs)
9017 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009018 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02009019 if (G.ifs) {
9020 char *p;
9021 G.ifs_whitespace = (char*)G.ifs;
9022 p = skip_whitespace(G.ifs);
9023 if (*p) {
9024 /* Not all $IFS is whitespace */
9025 char *d;
9026 int len = p - G.ifs;
9027 p = skip_non_whitespace(p);
9028 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
9029 d = mempcpy(G.ifs_whitespace, G.ifs, len);
9030 while (*p) {
9031 if (isspace(*p))
9032 *d++ = *p;
9033 p++;
9034 }
9035 *d = '\0';
9036 }
9037 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009038 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02009039 G.ifs_whitespace = (char*)G.ifs;
9040 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009041
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009042 IF_HUSH_JOB(pi->pgrp = -1;)
9043 pi->stopped_cmds = 0;
9044 command = &pi->cmds[0];
9045 argv_expanded = NULL;
9046
9047 if (pi->num_cmds != 1
9048 || pi->followup == PIPE_BG
9049 || command->cmd_type == CMD_SUBSHELL
9050 ) {
9051 goto must_fork;
9052 }
9053
9054 pi->alive_cmds = 1;
9055
9056 debug_printf_exec(": group:%p argv:'%s'\n",
9057 command->group, command->argv ? command->argv[0] : "NONE");
9058
9059 if (command->group) {
9060#if ENABLE_HUSH_FUNCTIONS
9061 if (command->cmd_type == CMD_FUNCDEF) {
9062 /* "executing" func () { list } */
9063 struct function *funcp;
9064
9065 funcp = new_function(command->argv[0]);
9066 /* funcp->name is already set to argv[0] */
9067 funcp->body = command->group;
9068# if !BB_MMU
9069 funcp->body_as_string = command->group_as_string;
9070 command->group_as_string = NULL;
9071# endif
9072 command->group = NULL;
9073 command->argv[0] = NULL;
9074 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
9075 funcp->parent_cmd = command;
9076 command->child_func = funcp;
9077
9078 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
9079 debug_leave();
9080 return EXIT_SUCCESS;
9081 }
9082#endif
9083 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009084 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009085 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009086 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009087 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02009088//FIXME: we need to pass squirrel down into run_list()
9089//for SH_STANDALONE case, or else this construct:
9090// { find /proc/self/fd; true; } >FILE; cmd2
9091//has no way of closing saved fd#1 for "find",
9092//and in SH_STANDALONE mode, "find" is not execed,
9093//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009094 rcode = run_list(command->group) & 0xff;
9095 }
9096 restore_redirects(squirrel);
9097 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9098 debug_leave();
9099 debug_printf_exec("run_pipe: return %d\n", rcode);
9100 return rcode;
9101 }
9102
9103 argv = command->argv ? command->argv : (char **) &null_ptr;
9104 {
9105 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009106 IF_HUSH_FUNCTIONS(const struct function *funcp;)
9107 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009108 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009109 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009110
Denys Vlasenko5807e182018-02-08 19:19:04 +01009111#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009112 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009113#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009114
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009115 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009116 /* Assignments, but no command.
9117 * Ensure redirects take effect (that is, create files).
9118 * Try "a=t >file"
9119 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009120 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009121 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009122 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009123 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009124 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009125
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009126 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009127 i = 0;
9128 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009129 char *p = expand_string_to_string(argv[i],
9130 EXP_FLAG_ESC_GLOB_CHARS,
9131 /*unbackslash:*/ 1
9132 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009133#if ENABLE_HUSH_MODE_X
9134 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009135 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009136 if (i == 0)
9137 x_mode_prefix();
9138 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009139 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009140 if (*eq) eq++;
9141 x_mode_addblock(p, (eq - p));
9142 x_mode_print_optionally_squoted(eq);
9143 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009144 }
9145#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009146 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009147 if (set_local_var(p, /*flag:*/ 0)) {
9148 /* assignment to readonly var / putenv error? */
9149 rcode = 1;
9150 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009151 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009152 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009153 /* Redirect error sets $? to 1. Otherwise,
9154 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009155 * Else, clear $?:
9156 * false; q=`exit 2`; echo $? - should print 2
9157 * false; x=1; echo $? - should print 0
9158 * Because of the 2nd case, we can't just use G.last_exitcode.
9159 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009160 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009161 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009162 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9163 debug_leave();
9164 debug_printf_exec("run_pipe: return %d\n", rcode);
9165 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009166 }
9167
9168 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkod2241f52020-10-31 03:34:07 +01009169#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
9170 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
9171 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
9172 else
9173#endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02009174#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009175 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009176 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009177 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009178#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009179 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009180
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009181 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009182 if (!argv_expanded[0]) {
9183 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009184 /* `false` still has to set exitcode 1 */
9185 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009186 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009187 }
9188
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009189 old_vars = NULL;
9190 sv_shadowed = G.shadowed_vars_pp;
9191
Denys Vlasenko75481d32017-07-31 05:27:09 +02009192 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009193 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9194 IF_HUSH_FUNCTIONS(x = NULL;)
9195 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009196 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009197 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009198 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9199 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009200 /*
9201 * Variable assignments are executed, but then "forgotten":
9202 * a=`sleep 1;echo A` exec 3>&-; echo $a
9203 * sleeps, but prints nothing.
9204 */
9205 enter_var_nest_level();
9206 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009207 rcode = redirect_and_varexp_helper(command,
9208 /*squirrel:*/ ERR_PTR,
9209 argv_expanded
9210 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009211 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009212 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009213
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009214 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009215 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009216
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009217 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009218 * a=b true; env | grep ^a=
9219 */
9220 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009221 /* Collect all variables "shadowed" by helper
9222 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9223 * into old_vars list:
9224 */
9225 G.shadowed_vars_pp = &old_vars;
9226 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009227 if (rcode == 0) {
9228 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009229 /* Do not collect *to old_vars list* vars shadowed
9230 * by e.g. "local VAR" builtin (collect them
9231 * in the previously nested list instead):
9232 * don't want them to be restored immediately
9233 * after "local" completes.
9234 */
9235 G.shadowed_vars_pp = sv_shadowed;
9236
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009237 debug_printf_exec(": builtin '%s' '%s'...\n",
9238 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009239 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009240 rcode = x->b_function(argv_expanded) & 0xff;
9241 fflush_all();
9242 }
9243#if ENABLE_HUSH_FUNCTIONS
9244 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009245 debug_printf_exec(": function '%s' '%s'...\n",
9246 funcp->name, argv_expanded[1]);
9247 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009248 /*
9249 * But do collect *to old_vars list* vars shadowed
9250 * within function execution. To that end, restore
9251 * this pointer _after_ function run:
9252 */
9253 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009254 }
9255#endif
9256 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009257 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009258 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009259 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009260 if (n < 0 || !APPLET_IS_NOFORK(n))
9261 goto must_fork;
9262
9263 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009264 /* Collect all variables "shadowed" by helper into old_vars list */
9265 G.shadowed_vars_pp = &old_vars;
9266 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9267 G.shadowed_vars_pp = sv_shadowed;
9268
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009269 if (rcode == 0) {
9270 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9271 argv_expanded[0], argv_expanded[1]);
9272 /*
9273 * Note: signals (^C) can't interrupt here.
9274 * We remember them and they will be acted upon
9275 * after applet returns.
9276 * This makes applets which can run for a long time
9277 * and/or wait for user input ineligible for NOFORK:
9278 * for example, "yes" or "rm" (rm -i waits for input).
9279 */
9280 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009281 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009282 } else
9283 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009284
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009285 restore_redirects(squirrel);
9286 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009287 leave_var_nest_level();
9288 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009289
9290 /*
9291 * Try "usleep 99999999" + ^C + "echo $?"
9292 * with FEATURE_SH_NOFORK=y.
9293 */
9294 if (!funcp) {
9295 /* It was builtin or nofork.
9296 * if this would be a real fork/execed program,
9297 * it should have died if a fatal sig was received.
9298 * But OTOH, there was no separate process,
9299 * the sig was sent to _shell_, not to non-existing
9300 * child.
9301 * Let's just handle ^C only, this one is obvious:
9302 * we aren't ok with exitcode 0 when ^C was pressed
9303 * during builtin/nofork.
9304 */
9305 if (sigismember(&G.pending_set, SIGINT))
9306 rcode = 128 + SIGINT;
9307 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009308 free(argv_expanded);
9309 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9310 debug_leave();
9311 debug_printf_exec("run_pipe return %d\n", rcode);
9312 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009313 }
9314
9315 must_fork:
9316 /* NB: argv_expanded may already be created, and that
9317 * might include `cmd` runs! Do not rerun it! We *must*
9318 * use argv_expanded if it's non-NULL */
9319
9320 /* Going to fork a child per each pipe member */
9321 pi->alive_cmds = 0;
9322 next_infd = 0;
9323
9324 cmd_no = 0;
9325 while (cmd_no < pi->num_cmds) {
9326 struct fd_pair pipefds;
9327#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009328 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009329 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009330 nommu_save.old_vars = NULL;
9331 nommu_save.argv = NULL;
9332 nommu_save.argv_from_re_execing = NULL;
9333#endif
9334 command = &pi->cmds[cmd_no];
9335 cmd_no++;
9336 if (command->argv) {
9337 debug_printf_exec(": pipe member '%s' '%s'...\n",
9338 command->argv[0], command->argv[1]);
9339 } else {
9340 debug_printf_exec(": pipe member with no argv\n");
9341 }
9342
9343 /* pipes are inserted between pairs of commands */
9344 pipefds.rd = 0;
9345 pipefds.wr = 1;
9346 if (cmd_no < pi->num_cmds)
9347 xpiped_pair(pipefds);
9348
Denys Vlasenko5807e182018-02-08 19:19:04 +01009349#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009350 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009351#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009352
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009353 command->pid = BB_MMU ? fork() : vfork();
9354 if (!command->pid) { /* child */
9355#if ENABLE_HUSH_JOB
9356 disable_restore_tty_pgrp_on_exit();
9357 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9358
9359 /* Every child adds itself to new process group
9360 * with pgid == pid_of_first_child_in_pipe */
9361 if (G.run_list_level == 1 && G_interactive_fd) {
9362 pid_t pgrp;
9363 pgrp = pi->pgrp;
9364 if (pgrp < 0) /* true for 1st process only */
9365 pgrp = getpid();
9366 if (setpgid(0, pgrp) == 0
9367 && pi->followup != PIPE_BG
9368 && G_saved_tty_pgrp /* we have ctty */
9369 ) {
9370 /* We do it in *every* child, not just first,
9371 * to avoid races */
9372 tcsetpgrp(G_interactive_fd, pgrp);
9373 }
9374 }
9375#endif
9376 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9377 /* 1st cmd in backgrounded pipe
9378 * should have its stdin /dev/null'ed */
9379 close(0);
9380 if (open(bb_dev_null, O_RDONLY))
9381 xopen("/", O_RDONLY);
9382 } else {
9383 xmove_fd(next_infd, 0);
9384 }
9385 xmove_fd(pipefds.wr, 1);
9386 if (pipefds.rd > 1)
9387 close(pipefds.rd);
9388 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009389 * and the pipe fd (fd#1) is available for dup'ing:
9390 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9391 * of cmd1 goes into pipe.
9392 */
9393 if (setup_redirects(command, NULL)) {
9394 /* Happens when redir file can't be opened:
9395 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9396 * FOO
9397 * hush: can't open '/qwe/rty': No such file or directory
9398 * BAZ
9399 * (echo BAR is not executed, it hits _exit(1) below)
9400 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009401 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009402 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009403
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009404 /* Stores to nommu_save list of env vars putenv'ed
9405 * (NOMMU, on MMU we don't need that) */
9406 /* cast away volatility... */
9407 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9408 /* pseudo_exec() does not return */
9409 }
9410
9411 /* parent or error */
9412#if ENABLE_HUSH_FAST
9413 G.count_SIGCHLD++;
9414//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9415#endif
9416 enable_restore_tty_pgrp_on_exit();
9417#if !BB_MMU
9418 /* Clean up after vforked child */
9419 free(nommu_save.argv);
9420 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009421 G.var_nest_level = sv_var_nest_level;
9422 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009423 add_vars(nommu_save.old_vars);
9424#endif
9425 free(argv_expanded);
9426 argv_expanded = NULL;
9427 if (command->pid < 0) { /* [v]fork failed */
9428 /* Clearly indicate, was it fork or vfork */
James Byrne69374872019-07-02 11:35:03 +02009429 bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009430 } else {
9431 pi->alive_cmds++;
9432#if ENABLE_HUSH_JOB
9433 /* Second and next children need to know pid of first one */
9434 if (pi->pgrp < 0)
9435 pi->pgrp = command->pid;
9436#endif
9437 }
9438
9439 if (cmd_no > 1)
9440 close(next_infd);
9441 if (cmd_no < pi->num_cmds)
9442 close(pipefds.wr);
9443 /* Pass read (output) pipe end to next iteration */
9444 next_infd = pipefds.rd;
9445 }
9446
9447 if (!pi->alive_cmds) {
9448 debug_leave();
9449 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9450 return 1;
9451 }
9452
9453 debug_leave();
9454 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9455 return -1;
9456}
9457
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009458/* NB: called by pseudo_exec, and therefore must not modify any
9459 * global data until exec/_exit (we can be a child after vfork!) */
9460static int run_list(struct pipe *pi)
9461{
9462#if ENABLE_HUSH_CASE
9463 char *case_word = NULL;
9464#endif
9465#if ENABLE_HUSH_LOOPS
9466 struct pipe *loop_top = NULL;
9467 char **for_lcur = NULL;
9468 char **for_list = NULL;
9469#endif
9470 smallint last_followup;
9471 smalluint rcode;
9472#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9473 smalluint cond_code = 0;
9474#else
9475 enum { cond_code = 0 };
9476#endif
9477#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009478 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009479 smallint last_rword; /* ditto */
9480#endif
9481
9482 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9483 debug_enter();
9484
9485#if ENABLE_HUSH_LOOPS
9486 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009487 {
9488 struct pipe *cpipe;
9489 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9490 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9491 continue;
9492 /* current word is FOR or IN (BOLD in comments below) */
9493 if (cpipe->next == NULL) {
9494 syntax_error("malformed for");
9495 debug_leave();
9496 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9497 return 1;
9498 }
9499 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9500 if (cpipe->next->res_word == RES_DO)
9501 continue;
9502 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9503 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9504 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9505 ) {
9506 syntax_error("malformed for");
9507 debug_leave();
9508 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9509 return 1;
9510 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009511 }
9512 }
9513#endif
9514
9515 /* Past this point, all code paths should jump to ret: label
9516 * in order to return, no direct "return" statements please.
9517 * This helps to ensure that no memory is leaked. */
9518
9519#if ENABLE_HUSH_JOB
9520 G.run_list_level++;
9521#endif
9522
9523#if HAS_KEYWORDS
9524 rword = RES_NONE;
9525 last_rword = RES_XXXX;
9526#endif
9527 last_followup = PIPE_SEQ;
9528 rcode = G.last_exitcode;
9529
9530 /* Go through list of pipes, (maybe) executing them. */
9531 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009532 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009533 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009534
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009535 if (G.flag_SIGINT)
9536 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009537 if (G_flag_return_in_progress == 1)
9538 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009539
9540 IF_HAS_KEYWORDS(rword = pi->res_word;)
9541 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9542 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009543
9544 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009545 if (
9546#if ENABLE_HUSH_IF
9547 rword == RES_IF || rword == RES_ELIF ||
9548#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009549 pi->followup != PIPE_SEQ
9550 ) {
9551 G.errexit_depth++;
9552 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009553#if ENABLE_HUSH_LOOPS
9554 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9555 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9556 ) {
9557 /* start of a loop: remember where loop starts */
9558 loop_top = pi;
9559 G.depth_of_loop++;
9560 }
9561#endif
9562 /* Still in the same "if...", "then..." or "do..." branch? */
9563 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9564 if ((rcode == 0 && last_followup == PIPE_OR)
9565 || (rcode != 0 && last_followup == PIPE_AND)
9566 ) {
9567 /* It is "<true> || CMD" or "<false> && CMD"
9568 * and we should not execute CMD */
9569 debug_printf_exec("skipped cmd because of || or &&\n");
9570 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009571 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009572 }
9573 }
9574 last_followup = pi->followup;
9575 IF_HAS_KEYWORDS(last_rword = rword;)
9576#if ENABLE_HUSH_IF
9577 if (cond_code) {
9578 if (rword == RES_THEN) {
9579 /* if false; then ... fi has exitcode 0! */
9580 G.last_exitcode = rcode = EXIT_SUCCESS;
9581 /* "if <false> THEN cmd": skip cmd */
9582 continue;
9583 }
9584 } else {
9585 if (rword == RES_ELSE || rword == RES_ELIF) {
9586 /* "if <true> then ... ELSE/ELIF cmd":
9587 * skip cmd and all following ones */
9588 break;
9589 }
9590 }
9591#endif
9592#if ENABLE_HUSH_LOOPS
9593 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9594 if (!for_lcur) {
9595 /* first loop through for */
9596
9597 static const char encoded_dollar_at[] ALIGN1 = {
9598 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9599 }; /* encoded representation of "$@" */
9600 static const char *const encoded_dollar_at_argv[] = {
9601 encoded_dollar_at, NULL
9602 }; /* argv list with one element: "$@" */
9603 char **vals;
9604
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009605 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009606 vals = (char**)encoded_dollar_at_argv;
9607 if (pi->next->res_word == RES_IN) {
9608 /* if no variable values after "in" we skip "for" */
9609 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009610 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9611 break;
9612 }
9613 vals = pi->next->cmds[0].argv;
9614 } /* else: "for var; do..." -> assume "$@" list */
9615 /* create list of variable values */
9616 debug_print_strings("for_list made from", vals);
9617 for_list = expand_strvec_to_strvec(vals);
9618 for_lcur = for_list;
9619 debug_print_strings("for_list", for_list);
9620 }
9621 if (!*for_lcur) {
9622 /* "for" loop is over, clean up */
9623 free(for_list);
9624 for_list = NULL;
9625 for_lcur = NULL;
9626 break;
9627 }
9628 /* Insert next value from for_lcur */
9629 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009630 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009631 continue;
9632 }
9633 if (rword == RES_IN) {
9634 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9635 }
9636 if (rword == RES_DONE) {
9637 continue; /* "done" has no cmds too */
9638 }
9639#endif
9640#if ENABLE_HUSH_CASE
9641 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009642 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009643 case_word = expand_string_to_string(pi->cmds->argv[0],
9644 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009645 debug_printf_exec("CASE word1:'%s'\n", case_word);
9646 //unbackslash(case_word);
9647 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009648 continue;
9649 }
9650 if (rword == RES_MATCH) {
9651 char **argv;
9652
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009653 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009654 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9655 break;
9656 /* all prev words didn't match, does this one match? */
9657 argv = pi->cmds->argv;
9658 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009659 char *pattern;
9660 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9661 pattern = expand_string_to_string(*argv,
9662 EXP_FLAG_ESC_GLOB_CHARS,
9663 /*unbackslash:*/ 0
9664 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009665 /* TODO: which FNM_xxx flags to use? */
9666 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009667 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9668 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009669 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009670 if (cond_code == 0) {
9671 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009672 free(case_word);
9673 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009674 break;
9675 }
9676 argv++;
9677 }
9678 continue;
9679 }
9680 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009681 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009682 if (cond_code != 0)
9683 continue; /* not matched yet, skip this pipe */
9684 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009685 if (rword == RES_ESAC) {
9686 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9687 if (case_word) {
9688 /* "case" did not match anything: still set $? (to 0) */
9689 G.last_exitcode = rcode = EXIT_SUCCESS;
9690 }
9691 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009692#endif
9693 /* Just pressing <enter> in shell should check for jobs.
9694 * OTOH, in non-interactive shell this is useless
9695 * and only leads to extra job checks */
9696 if (pi->num_cmds == 0) {
9697 if (G_interactive_fd)
9698 goto check_jobs_and_continue;
9699 continue;
9700 }
9701
9702 /* After analyzing all keywords and conditions, we decided
9703 * to execute this pipe. NB: have to do checkjobs(NULL)
9704 * after run_pipe to collect any background children,
9705 * even if list execution is to be stopped. */
9706 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009707#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009708 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009709#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009710 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9711 if (r != -1) {
9712 /* We ran a builtin, function, or group.
9713 * rcode is already known
9714 * and we don't need to wait for anything. */
9715 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9716 G.last_exitcode = rcode;
9717 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009718#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9719 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9720#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009721#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009722 /* Was it "break" or "continue"? */
9723 if (G.flag_break_continue) {
9724 smallint fbc = G.flag_break_continue;
9725 /* We might fall into outer *loop*,
9726 * don't want to break it too */
9727 if (loop_top) {
9728 G.depth_break_continue--;
9729 if (G.depth_break_continue == 0)
9730 G.flag_break_continue = 0;
9731 /* else: e.g. "continue 2" should *break* once, *then* continue */
9732 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9733 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009734 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009735 break;
9736 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009737 /* "continue": simulate end of loop */
9738 rword = RES_DONE;
9739 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009740 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009741#endif
9742 if (G_flag_return_in_progress == 1) {
9743 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9744 break;
9745 }
9746 } else if (pi->followup == PIPE_BG) {
9747 /* What does bash do with attempts to background builtins? */
9748 /* even bash 3.2 doesn't do that well with nested bg:
9749 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9750 * I'm NOT treating inner &'s as jobs */
9751#if ENABLE_HUSH_JOB
9752 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009753 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009754#endif
9755 /* Last command's pid goes to $! */
9756 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009757 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009758 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009759/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009760 rcode = EXIT_SUCCESS;
9761 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009762 } else {
9763#if ENABLE_HUSH_JOB
9764 if (G.run_list_level == 1 && G_interactive_fd) {
9765 /* Waits for completion, then fg's main shell */
9766 rcode = checkjobs_and_fg_shell(pi);
9767 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009768 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009769 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009770#endif
9771 /* This one just waits for completion */
9772 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9773 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9774 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009775 G.last_exitcode = rcode;
9776 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009777#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9778 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9779#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009780 }
9781
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009782 /* Handle "set -e" */
9783 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9784 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9785 if (G.errexit_depth == 0)
9786 hush_exit(rcode);
9787 }
9788 G.errexit_depth = sv_errexit_depth;
9789
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009790 /* Analyze how result affects subsequent commands */
9791#if ENABLE_HUSH_IF
9792 if (rword == RES_IF || rword == RES_ELIF)
9793 cond_code = rcode;
9794#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009795 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009796 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009797 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009798#if ENABLE_HUSH_LOOPS
9799 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009800 if (pi->next
9801 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009802 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009803 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009804 if (rword == RES_WHILE) {
9805 if (rcode) {
9806 /* "while false; do...done" - exitcode 0 */
9807 G.last_exitcode = rcode = EXIT_SUCCESS;
9808 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009809 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009810 }
9811 }
9812 if (rword == RES_UNTIL) {
9813 if (!rcode) {
9814 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009815 break;
9816 }
9817 }
9818 }
9819#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009820 } /* for (pi) */
9821
9822#if ENABLE_HUSH_JOB
9823 G.run_list_level--;
9824#endif
9825#if ENABLE_HUSH_LOOPS
9826 if (loop_top)
9827 G.depth_of_loop--;
9828 free(for_list);
9829#endif
9830#if ENABLE_HUSH_CASE
9831 free(case_word);
9832#endif
9833 debug_leave();
9834 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9835 return rcode;
9836}
9837
9838/* Select which version we will use */
9839static int run_and_free_list(struct pipe *pi)
9840{
9841 int rcode = 0;
9842 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009843 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009844 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9845 rcode = run_list(pi);
9846 }
9847 /* free_pipe_list has the side effect of clearing memory.
9848 * In the long run that function can be merged with run_list,
9849 * but doing that now would hobble the debugging effort. */
9850 free_pipe_list(pi);
9851 debug_printf_exec("run_and_free_list return %d\n", rcode);
9852 return rcode;
9853}
9854
9855
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009856static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009857{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009858 sighandler_t old_handler;
9859 unsigned sig = 0;
9860 while ((mask >>= 1) != 0) {
9861 sig++;
9862 if (!(mask & 1))
9863 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009864 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009865 /* POSIX allows shell to re-enable SIGCHLD
9866 * even if it was SIG_IGN on entry.
9867 * Therefore we skip IGN check for it:
9868 */
9869 if (sig == SIGCHLD)
9870 continue;
Denys Vlasenko23bc5622020-02-18 16:46:01 +01009871 /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
9872 * Try:
9873 * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
9874 * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009875 */
Denys Vlasenko23bc5622020-02-18 16:46:01 +01009876 if (sig == SIGHUP && G_interactive_fd)
9877 continue;
9878 /* Unless one of the above signals, is it SIG_IGN? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009879 if (old_handler == SIG_IGN) {
9880 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009881 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009882#if ENABLE_HUSH_TRAP
9883 if (!G_traps)
9884 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9885 free(G_traps[sig]);
9886 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9887#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009888 }
9889 }
9890}
9891
9892/* Called a few times only (or even once if "sh -c") */
9893static void install_special_sighandlers(void)
9894{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009895 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009896
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009897 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009898 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009899 if (G_interactive_fd) {
9900 mask |= SPECIAL_INTERACTIVE_SIGS;
9901 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009902 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009903 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009904 /* Careful, do not re-install handlers we already installed */
9905 if (G.special_sig_mask != mask) {
9906 unsigned diff = mask & ~G.special_sig_mask;
9907 G.special_sig_mask = mask;
9908 install_sighandlers(diff);
9909 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009910}
9911
9912#if ENABLE_HUSH_JOB
9913/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009914/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009915static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009916{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009917 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009918
9919 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009920 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009921 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9922 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009923 + (1 << SIGBUS ) * HUSH_DEBUG
9924 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009925 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009926 + (1 << SIGABRT)
9927 /* bash 3.2 seems to handle these just like 'fatal' ones */
9928 + (1 << SIGPIPE)
9929 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009930 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009931 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009932 * we never want to restore pgrp on exit, and this fn is not called
9933 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009934 /*+ (1 << SIGHUP )*/
9935 /*+ (1 << SIGTERM)*/
9936 /*+ (1 << SIGINT )*/
9937 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009938 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009939
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009940 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009941}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009942#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009943
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009944static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009945{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009946 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009947 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009948 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009949 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009950 break;
9951 case 'x':
9952 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009953 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 +01009954 break;
Denys Vlasenko18a90ec2019-09-05 14:07:14 +02009955 case 'e':
9956 G.o_opt[OPT_O_ERREXIT] = state;
9957 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009958 case 'o':
9959 if (!o_opt) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +02009960 /* "set -o" or "set +o" without parameter.
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009961 * in bash, set -o produces this output:
9962 * pipefail off
9963 * and set +o:
9964 * set +o pipefail
9965 * We always use the second form.
9966 */
9967 const char *p = o_opt_strings;
9968 idx = 0;
9969 while (*p) {
9970 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9971 idx++;
9972 p += strlen(p) + 1;
9973 }
9974 break;
9975 }
9976 idx = index_in_strings(o_opt_strings, o_opt);
9977 if (idx >= 0) {
9978 G.o_opt[idx] = state;
9979 break;
9980 }
Denys Vlasenko18a90ec2019-09-05 14:07:14 +02009981 /* fall through to error */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009982 default:
9983 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009984 }
9985 return EXIT_SUCCESS;
9986}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009987
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009988int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009989int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009990{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009991 enum {
9992 OPT_login = (1 << 0),
9993 };
9994 unsigned flags;
Denys Vlasenko63139b52020-12-13 22:00:56 +01009995#if !BB_MMU
9996 unsigned builtin_argc = 0;
9997#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009998 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009999 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010000 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +000010001
Denis Vlasenko574f2f42008-02-27 18:41:59 +000010002 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +020010003 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010004 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010005#if ENABLE_HUSH_TRAP
10006# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010007 G.return_exitcode = -1;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010008# endif
10009 G.pre_trap_exitcode = -1;
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010010#endif
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010011
Denys Vlasenko10c01312011-05-11 11:49:21 +020010012#if ENABLE_HUSH_FAST
10013 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
10014#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010015#if !BB_MMU
10016 G.argv0_for_re_execing = argv[0];
10017#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010018
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010019 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010020 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
10021 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010022 shell_ver = xzalloc(sizeof(*shell_ver));
10023 shell_ver->flg_export = 1;
10024 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +020010025 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +020010026 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010027 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010028
Denys Vlasenko605067b2010-09-06 12:10:51 +020010029 /* Create shell local variables from the values
10030 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010031 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010032 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010033 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010034 if (e) while (*e) {
10035 char *value = strchr(*e, '=');
10036 if (value) { /* paranoia */
10037 cur_var->next = xzalloc(sizeof(*cur_var));
10038 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +000010039 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010040 cur_var->max_len = strlen(*e);
10041 cur_var->flg_export = 1;
10042 }
10043 e++;
10044 }
Denys Vlasenko605067b2010-09-06 12:10:51 +020010045 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010046 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
10047 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +020010048
10049 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010050 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010051
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010052#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010053 /* Set (but not export) HOSTNAME unless already set */
10054 if (!get_local_var_value("HOSTNAME")) {
10055 struct utsname uts;
10056 uname(&uts);
10057 set_local_var_from_halves("HOSTNAME", uts.nodename);
10058 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +020010059#endif
10060 /* IFS is not inherited from the parent environment */
10061 set_local_var_from_halves("IFS", defifs);
10062
Denys Vlasenkoef8985c2019-05-19 16:29:09 +020010063 if (!get_local_var_value("PATH"))
10064 set_local_var_from_halves("PATH", bb_default_root_path);
10065
Denys Vlasenko0c360192019-05-19 15:37:50 +020010066 /* PS1/PS2 are set later, if we determine that we are interactive */
10067
Denys Vlasenko6db47842009-09-05 20:15:17 +020010068 /* bash also exports SHLVL and _,
10069 * and sets (but doesn't export) the following variables:
10070 * BASH=/bin/bash
10071 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
10072 * BASH_VERSION='3.2.0(1)-release'
10073 * HOSTTYPE=i386
10074 * MACHTYPE=i386-pc-linux-gnu
10075 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +020010076 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +020010077 * EUID=<NNNNN>
10078 * UID=<NNNNN>
10079 * GROUPS=()
10080 * LINES=<NNN>
10081 * COLUMNS=<NNN>
10082 * BASH_ARGC=()
10083 * BASH_ARGV=()
10084 * BASH_LINENO=()
10085 * BASH_SOURCE=()
10086 * DIRSTACK=()
10087 * PIPESTATUS=([0]="0")
10088 * HISTFILE=/<xxx>/.bash_history
10089 * HISTFILESIZE=500
10090 * HISTSIZE=500
10091 * MAILCHECK=60
10092 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
10093 * SHELL=/bin/bash
10094 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
10095 * TERM=dumb
10096 * OPTERR=1
10097 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +020010098 * PS4='+ '
10099 */
10100
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010101#if NUM_SCRIPTS > 0
10102 if (argc < 0) {
10103 char *script = get_script_content(-argc - 1);
10104 G.global_argv = argv;
10105 G.global_argc = string_array_len(argv);
10106 G.root_pid = getpid();
10107 G.root_ppid = getppid();
10108 //install_special_sighandlers(); - needed?
10109 parse_and_run_string(script);
10110 goto final_return;
10111 }
10112#endif
10113
Eric Andersen94ac2442001-05-22 19:05:18 +000010114 /* Initialize some more globals to non-zero values */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010115 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +000010116
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010117 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010118 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010119 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010120 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010121 * in order to intercept (more) signals.
10122 */
10123
10124 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010125 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010126 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010127 while (1) {
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010128 int opt = getopt(argc, argv, "+cexinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010129#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +000010130 "<:$:R:V:"
10131# if ENABLE_HUSH_FUNCTIONS
10132 "F:"
10133# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010134#endif
10135 );
10136 if (opt <= 0)
10137 break;
Eric Andersen25f27032001-04-26 23:22:31 +000010138 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010139 case 'c':
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010140 /* Note: -c is not a param with option!
10141 * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010142 */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010143 G.opt_c = 1;
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010144 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010145 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010146 /* Well, we cannot just declare interactiveness,
10147 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010148 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010149 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010150 case 's':
Denys Vlasenkof3634582019-06-03 12:21:04 +020010151 G.opt_s = 1;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010152 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010153 case 'l':
10154 flags |= OPT_login;
10155 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010156#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010157 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010158 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010159 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010160 case '$': {
10161 unsigned long long empty_trap_mask;
10162
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010163 G.root_pid = bb_strtou(optarg, &optarg, 16);
10164 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010165 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10166 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010167 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10168 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010169 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010170 optarg++;
10171 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010172 optarg++;
10173 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10174 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010175 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010176 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010177# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010178 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010179 for (sig = 1; sig < NSIG; sig++) {
10180 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010181 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010182 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010183 }
10184 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010185# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010186 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010187# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010188 optarg++;
10189 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010190# endif
Denys Vlasenko49142d42020-12-13 18:44:07 +010010191 /* Suppress "killed by signal" message, -$ hack is used
10192 * for subshells: echo `sh -c 'kill -9 $$'`
10193 * should be silent.
10194 */
10195 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010196# if ENABLE_HUSH_FUNCTIONS
10197 /* nommu uses re-exec trick for "... | func | ...",
10198 * should allow "return".
10199 * This accidentally allows returns in subshells.
10200 */
10201 G_flag_return_in_progress = -1;
10202# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010203 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010204 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010205 case 'R':
10206 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010207 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010208 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010209# if ENABLE_HUSH_FUNCTIONS
10210 case 'F': {
10211 struct function *funcp = new_function(optarg);
10212 /* funcp->name is already set to optarg */
10213 /* funcp->body is set to NULL. It's a special case. */
10214 funcp->body_as_string = argv[optind];
10215 optind++;
10216 break;
10217 }
10218# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010219#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010220 case 'n':
10221 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +020010222 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010223 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010224 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010225 default:
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010226 bb_show_usage();
Eric Andersen25f27032001-04-26 23:22:31 +000010227 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010228 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010229
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010230 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10231 G.global_argc = argc - (optind - 1);
10232 G.global_argv = argv + (optind - 1);
10233 G.global_argv[0] = argv[0];
10234
Denys Vlasenkodea47882009-10-09 15:40:49 +020010235 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010236 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +020010237 G.root_ppid = getppid();
10238 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010239
10240 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010241 if (flags & OPT_login) {
Denys Vlasenko63139b52020-12-13 22:00:56 +010010242 const char *hp = NULL;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010243 HFILE *input;
Denys Vlasenko63139b52020-12-13 22:00:56 +010010244
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010245 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010246 input = hfopen("/etc/profile");
Denys Vlasenko63139b52020-12-13 22:00:56 +010010247 run_profile:
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010248 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010249 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010250 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010251 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010252 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010253 /* bash: after sourcing /etc/profile,
10254 * tries to source (in the given order):
10255 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010256 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010257 * bash also sources ~/.bash_logout on exit.
10258 * If called as sh, skips .bash_XXX files.
10259 */
Denys Vlasenko63139b52020-12-13 22:00:56 +010010260 if (!hp) { /* unless we looped on the "goto" already */
10261 hp = get_local_var_value("HOME");
10262 if (hp && hp[0]) {
10263 debug_printf("sourcing ~/.profile\n");
10264 hp = concat_path_file(hp, ".profile");
10265 input = hfopen(hp);
10266 free((char*)hp);
10267 goto run_profile;
10268 }
10269 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010270 }
10271
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010272 /* -c takes effect *after* -l */
10273 if (G.opt_c) {
10274 /* Possibilities:
10275 * sh ... -c 'script'
10276 * sh ... -c 'script' ARG0 [ARG1...]
10277 * On NOMMU, if builtin_argc != 0,
10278 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
10279 * "" needs to be replaced with NULL
10280 * and BARGV vector fed to builtin function.
10281 * Note: the form without ARG0 never happens:
10282 * sh ... -c 'builtin' BARGV... ""
10283 */
10284 char *script;
10285
10286 install_special_sighandlers();
10287
10288 G.global_argc--;
10289 G.global_argv++;
Denys Vlasenko49142d42020-12-13 18:44:07 +010010290#if !BB_MMU
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010291 if (builtin_argc) {
10292 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10293 const struct built_in_command *x;
10294 x = find_builtin(G.global_argv[0]);
10295 if (x) { /* paranoia */
10296 argv = G.global_argv;
10297 G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
10298 G.global_argv += builtin_argc + 1;
10299 G.global_argv[-1] = NULL; /* replace "" */
10300 G.last_exitcode = x->b_function(argv);
10301 }
10302 goto final_return;
10303 }
Denys Vlasenko49142d42020-12-13 18:44:07 +010010304#endif
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010305
10306 script = G.global_argv[0];
10307 if (!script)
10308 bb_error_msg_and_die(bb_msg_requires_arg, "-c");
10309 if (!G.global_argv[1]) {
10310 /* -c 'script' (no params): prevent empty $0 */
10311 G.global_argv[0] = argv[0];
10312 } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
10313 G.global_argc--;
10314 G.global_argv++;
10315 }
10316 parse_and_run_string(script);
10317 goto final_return;
10318 }
10319
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010320 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010321 if (!G.opt_s && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010322 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010323 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010324 * "bash <script>" (which is never interactive (unless -i?))
10325 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010326 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010327 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010328 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010329 G.global_argc--;
10330 G.global_argv++;
10331 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010332 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010333 input = hfopen(G.global_argv[0]);
10334 if (!input) {
10335 bb_simple_perror_msg_and_die(G.global_argv[0]);
10336 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010337 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010338 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010339 parse_and_run_file(input);
10340#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010341 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010342#endif
10343 goto final_return;
10344 }
Denys Vlasenkof3634582019-06-03 12:21:04 +020010345 /* "implicit" -s: bare interactive hush shows 's' in $- */
Denys Vlasenkod8740b22019-05-19 19:11:21 +020010346 G.opt_s = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010347
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010348 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010349 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010350 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010351
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010352 /* A shell is interactive if the '-i' flag was given,
10353 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010354 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010355 * no arguments remaining or the -s flag given
10356 * standard input is a terminal
10357 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010358 * Refer to Posix.2, the description of the 'sh' utility.
10359 */
10360#if ENABLE_HUSH_JOB
10361 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010362 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10363 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10364 if (G_saved_tty_pgrp < 0)
10365 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010366
10367 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010368 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010369 if (G_interactive_fd < 0) {
10370 /* try to dup to any fd */
10371 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010372 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010373 /* give up */
10374 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010375 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010376 }
10377 }
Eric Andersen25f27032001-04-26 23:22:31 +000010378 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010379 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010380 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010381 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010382
Mike Frysinger38478a62009-05-20 04:48:06 -040010383 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010384 /* If we were run as 'hush &', sleep until we are
10385 * in the foreground (tty pgrp == our pgrp).
10386 * If we get started under a job aware app (like bash),
10387 * make sure we are now in charge so we don't fight over
10388 * who gets the foreground */
10389 while (1) {
10390 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010391 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10392 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010393 break;
10394 /* send TTIN to ourself (should stop us) */
10395 kill(- shell_pgrp, SIGTTIN);
10396 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010397 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010398
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010399 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010400 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010401
Mike Frysinger38478a62009-05-20 04:48:06 -040010402 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010403 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010404 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010405 /* Put ourselves in our own process group
10406 * (bash, too, does this only if ctty is available) */
10407 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10408 /* Grab control of the terminal */
10409 tcsetpgrp(G_interactive_fd, getpid());
10410 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010411 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010412
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010413# if ENABLE_FEATURE_EDITING
10414 G.line_input_state = new_line_input_t(FOR_SHELL);
Ron Yorston9e2a5662020-01-21 16:01:58 +000010415# if EDITING_HAS_get_exe_name
10416 G.line_input_state->get_exe_name = get_builtin_name;
10417# endif
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010418# endif
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010419# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10420 {
10421 const char *hp = get_local_var_value("HISTFILE");
10422 if (!hp) {
10423 hp = get_local_var_value("HOME");
10424 if (hp)
10425 hp = concat_path_file(hp, ".hush_history");
10426 } else {
10427 hp = xstrdup(hp);
10428 }
10429 if (hp) {
10430 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010431 //set_local_var(xasprintf("HISTFILE=%s", ...));
10432 }
10433# if ENABLE_FEATURE_SH_HISTFILESIZE
10434 hp = get_local_var_value("HISTFILESIZE");
10435 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10436# endif
10437 }
10438# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010439 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010440 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010441 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010442#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010443 /* No job control compiled in, only prompt/line editing */
10444 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010445 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010446 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010447 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010448 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010449 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010450 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010451 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010452 }
10453 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010454 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010455 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010456 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010457 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010458#else
10459 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010460 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010461#endif
10462 /* bash:
10463 * if interactive but not a login shell, sources ~/.bashrc
10464 * (--norc turns this off, --rcfile <file> overrides)
10465 */
10466
Denys Vlasenko0c360192019-05-19 15:37:50 +020010467 if (G_interactive_fd) {
10468#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
10469 /* Set (but not export) PS1/2 unless already set */
10470 if (!get_local_var_value("PS1"))
10471 set_local_var_from_halves("PS1", "\\w \\$ ");
10472 if (!get_local_var_value("PS2"))
10473 set_local_var_from_halves("PS2", "> ");
10474#endif
10475 if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
10476 /* note: ash and hush share this string */
10477 printf("\n\n%s %s\n"
10478 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10479 "\n",
10480 bb_banner,
10481 "hush - the humble shell"
10482 );
10483 }
Mike Frysingerb2705e12009-03-23 08:44:02 +000010484 }
10485
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010486 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010487
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010488 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010489 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010490}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010491
10492
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010493/*
10494 * Built-ins
10495 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010496static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010497{
10498 return 0;
10499}
10500
Denys Vlasenko265062d2017-01-10 15:13:30 +010010501#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +020010502static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010503{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010504 int argc = string_array_len(argv);
10505 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010506}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010507#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010508#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010509static int FAST_FUNC builtin_test(char **argv)
10510{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010511 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010512}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010513#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010514#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010515static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010516{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010517 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010518}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010519#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010520#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010521static int FAST_FUNC builtin_printf(char **argv)
10522{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010523 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010524}
10525#endif
10526
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010527#if ENABLE_HUSH_HELP
10528static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10529{
10530 const struct built_in_command *x;
10531
10532 printf(
10533 "Built-in commands:\n"
10534 "------------------\n");
10535 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10536 if (x->b_descr)
10537 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10538 }
10539 return EXIT_SUCCESS;
10540}
10541#endif
10542
10543#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10544static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10545{
Ron Yorston9f3b4102019-12-16 09:31:10 +000010546 show_history(G.line_input_state);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010547 return EXIT_SUCCESS;
10548}
10549#endif
10550
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010551static char **skip_dash_dash(char **argv)
10552{
10553 argv++;
10554 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10555 argv++;
10556 return argv;
10557}
10558
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010559static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010560{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010561 const char *newdir;
10562
10563 argv = skip_dash_dash(argv);
10564 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010565 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010566 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010567 * bash says "bash: cd: HOME not set" and does nothing
10568 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010569 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010570 const char *home = get_local_var_value("HOME");
10571 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010572 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010573 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010574 /* Mimic bash message exactly */
10575 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010576 return EXIT_FAILURE;
10577 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010578 /* Read current dir (get_cwd(1) is inside) and set PWD.
10579 * Note: do not enforce exporting. If PWD was unset or unexported,
10580 * set it again, but do not export. bash does the same.
10581 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010582 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010583 return EXIT_SUCCESS;
10584}
10585
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010586static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10587{
10588 puts(get_cwd(0));
10589 return EXIT_SUCCESS;
10590}
10591
10592static int FAST_FUNC builtin_eval(char **argv)
10593{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010594 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010595
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010596 if (!argv[0])
10597 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010598
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010599 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010600 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010601 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010602 /* bash:
10603 * eval "echo Hi; done" ("done" is syntax error):
10604 * "echo Hi" will not execute too.
10605 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010606 parse_and_run_string(argv[0]);
10607 } else {
10608 /* "The eval utility shall construct a command by
10609 * concatenating arguments together, separating
10610 * each with a <space> character."
10611 */
10612 char *str, *p;
10613 unsigned len = 0;
10614 char **pp = argv;
10615 do
10616 len += strlen(*pp) + 1;
10617 while (*++pp);
10618 str = p = xmalloc(len);
10619 pp = argv;
10620 for (;;) {
10621 p = stpcpy(p, *pp);
10622 pp++;
10623 if (!*pp)
10624 break;
10625 *p++ = ' ';
10626 }
10627 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010628 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010629 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010630 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010631 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010632 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010633}
10634
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010635static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010636{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010637 argv = skip_dash_dash(argv);
10638 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010639 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010640
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010641 /* Careful: we can end up here after [v]fork. Do not restore
10642 * tty pgrp then, only top-level shell process does that */
10643 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10644 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10645
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010646 /* Saved-redirect fds, script fds and G_interactive_fd are still
10647 * open here. However, they are all CLOEXEC, and execv below
10648 * closes them. Try interactive "exec ls -l /proc/self/fd",
10649 * it should show no extra open fds in the "ls" process.
10650 * If we'd try to run builtins/NOEXECs, this would need improving.
10651 */
10652 //close_saved_fds_and_FILE_fds();
10653
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010654 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010655 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010656 * and tcsetpgrp, and this is inherently racy.
10657 */
10658 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010659}
10660
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010661static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010662{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010663 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010664
10665 /* interactive bash:
10666 * # trap "echo EEE" EXIT
10667 * # exit
10668 * exit
10669 * There are stopped jobs.
10670 * (if there are _stopped_ jobs, running ones don't count)
10671 * # exit
10672 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010673 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010674 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010675 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010676 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010677
10678 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010679 argv = skip_dash_dash(argv);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010680 if (argv[0] == NULL) {
10681#if ENABLE_HUSH_TRAP
10682 if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
10683 hush_exit(G.pre_trap_exitcode);
10684#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010685 hush_exit(G.last_exitcode);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010686 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010687 /* mimic bash: exit 123abc == exit 255 + error msg */
10688 xfunc_error_retval = 255;
10689 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010690 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010691}
10692
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010693#if ENABLE_HUSH_TYPE
10694/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10695static int FAST_FUNC builtin_type(char **argv)
10696{
10697 int ret = EXIT_SUCCESS;
10698
10699 while (*++argv) {
10700 const char *type;
10701 char *path = NULL;
10702
10703 if (0) {} /* make conditional compile easier below */
10704 /*else if (find_alias(*argv))
10705 type = "an alias";*/
Denys Vlasenko259747c2019-11-28 10:28:14 +010010706# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010707 else if (find_function(*argv))
10708 type = "a function";
Denys Vlasenko259747c2019-11-28 10:28:14 +010010709# endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010710 else if (find_builtin(*argv))
10711 type = "a shell builtin";
10712 else if ((path = find_in_path(*argv)) != NULL)
10713 type = path;
10714 else {
10715 bb_error_msg("type: %s: not found", *argv);
10716 ret = EXIT_FAILURE;
10717 continue;
10718 }
10719
10720 printf("%s is %s\n", *argv, type);
10721 free(path);
10722 }
10723
10724 return ret;
10725}
10726#endif
10727
10728#if ENABLE_HUSH_READ
10729/* Interruptibility of read builtin in bash
10730 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10731 *
10732 * Empty trap makes read ignore corresponding signal, for any signal.
10733 *
10734 * SIGINT:
10735 * - terminates non-interactive shell;
10736 * - interrupts read in interactive shell;
10737 * if it has non-empty trap:
10738 * - executes trap and returns to command prompt in interactive shell;
10739 * - executes trap and returns to read in non-interactive shell;
10740 * SIGTERM:
10741 * - is ignored (does not interrupt) read in interactive shell;
10742 * - terminates non-interactive shell;
10743 * if it has non-empty trap:
10744 * - executes trap and returns to read;
10745 * SIGHUP:
10746 * - terminates shell (regardless of interactivity);
10747 * if it has non-empty trap:
10748 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010749 * SIGCHLD from children:
10750 * - does not interrupt read regardless of interactivity:
10751 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010752 */
10753static int FAST_FUNC builtin_read(char **argv)
10754{
10755 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010756 struct builtin_read_params params;
10757
10758 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010759
10760 /* "!": do not abort on errors.
10761 * Option string must start with "sr" to match BUILTIN_READ_xxx
10762 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010763 params.read_flags = getopt32(argv,
Denys Vlasenko259747c2019-11-28 10:28:14 +010010764# if BASH_READ_D
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010765 "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko259747c2019-11-28 10:28:14 +010010766# else
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010767 "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko259747c2019-11-28 10:28:14 +010010768# endif
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010769 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010770 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010771 return EXIT_FAILURE;
10772 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010773 params.argv = argv;
10774 params.setvar = set_local_var_from_halves;
10775 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010776
10777 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010778 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010779
10780 if ((uintptr_t)r == 1 && errno == EINTR) {
10781 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010782 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010783 goto again;
10784 }
10785
10786 if ((uintptr_t)r > 1) {
James Byrne69374872019-07-02 11:35:03 +020010787 bb_simple_error_msg(r);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010788 r = (char*)(uintptr_t)1;
10789 }
10790
10791 return (uintptr_t)r;
10792}
10793#endif
10794
10795#if ENABLE_HUSH_UMASK
10796static int FAST_FUNC builtin_umask(char **argv)
10797{
10798 int rc;
10799 mode_t mask;
10800
10801 rc = 1;
10802 mask = umask(0);
10803 argv = skip_dash_dash(argv);
10804 if (argv[0]) {
10805 mode_t old_mask = mask;
10806
10807 /* numeric umasks are taken as-is */
10808 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10809 if (!isdigit(argv[0][0]))
10810 mask ^= 0777;
10811 mask = bb_parse_mode(argv[0], mask);
10812 if (!isdigit(argv[0][0]))
10813 mask ^= 0777;
10814 if ((unsigned)mask > 0777) {
10815 mask = old_mask;
10816 /* bash messages:
10817 * bash: umask: 'q': invalid symbolic mode operator
10818 * bash: umask: 999: octal number out of range
10819 */
10820 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10821 rc = 0;
10822 }
10823 } else {
10824 /* Mimic bash */
10825 printf("%04o\n", (unsigned) mask);
10826 /* fall through and restore mask which we set to 0 */
10827 }
10828 umask(mask);
10829
10830 return !rc; /* rc != 0 - success */
10831}
10832#endif
10833
Denys Vlasenko41ade052017-01-08 18:56:24 +010010834#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010835static void print_escaped(const char *s)
10836{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010837 if (*s == '\'')
10838 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010839 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010840 const char *p = strchrnul(s, '\'');
10841 /* print 'xxxx', possibly just '' */
10842 printf("'%.*s'", (int)(p - s), s);
10843 if (*p == '\0')
10844 break;
10845 s = p;
10846 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010847 /* s points to '; print "'''...'''" */
10848 putchar('"');
10849 do putchar('\''); while (*++s == '\'');
10850 putchar('"');
10851 } while (*s);
10852}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010853#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010854
Denys Vlasenko1e660422017-07-17 21:10:50 +020010855#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010856static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010857{
10858 do {
10859 char *name = *argv;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010860 const char *name_end = endofname(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010861
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010862 if (*name_end == '\0') {
10863 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010864
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010865 vpp = get_ptr_to_local_var(name, name_end - name);
10866 var = vpp ? *vpp : NULL;
10867
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010868 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010869 /* export -n NAME (without =VALUE) */
10870 if (var) {
10871 var->flg_export = 0;
10872 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10873 unsetenv(name);
10874 } /* else: export -n NOT_EXISTING_VAR: no-op */
10875 continue;
10876 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010877 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010878 /* export NAME (without =VALUE) */
10879 if (var) {
10880 var->flg_export = 1;
10881 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10882 putenv(var->varstr);
10883 continue;
10884 }
10885 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010886 if (flags & SETFLAG_MAKE_RO) {
10887 /* readonly NAME (without =VALUE) */
10888 if (var) {
10889 var->flg_read_only = 1;
10890 continue;
10891 }
10892 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010893# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010894 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010895 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010896 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10897 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010898 /* "local x=abc; ...; local x" - ignore second local decl */
10899 continue;
10900 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010901 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010902# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010903 /* Exporting non-existing variable.
10904 * bash does not put it in environment,
10905 * but remembers that it is exported,
10906 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010907 * We just set it to "" and export.
10908 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010909 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010910 * bash sets the value to "".
10911 */
10912 /* Or, it's "readonly NAME" (without =VALUE).
10913 * bash remembers NAME and disallows its creation
10914 * in the future.
10915 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010916 name = xasprintf("%s=", name);
10917 } else {
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010918 if (*name_end != '=') {
10919 bb_error_msg("'%s': bad variable name", name);
10920 /* do not parse following argv[]s: */
10921 return 1;
10922 }
Denys Vlasenko295fef82009-06-03 12:47:26 +020010923 /* (Un)exporting/making local NAME=VALUE */
10924 name = xstrdup(name);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010925 /* Testcase: export PS1='\w \$ ' */
10926 unbackslash(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010927 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010928 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010929 if (set_local_var(name, flags))
10930 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010931 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010932 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010933}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010934#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010935
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010936#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010937static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010938{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010939 unsigned opt_unexport;
10940
Denys Vlasenko259747c2019-11-28 10:28:14 +010010941# if ENABLE_HUSH_EXPORT_N
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010942 /* "!": do not abort on errors */
10943 opt_unexport = getopt32(argv, "!n");
10944 if (opt_unexport == (uint32_t)-1)
10945 return EXIT_FAILURE;
10946 argv += optind;
Denys Vlasenko259747c2019-11-28 10:28:14 +010010947# else
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010948 opt_unexport = 0;
10949 argv++;
Denys Vlasenko259747c2019-11-28 10:28:14 +010010950# endif
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010951
10952 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010953 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010954 if (e) {
10955 while (*e) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010010956# if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010957 puts(*e++);
Denys Vlasenko259747c2019-11-28 10:28:14 +010010958# else
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010959 /* ash emits: export VAR='VAL'
10960 * bash: declare -x VAR="VAL"
10961 * we follow ash example */
10962 const char *s = *e++;
10963 const char *p = strchr(s, '=');
10964
10965 if (!p) /* wtf? take next variable */
10966 continue;
10967 /* export var= */
10968 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010969 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010970 putchar('\n');
Denys Vlasenko259747c2019-11-28 10:28:14 +010010971# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010972 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010973 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010974 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010975 return EXIT_SUCCESS;
10976 }
10977
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010978 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010979}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010980#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010981
Denys Vlasenko295fef82009-06-03 12:47:26 +020010982#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010983static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010984{
10985 if (G.func_nest_level == 0) {
10986 bb_error_msg("%s: not in a function", argv[0]);
10987 return EXIT_FAILURE; /* bash compat */
10988 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010989 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010990 /* Since all builtins run in a nested variable level,
10991 * need to use level - 1 here. Or else the variable will be removed at once
10992 * after builtin returns.
10993 */
10994 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010995}
10996#endif
10997
Denys Vlasenko1e660422017-07-17 21:10:50 +020010998#if ENABLE_HUSH_READONLY
10999static int FAST_FUNC builtin_readonly(char **argv)
11000{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011001 argv++;
11002 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020011003 /* bash: readonly [-p]: list all readonly VARs
11004 * (-p has no effect in bash)
11005 */
11006 struct variable *e;
11007 for (e = G.top_var; e; e = e->next) {
11008 if (e->flg_read_only) {
11009//TODO: quote value: readonly VAR='VAL'
11010 printf("readonly %s\n", e->varstr);
11011 }
11012 }
11013 return EXIT_SUCCESS;
11014 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011015 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020011016}
11017#endif
11018
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011019#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011020/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
11021static int FAST_FUNC builtin_unset(char **argv)
11022{
11023 int ret;
11024 unsigned opts;
11025
11026 /* "!": do not abort on errors */
11027 /* "+": stop at 1st non-option */
11028 opts = getopt32(argv, "!+vf");
11029 if (opts == (unsigned)-1)
11030 return EXIT_FAILURE;
11031 if (opts == 3) {
James Byrne69374872019-07-02 11:35:03 +020011032 bb_simple_error_msg("unset: -v and -f are exclusive");
Denys Vlasenko61508d92016-10-02 21:12:02 +020011033 return EXIT_FAILURE;
11034 }
11035 argv += optind;
11036
11037 ret = EXIT_SUCCESS;
11038 while (*argv) {
11039 if (!(opts & 2)) { /* not -f */
11040 if (unset_local_var(*argv)) {
11041 /* unset <nonexistent_var> doesn't fail.
11042 * Error is when one tries to unset RO var.
11043 * Message was printed by unset_local_var. */
11044 ret = EXIT_FAILURE;
11045 }
11046 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011047# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020011048 else {
11049 unset_func(*argv);
11050 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011051# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011052 argv++;
11053 }
11054 return ret;
11055}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011056#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011057
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011058#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011059/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
11060 * built-in 'set' handler
11061 * SUSv3 says:
11062 * set [-abCefhmnuvx] [-o option] [argument...]
11063 * set [+abCefhmnuvx] [+o option] [argument...]
11064 * set -- [argument...]
11065 * set -o
11066 * set +o
11067 * Implementations shall support the options in both their hyphen and
11068 * plus-sign forms. These options can also be specified as options to sh.
11069 * Examples:
11070 * Write out all variables and their values: set
11071 * Set $1, $2, and $3 and set "$#" to 3: set c a b
11072 * Turn on the -x and -v options: set -xv
11073 * Unset all positional parameters: set --
11074 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
11075 * Set the positional parameters to the expansion of x, even if x expands
11076 * with a leading '-' or '+': set -- $x
11077 *
11078 * So far, we only support "set -- [argument...]" and some of the short names.
11079 */
11080static int FAST_FUNC builtin_set(char **argv)
11081{
11082 int n;
11083 char **pp, **g_argv;
11084 char *arg = *++argv;
11085
11086 if (arg == NULL) {
11087 struct variable *e;
11088 for (e = G.top_var; e; e = e->next)
11089 puts(e->varstr);
11090 return EXIT_SUCCESS;
11091 }
11092
11093 do {
11094 if (strcmp(arg, "--") == 0) {
11095 ++argv;
11096 goto set_argv;
11097 }
11098 if (arg[0] != '+' && arg[0] != '-')
11099 break;
11100 for (n = 1; arg[n]; ++n) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020011101 if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
11102 bb_error_msg("%s: %s: invalid option", "set", arg);
11103 return EXIT_FAILURE;
11104 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011105 if (arg[n] == 'o' && argv[1])
11106 argv++;
11107 }
11108 } while ((arg = *++argv) != NULL);
11109 /* Now argv[0] is 1st argument */
11110
11111 if (arg == NULL)
11112 return EXIT_SUCCESS;
11113 set_argv:
11114
11115 /* NB: G.global_argv[0] ($0) is never freed/changed */
11116 g_argv = G.global_argv;
11117 if (G.global_args_malloced) {
11118 pp = g_argv;
11119 while (*++pp)
11120 free(*pp);
11121 g_argv[1] = NULL;
11122 } else {
11123 G.global_args_malloced = 1;
11124 pp = xzalloc(sizeof(pp[0]) * 2);
11125 pp[0] = g_argv[0]; /* retain $0 */
11126 g_argv = pp;
11127 }
11128 /* This realloc's G.global_argv */
11129 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
11130
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020011131 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020011132
11133 return EXIT_SUCCESS;
Denys Vlasenko61508d92016-10-02 21:12:02 +020011134}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011135#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011136
11137static int FAST_FUNC builtin_shift(char **argv)
11138{
11139 int n = 1;
11140 argv = skip_dash_dash(argv);
11141 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020011142 n = bb_strtou(argv[0], NULL, 10);
11143 if (errno || n < 0) {
11144 /* shared string with ash.c */
11145 bb_error_msg("Illegal number: %s", argv[0]);
11146 /*
11147 * ash aborts in this case.
11148 * bash prints error message and set $? to 1.
11149 * Interestingly, for "shift 99999" bash does not
11150 * print error message, but does set $? to 1
11151 * (and does no shifting at all).
11152 */
11153 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011154 }
11155 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010011156 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020011157 int m = 1;
11158 while (m <= n)
11159 free(G.global_argv[m++]);
11160 }
11161 G.global_argc -= n;
11162 memmove(&G.global_argv[1], &G.global_argv[n+1],
11163 G.global_argc * sizeof(G.global_argv[0]));
11164 return EXIT_SUCCESS;
11165 }
11166 return EXIT_FAILURE;
11167}
11168
Denys Vlasenko74d40582017-08-11 01:32:46 +020011169#if ENABLE_HUSH_GETOPTS
11170static int FAST_FUNC builtin_getopts(char **argv)
11171{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011172/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11173
Denys Vlasenko74d40582017-08-11 01:32:46 +020011174TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011175If a required argument is not found, and getopts is not silent,
11176a question mark (?) is placed in VAR, OPTARG is unset, and a
11177diagnostic message is printed. If getopts is silent, then a
11178colon (:) is placed in VAR and OPTARG is set to the option
11179character found.
11180
11181Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011182
11183"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011184*/
11185 char cbuf[2];
11186 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011187 int c, n, exitcode, my_opterr;
11188 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011189
11190 optstring = *++argv;
11191 if (!optstring || !(var = *++argv)) {
James Byrne69374872019-07-02 11:35:03 +020011192 bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
Denys Vlasenko74d40582017-08-11 01:32:46 +020011193 return EXIT_FAILURE;
11194 }
11195
Denys Vlasenko238ff982017-08-29 13:38:30 +020011196 if (argv[1])
11197 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11198 else
11199 argv = G.global_argv;
11200 cbuf[1] = '\0';
11201
11202 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011203 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011204 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011205 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011206 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011207 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011208
11209 /* getopts stops on first non-option. Add "+" to force that */
11210 /*if (optstring[0] != '+')*/ {
11211 char *s = alloca(strlen(optstring) + 2);
11212 sprintf(s, "+%s", optstring);
11213 optstring = s;
11214 }
11215
Denys Vlasenko238ff982017-08-29 13:38:30 +020011216 /* Naively, now we should just
11217 * cp = get_local_var_value("OPTIND");
11218 * optind = cp ? atoi(cp) : 0;
11219 * optarg = NULL;
11220 * opterr = my_opterr;
11221 * c = getopt(string_array_len(argv), argv, optstring);
11222 * and be done? Not so fast...
11223 * Unlike normal getopt() usage in C programs, here
11224 * each successive call will (usually) have the same argv[] CONTENTS,
11225 * but not the ADDRESSES. Worse yet, it's possible that between
11226 * invocations of "getopts", there will be calls to shell builtins
11227 * which use getopt() internally. Example:
11228 * while getopts "abc" RES -a -bc -abc de; do
11229 * unset -ff func
11230 * done
11231 * This would not work correctly: getopt() call inside "unset"
11232 * modifies internal libc state which is tracking position in
11233 * multi-option strings ("-abc"). At best, it can skip options
11234 * or return the same option infinitely. With glibc implementation
11235 * of getopt(), it would use outright invalid pointers and return
11236 * garbage even _without_ "unset" mangling internal state.
11237 *
11238 * We resort to resetting getopt() state and calling it N times,
11239 * until we get Nth result (or failure).
11240 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11241 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011242 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011243 count = 0;
11244 n = string_array_len(argv);
11245 do {
11246 optarg = NULL;
11247 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11248 c = getopt(n, argv, optstring);
11249 if (c < 0)
11250 break;
11251 count++;
11252 } while (count <= G.getopt_count);
11253
11254 /* Set OPTIND. Prevent resetting of the magic counter! */
11255 set_local_var_from_halves("OPTIND", utoa(optind));
11256 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011257 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011258
11259 /* Set OPTARG */
11260 /* Always set or unset, never left as-is, even on exit/error:
11261 * "If no option was found, or if the option that was found
11262 * does not have an option-argument, OPTARG shall be unset."
11263 */
11264 cp = optarg;
11265 if (c == '?') {
11266 /* If ":optstring" and unknown option is seen,
11267 * it is stored to OPTARG.
11268 */
11269 if (optstring[1] == ':') {
11270 cbuf[0] = optopt;
11271 cp = cbuf;
11272 }
11273 }
11274 if (cp)
11275 set_local_var_from_halves("OPTARG", cp);
11276 else
11277 unset_local_var("OPTARG");
11278
11279 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011280 exitcode = EXIT_SUCCESS;
11281 if (c < 0) { /* -1: end of options */
11282 exitcode = EXIT_FAILURE;
11283 c = '?';
11284 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011285
Denys Vlasenko238ff982017-08-29 13:38:30 +020011286 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011287 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011288 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011289
Denys Vlasenko74d40582017-08-11 01:32:46 +020011290 return exitcode;
11291}
11292#endif
11293
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011294static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011295{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011296 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011297 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011298 save_arg_t sv;
11299 char *args_need_save;
11300#if ENABLE_HUSH_FUNCTIONS
11301 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011302#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011303
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011304 argv = skip_dash_dash(argv);
11305 filename = argv[0];
11306 if (!filename) {
11307 /* bash says: "bash: .: filename argument required" */
11308 return 2; /* bash compat */
11309 }
11310 arg_path = NULL;
11311 if (!strchr(filename, '/')) {
11312 arg_path = find_in_path(filename);
11313 if (arg_path)
11314 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011315 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011316 errno = ENOENT;
11317 bb_simple_perror_msg(filename);
11318 return EXIT_FAILURE;
11319 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011320 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011321 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011322 free(arg_path);
11323 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011324 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011325 /* POSIX: non-interactive shell should abort here,
11326 * not merely fail. So far no one complained :)
11327 */
11328 return EXIT_FAILURE;
11329 }
11330
11331#if ENABLE_HUSH_FUNCTIONS
11332 sv_flg = G_flag_return_in_progress;
11333 /* "we are inside sourced file, ok to use return" */
11334 G_flag_return_in_progress = -1;
11335#endif
11336 args_need_save = argv[1]; /* used as a boolean variable */
11337 if (args_need_save)
11338 save_and_replace_G_args(&sv, argv);
11339
11340 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11341 G.last_exitcode = 0;
11342 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011343 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011344
11345 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11346 restore_G_args(&sv, argv);
11347#if ENABLE_HUSH_FUNCTIONS
11348 G_flag_return_in_progress = sv_flg;
11349#endif
11350
11351 return G.last_exitcode;
11352}
11353
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011354#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011355static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011356{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011357 int sig;
11358 char *new_cmd;
11359
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011360 if (!G_traps)
11361 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011362
11363 argv++;
11364 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011365 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011366 /* No args: print all trapped */
11367 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011368 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011369 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011370 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011371 /* note: bash adds "SIG", but only if invoked
11372 * as "bash". If called as "sh", or if set -o posix,
11373 * then it prints short signal names.
11374 * We are printing short names: */
11375 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011376 }
11377 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011378 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011379 return EXIT_SUCCESS;
11380 }
11381
11382 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011383 /* If first arg is a number: reset all specified signals */
11384 sig = bb_strtou(*argv, NULL, 10);
11385 if (errno == 0) {
11386 int ret;
11387 process_sig_list:
11388 ret = EXIT_SUCCESS;
11389 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011390 sighandler_t handler;
11391
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011392 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011393 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011394 ret = EXIT_FAILURE;
11395 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011396 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011397 continue;
11398 }
11399
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011400 free(G_traps[sig]);
11401 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011402
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011403 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011404 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011405
11406 /* There is no signal for 0 (EXIT) */
11407 if (sig == 0)
11408 continue;
11409
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011410 if (new_cmd)
11411 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11412 else
11413 /* We are removing trap handler */
11414 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011415 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011416 }
11417 return ret;
11418 }
11419
11420 if (!argv[1]) { /* no second arg */
James Byrne69374872019-07-02 11:35:03 +020011421 bb_simple_error_msg("trap: invalid arguments");
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011422 return EXIT_FAILURE;
11423 }
11424
11425 /* First arg is "-": reset all specified to default */
11426 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11427 /* Everything else: set arg as signal handler
11428 * (includes "" case, which ignores signal) */
11429 if (argv[0][0] == '-') {
11430 if (argv[0][1] == '\0') { /* "-" */
11431 /* new_cmd remains NULL: "reset these sigs" */
11432 goto reset_traps;
11433 }
11434 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11435 argv++;
11436 }
11437 /* else: "-something", no special meaning */
11438 }
11439 new_cmd = *argv;
11440 reset_traps:
11441 argv++;
11442 goto process_sig_list;
11443}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011444#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011445
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011446#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011447static struct pipe *parse_jobspec(const char *str)
11448{
11449 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011450 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011451
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011452 if (sscanf(str, "%%%u", &jobnum) != 1) {
11453 if (str[0] != '%'
11454 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11455 ) {
11456 bb_error_msg("bad argument '%s'", str);
11457 return NULL;
11458 }
11459 /* It is "%%", "%+" or "%" - current job */
11460 jobnum = G.last_jobid;
11461 if (jobnum == 0) {
James Byrne69374872019-07-02 11:35:03 +020011462 bb_simple_error_msg("no current job");
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011463 return NULL;
11464 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011465 }
11466 for (pi = G.job_list; pi; pi = pi->next) {
11467 if (pi->jobid == jobnum) {
11468 return pi;
11469 }
11470 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011471 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011472 return NULL;
11473}
11474
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011475static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11476{
11477 struct pipe *job;
11478 const char *status_string;
11479
11480 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11481 for (job = G.job_list; job; job = job->next) {
11482 if (job->alive_cmds == job->stopped_cmds)
11483 status_string = "Stopped";
11484 else
11485 status_string = "Running";
11486
11487 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11488 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011489
11490 clean_up_last_dead_job();
11491
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011492 return EXIT_SUCCESS;
11493}
11494
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011495/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011496static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011497{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011498 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011499 struct pipe *pi;
11500
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011501 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011502 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011503
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011504 /* If they gave us no args, assume they want the last backgrounded task */
11505 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011506 for (pi = G.job_list; pi; pi = pi->next) {
11507 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011508 goto found;
11509 }
11510 }
11511 bb_error_msg("%s: no current job", argv[0]);
11512 return EXIT_FAILURE;
11513 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011514
11515 pi = parse_jobspec(argv[1]);
11516 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011517 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011518 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011519 /* TODO: bash prints a string representation
11520 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011521 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011522 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011523 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011524 }
11525
11526 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011527 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11528 for (i = 0; i < pi->num_cmds; i++) {
11529 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011530 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011531 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011532
11533 i = kill(- pi->pgrp, SIGCONT);
11534 if (i < 0) {
11535 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011536 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011537 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011538 }
James Byrne69374872019-07-02 11:35:03 +020011539 bb_simple_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011540 }
11541
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011542 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011543 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011544 return checkjobs_and_fg_shell(pi);
11545 }
11546 return EXIT_SUCCESS;
11547}
11548#endif
11549
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011550#if ENABLE_HUSH_KILL
11551static int FAST_FUNC builtin_kill(char **argv)
11552{
11553 int ret = 0;
11554
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011555# if ENABLE_HUSH_JOB
11556 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11557 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011558
11559 do {
11560 struct pipe *pi;
11561 char *dst;
11562 int j, n;
11563
11564 if (argv[i][0] != '%')
11565 continue;
11566 /*
11567 * "kill %N" - job kill
11568 * Converting to pgrp / pid kill
11569 */
11570 pi = parse_jobspec(argv[i]);
11571 if (!pi) {
11572 /* Eat bad jobspec */
11573 j = i;
11574 do {
11575 j++;
11576 argv[j - 1] = argv[j];
11577 } while (argv[j]);
11578 ret = 1;
11579 i--;
11580 continue;
11581 }
11582 /*
11583 * In jobs started under job control, we signal
11584 * entire process group by kill -PGRP_ID.
11585 * This happens, f.e., in interactive shell.
11586 *
11587 * Otherwise, we signal each child via
11588 * kill PID1 PID2 PID3.
11589 * Testcases:
11590 * sh -c 'sleep 1|sleep 1 & kill %1'
11591 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11592 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11593 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011594 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011595 dst = alloca(n * sizeof(int)*4);
11596 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011597 if (G_interactive_fd)
11598 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011599 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011600 struct command *cmd = &pi->cmds[j];
11601 /* Skip exited members of the job */
11602 if (cmd->pid == 0)
11603 continue;
11604 /*
11605 * kill_main has matching code to expect
11606 * leading space. Needed to not confuse
11607 * negative pids with "kill -SIGNAL_NO" syntax
11608 */
11609 dst += sprintf(dst, " %u", (int)cmd->pid);
11610 }
11611 *dst = '\0';
11612 } while (argv[++i]);
11613 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011614# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011615
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011616 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011617 ret = run_applet_main(argv, kill_main);
11618 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011619 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011620 return ret;
11621}
11622#endif
11623
11624#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011625/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011626# if !ENABLE_HUSH_JOB
11627# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11628# endif
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011629static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011630{
11631 int ret = 0;
11632 for (;;) {
11633 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011634 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011635
Denys Vlasenko830ea352016-11-08 04:59:11 +010011636 if (!sigisemptyset(&G.pending_set))
11637 goto check_sig;
11638
Denys Vlasenko7e675362016-10-28 21:57:31 +020011639 /* waitpid is not interruptible by SA_RESTARTed
11640 * signals which we use. Thus, this ugly dance:
11641 */
11642
11643 /* Make sure possible SIGCHLD is stored in kernel's
11644 * pending signal mask before we call waitpid.
11645 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011646 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011647 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011648 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011649 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011650
11651 if (!sigisemptyset(&G.pending_set)) {
11652 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011653 goto restore;
11654 }
11655
11656 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011657/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011658 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011659 debug_printf_exec("checkjobs:%d\n", ret);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011660# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011661 if (waitfor_pipe) {
11662 int rcode = job_exited_or_stopped(waitfor_pipe);
11663 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11664 if (rcode >= 0) {
11665 ret = rcode;
11666 sigprocmask(SIG_SETMASK, &oldset, NULL);
11667 break;
11668 }
11669 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011670# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011671 /* if ECHILD, there are no children (ret is -1 or 0) */
11672 /* if ret == 0, no children changed state */
11673 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011674 if (errno == ECHILD || ret) {
11675 ret--;
11676 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011677 ret = 0;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011678# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011679 if (waitfor_pid == -1 && errno == ECHILD) {
11680 /* exitcode of "wait -n" with no children is 127, not 0 */
11681 ret = 127;
11682 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011683# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011684 sigprocmask(SIG_SETMASK, &oldset, NULL);
11685 break;
11686 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011687 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011688 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11689 /* Note: sigsuspend invokes signal handler */
11690 sigsuspend(&oldset);
Denys Vlasenko23bc5622020-02-18 16:46:01 +010011691 /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
11692 * to make sure SIGCHLD is not masked off?
11693 * It was reported that this:
11694 * fn() { : | return; }
11695 * shopt -s lastpipe
11696 * fn
11697 * exec hush SCRIPT
11698 * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
11699 * making "wait" commands in SCRIPT block forever.
11700 */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011701 restore:
11702 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011703 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011704 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011705 sig = check_and_run_traps();
11706 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011707 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011708 ret = 128 + sig;
11709 break;
11710 }
11711 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11712 }
11713 return ret;
11714}
11715
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011716static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011717{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011718 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011719 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011720
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011721 argv = skip_dash_dash(argv);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011722# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011723 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011724 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011725 /* (bash accepts "wait -n PID" too and ignores PID) */
11726 G.dead_job_exitcode = -1;
11727 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011728 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011729# endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011730 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011731 /* Don't care about wait results */
11732 /* Note 1: must wait until there are no more children */
11733 /* Note 2: must be interruptible */
11734 /* Examples:
11735 * $ sleep 3 & sleep 6 & wait
11736 * [1] 30934 sleep 3
11737 * [2] 30935 sleep 6
11738 * [1] Done sleep 3
11739 * [2] Done sleep 6
11740 * $ sleep 3 & sleep 6 & wait
11741 * [1] 30936 sleep 3
11742 * [2] 30937 sleep 6
11743 * [1] Done sleep 3
11744 * ^C <-- after ~4 sec from keyboard
11745 * $
11746 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011747 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011748 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011749
Denys Vlasenko7e675362016-10-28 21:57:31 +020011750 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011751 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011752 if (errno || pid <= 0) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010011753# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011754 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011755 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011756 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011757 wait_pipe = parse_jobspec(*argv);
11758 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011759 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011760 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011761 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011762 } else {
11763 /* waiting on "last dead job" removes it */
11764 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011765 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011766 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011767 /* else: parse_jobspec() already emitted error msg */
11768 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011769 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011770# endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011771 /* mimic bash message */
11772 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011773 ret = EXIT_FAILURE;
11774 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011775 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011776
Denys Vlasenko7e675362016-10-28 21:57:31 +020011777 /* Do we have such child? */
11778 ret = waitpid(pid, &status, WNOHANG);
11779 if (ret < 0) {
11780 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011781 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011782 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011783 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011784 /* "wait $!" but last bg task has already exited. Try:
11785 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11786 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011787 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011788 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011789 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011790 } else {
11791 /* Example: "wait 1". mimic bash message */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011792 bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011793 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011794 } else {
11795 /* ??? */
11796 bb_perror_msg("wait %s", *argv);
11797 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011798 continue; /* bash checks all argv[] */
11799 }
11800 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011801 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011802 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011803 } else {
11804 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011805 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011806 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011807 if (WIFSIGNALED(status))
11808 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011809 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011810 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011811
11812 return ret;
11813}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011814#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011815
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011816#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11817static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11818{
11819 if (argv[1]) {
11820 def = bb_strtou(argv[1], NULL, 10);
11821 if (errno || def < def_min || argv[2]) {
11822 bb_error_msg("%s: bad arguments", argv[0]);
11823 def = UINT_MAX;
11824 }
11825 }
11826 return def;
11827}
11828#endif
11829
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011830#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011831static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011832{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011833 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011834 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011835 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011836 /* if we came from builtin_continue(), need to undo "= 1" */
11837 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011838 return EXIT_SUCCESS; /* bash compat */
11839 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011840 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011841
11842 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11843 if (depth == UINT_MAX)
11844 G.flag_break_continue = BC_BREAK;
11845 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011846 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011847
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011848 return EXIT_SUCCESS;
11849}
11850
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011851static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011852{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011853 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11854 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011855}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011856#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011857
11858#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011859static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011860{
11861 int rc;
11862
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011863 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011864 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11865 return EXIT_FAILURE; /* bash compat */
11866 }
11867
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011868 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011869
11870 /* bash:
11871 * out of range: wraps around at 256, does not error out
11872 * non-numeric param:
11873 * f() { false; return qwe; }; f; echo $?
11874 * bash: return: qwe: numeric argument required <== we do this
11875 * 255 <== we also do this
11876 */
11877 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
Denys Vlasenkobb095f42020-02-20 16:37:59 +010011878# if ENABLE_HUSH_TRAP
11879 if (argv[1]) { /* "return ARG" inside a running trap sets $? */
11880 debug_printf_exec("G.return_exitcode=%d\n", rc);
11881 G.return_exitcode = rc;
11882 }
11883# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011884 return rc;
11885}
11886#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011887
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011888#if ENABLE_HUSH_TIMES
11889static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11890{
11891 static const uint8_t times_tbl[] ALIGN1 = {
11892 ' ', offsetof(struct tms, tms_utime),
11893 '\n', offsetof(struct tms, tms_stime),
11894 ' ', offsetof(struct tms, tms_cutime),
11895 '\n', offsetof(struct tms, tms_cstime),
11896 0
11897 };
11898 const uint8_t *p;
11899 unsigned clk_tck;
11900 struct tms buf;
11901
11902 clk_tck = bb_clk_tck();
11903
11904 times(&buf);
11905 p = times_tbl;
11906 do {
11907 unsigned sec, frac;
11908 unsigned long t;
11909 t = *(clock_t *)(((char *) &buf) + p[1]);
11910 sec = t / clk_tck;
11911 frac = t % clk_tck;
11912 printf("%um%u.%03us%c",
11913 sec / 60, sec % 60,
11914 (frac * 1000) / clk_tck,
11915 p[0]);
11916 p += 2;
11917 } while (*p);
11918
11919 return EXIT_SUCCESS;
11920}
11921#endif
11922
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011923#if ENABLE_HUSH_MEMLEAK
11924static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11925{
11926 void *p;
11927 unsigned long l;
11928
11929# ifdef M_TRIM_THRESHOLD
11930 /* Optional. Reduces probability of false positives */
11931 malloc_trim(0);
11932# endif
11933 /* Crude attempt to find where "free memory" starts,
11934 * sans fragmentation. */
11935 p = malloc(240);
11936 l = (unsigned long)p;
11937 free(p);
11938 p = malloc(3400);
11939 if (l < (unsigned long)p) l = (unsigned long)p;
11940 free(p);
11941
11942
11943# if 0 /* debug */
11944 {
11945 struct mallinfo mi = mallinfo();
11946 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11947 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11948 }
11949# endif
11950
11951 if (!G.memleak_value)
11952 G.memleak_value = l;
11953
11954 l -= G.memleak_value;
11955 if ((long)l < 0)
11956 l = 0;
11957 l /= 1024;
11958 if (l > 127)
11959 l = 127;
11960
11961 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11962 return l;
11963}
11964#endif