blob: 179155f66efee98cc252d749f783997e27ecdfc6 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020066 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020067 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
68 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
69 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020070 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020071 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
72 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020073 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020074 * indirect expansion: ${!VAR}
75 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020076 *
77 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020078 * Some builtins mandated by standards:
79 * newgrp [GRP]: not a builtin in bash but a suid binary
80 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020081 *
82 * Status of [[ support:
83 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
84 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020085 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenkod2241f52020-10-31 03:34:07 +010086 * = is glob match operator, not equality operator: STR = GLOB
Denys Vlasenkod2241f52020-10-31 03:34:07 +010087 * == same as =
88 * =~ is regex match operator: STR =~ REGEX
Denys Vlasenko3632cb12018-04-10 15:25:41 +020089 * TODO:
Denys Vlasenko3632cb12018-04-10 15:25:41 +020090 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
Denys Vlasenkoa7c06532020-10-31 04:32:34 +010091 * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
Eric Andersen25f27032001-04-26 23:22:31 +000092 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020093//config:config HUSH
Denys Vlasenkob097a842018-12-28 03:20:17 +010094//config: bool "hush (68 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +020096//config: select SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020098//config: hush is a small shell. It handles the normal flow control
99//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
100//config: case/esac. Redirections, here documents, $((arithmetic))
101//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200102//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200103//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200104//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200105//config: It does not handle select, aliases, tilde expansion,
106//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200107//config:
Denys Vlasenko67e15292020-06-24 13:39:13 +0200108// This option is visible (has a description) to make it possible to select
109// a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
110//config:config SHELL_HUSH
111//config: bool "Internal shell for embedded script support"
112//config: default n
113//config:
114//config:# hush options
115//config:# It's only needed to get "nice" menuconfig indenting.
116//config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
117//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200118//config:config HUSH_BASH_COMPAT
119//config: bool "bash-compatible extensions"
120//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200121//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200122//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200123//config:config HUSH_BRACE_EXPANSION
124//config: bool "Brace expansion"
125//config: default y
126//config: depends on HUSH_BASH_COMPAT
127//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200128//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200129//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100130//config:config HUSH_BASH_SOURCE_CURDIR
131//config: bool "'source' and '.' builtins search current directory after $PATH"
132//config: default n # do not encourage non-standard behavior
133//config: depends on HUSH_BASH_COMPAT
134//config: help
135//config: This is not compliant with standards. Avoid if possible.
136//config:
Denys Vlasenkocbfdeba2021-03-10 16:31:05 +0100137//config:config HUSH_LINENO_VAR
138//config: bool "$LINENO variable (bashism)"
139//config: default y
140//config: depends on SHELL_HUSH
141//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:config HUSH_INTERACTIVE
143//config: bool "Interactive mode"
144//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200145//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200146//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200147//config: Enable interactive mode (prompt and command editing).
148//config: Without this, hush simply reads and executes commands
149//config: from stdin just like a shell script from a file.
150//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200151//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200152//config:config HUSH_SAVEHISTORY
153//config: bool "Save command history to .hush_history"
154//config: default y
155//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200156//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200157//config:config HUSH_JOB
158//config: bool "Job control"
159//config: default y
160//config: depends on HUSH_INTERACTIVE
161//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200162//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
163//config: command (not entire shell), fg/bg builtins work. Without this option,
164//config: "cmd &" still works by simply spawning a process and immediately
165//config: prompting for next command (or executing next command in a script),
166//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200167//config:
168//config:config HUSH_TICK
Ron Yorston060f0a02018-11-09 12:00:39 +0000169//config: bool "Support command substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200171//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200172//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200173//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200174//config:
175//config:config HUSH_IF
176//config: bool "Support if/then/elif/else/fi"
177//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200178//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200179//config:
180//config:config HUSH_LOOPS
181//config: bool "Support for, while and until loops"
182//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200183//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200184//config:
185//config:config HUSH_CASE
186//config: bool "Support case ... esac statement"
187//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200188//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200190//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200191//config:
192//config:config HUSH_FUNCTIONS
193//config: bool "Support funcname() { commands; } syntax"
194//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200195//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200197//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200198//config:
199//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100200//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: default y
202//config: depends on HUSH_FUNCTIONS
203//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200204//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:
206//config:config HUSH_RANDOM_SUPPORT
207//config: bool "Pseudorandom generator and $RANDOM variable"
208//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200209//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200210//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200211//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
212//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200213//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200214//config:config HUSH_MODE_X
215//config: bool "Support 'hush -x' option and 'set -x' command"
216//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200217//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200218//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200219//config: This instructs hush to print commands before execution.
220//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200221//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100222//config:config HUSH_ECHO
223//config: bool "echo builtin"
224//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200225//config: depends on SHELL_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100226//config:
227//config:config HUSH_PRINTF
228//config: bool "printf builtin"
229//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200230//config: depends on SHELL_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100231//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100232//config:config HUSH_TEST
233//config: bool "test builtin"
234//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200235//config: depends on SHELL_HUSH
Denys Vlasenko265062d2017-01-10 15:13:30 +0100236//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100237//config:config HUSH_HELP
238//config: bool "help builtin"
239//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200240//config: depends on SHELL_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100241//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100242//config:config HUSH_EXPORT
243//config: bool "export builtin"
244//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200245//config: depends on SHELL_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100246//config:
247//config:config HUSH_EXPORT_N
248//config: bool "Support 'export -n' option"
249//config: default y
250//config: depends on HUSH_EXPORT
251//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200252//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100253//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200254//config:config HUSH_READONLY
255//config: bool "readonly builtin"
256//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200257//config: depends on SHELL_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200258//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200259//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200260//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100262//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100263//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200264//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100265//config:
266//config:config HUSH_WAIT
267//config: bool "wait builtin"
268//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200269//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100270//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100271//config:config HUSH_COMMAND
272//config: bool "command builtin"
273//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200274//config: depends on SHELL_HUSH
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100275//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:config HUSH_TRAP
277//config: bool "trap builtin"
278//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200279//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100280//config:
281//config:config HUSH_TYPE
282//config: bool "type builtin"
283//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200284//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100285//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200286//config:config HUSH_TIMES
287//config: bool "times builtin"
288//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200289//config: depends on SHELL_HUSH
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200290//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100291//config:config HUSH_READ
292//config: bool "read builtin"
293//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200294//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100295//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100296//config:config HUSH_SET
297//config: bool "set builtin"
298//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200299//config: depends on SHELL_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100300//config:
301//config:config HUSH_UNSET
302//config: bool "unset builtin"
303//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200304//config: depends on SHELL_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100305//config:
306//config:config HUSH_ULIMIT
307//config: bool "ulimit builtin"
308//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200309//config: depends on SHELL_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100310//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100311//config:config HUSH_UMASK
312//config: bool "umask builtin"
313//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200314//config: depends on SHELL_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100315//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200316//config:config HUSH_GETOPTS
317//config: bool "getopts builtin"
318//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200319//config: depends on SHELL_HUSH
Denys Vlasenko74d40582017-08-11 01:32:46 +0200320//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100321//config:config HUSH_MEMLEAK
322//config: bool "memleak builtin (debugging)"
323//config: default n
Denys Vlasenko67e15292020-06-24 13:39:13 +0200324//config: depends on SHELL_HUSH
325//config:
326//config:endif # hush options
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200327
Denys Vlasenko20704f02011-03-23 17:59:27 +0100328//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100329// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100330//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100331//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100332
Denys Vlasenko67e15292020-06-24 13:39:13 +0200333//kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100334//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
335
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200336/* -i (interactive) is also accepted,
337 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100338 * NOMMU-specific options are not meant to be used by users,
339 * therefore we don't show them either.
340 */
341//usage:#define hush_trivial_usage
Denys Vlasenko1f60d882021-06-15 10:00:18 +0200342//usage: "[-enxl] [-c 'SCRIPT' [ARG0 ARGS] | FILE [ARGS] | -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100343//usage:#define hush_full_usage "\n\n"
344//usage: "Unix shell interpreter"
345
Denys Vlasenko67047462016-12-22 15:21:58 +0100346#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
347 || defined(__APPLE__) \
348 )
349# include <malloc.h> /* for malloc_trim */
350#endif
351#include <glob.h>
352/* #include <dmalloc.h> */
353#if ENABLE_HUSH_CASE
354# include <fnmatch.h>
355#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200356#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100357#include <sys/utsname.h> /* for setting $HOSTNAME */
358
359#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
360#include "unicode.h"
361#include "shell_common.h"
362#include "math.h"
363#include "match.h"
364#if ENABLE_HUSH_RANDOM_SUPPORT
365# include "random.h"
366#else
367# define CLEAR_RANDOM_T(rnd) ((void)0)
368#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200369#ifndef O_CLOEXEC
370# define O_CLOEXEC 0
371#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100372#ifndef F_DUPFD_CLOEXEC
373# define F_DUPFD_CLOEXEC F_DUPFD
374#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100375
Ron Yorston71df2d32018-11-27 14:34:25 +0000376#if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
377# include "embedded_scripts.h"
378#else
379# define NUM_SCRIPTS 0
380#endif
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000381
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100382/* So far, all bash compat is controlled by one config option */
383/* Separate defines document which part of code implements what */
384#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
385#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100386#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob278d822021-07-26 15:29:13 +0200387#define BASH_DOLLAR_SQUOTE ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100388#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Ron Yorstona81700b2019-04-15 10:48:29 +0100389#define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200390#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200391#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100392
393
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200394/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000395#define LEAK_HUNTING 0
396#define BUILD_AS_NOMMU 0
397/* Enable/disable sanity checks. Ok to enable in production,
398 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
399 * Keeping 1 for now even in released versions.
400 */
401#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200402/* Slightly bigger (+200 bytes), but faster hush.
403 * So far it only enables a trick with counting SIGCHLDs and forks,
404 * which allows us to do fewer waitpid's.
405 * (we can detect a case where neither forks were done nor SIGCHLDs happened
406 * and therefore waitpid will return the same result as last time)
407 */
408#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200409/* TODO: implement simplified code for users which do not need ${var%...} ops
410 * So far ${var%...} ops are always enabled:
411 */
412#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000413
414
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000415#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000416# undef BB_MMU
417# undef USE_FOR_NOMMU
418# undef USE_FOR_MMU
419# define BB_MMU 0
420# define USE_FOR_NOMMU(...) __VA_ARGS__
421# define USE_FOR_MMU(...)
422#endif
423
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200424#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100425#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000426/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000427# undef CONFIG_FEATURE_SH_STANDALONE
428# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000429# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100430# undef IF_NOT_FEATURE_SH_STANDALONE
431# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000432# define IF_FEATURE_SH_STANDALONE(...)
433# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000434#endif
435
Denis Vlasenko05743d72008-02-10 12:10:08 +0000436#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000437# undef ENABLE_FEATURE_EDITING
438# define ENABLE_FEATURE_EDITING 0
439# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
440# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200441# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
442# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000443#endif
444
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000445/* Do we support ANY keywords? */
446#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000447# define HAS_KEYWORDS 1
448# define IF_HAS_KEYWORDS(...) __VA_ARGS__
449# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000450#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000451# define HAS_KEYWORDS 0
452# define IF_HAS_KEYWORDS(...)
453# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000454#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000455
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000456/* If you comment out one of these below, it will be #defined later
457 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200458#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000459/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200460#define debug_printf_parse(...) do {} while (0)
461#define debug_printf_heredoc(...) do {} while (0)
462#define debug_print_tree(a, b) do {} while (0)
463#define debug_printf_exec(...) do {} while (0)
464#define debug_printf_env(...) do {} while (0)
465#define debug_printf_jobs(...) do {} while (0)
466#define debug_printf_expand(...) do {} while (0)
467#define debug_printf_varexp(...) do {} while (0)
468#define debug_printf_glob(...) do {} while (0)
469#define debug_printf_redir(...) do {} while (0)
470#define debug_printf_list(...) do {} while (0)
471#define debug_printf_subst(...) do {} while (0)
472#define debug_printf_prompt(...) do {} while (0)
473#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000474
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000475#define ERR_PTR ((void*)(long)1)
476
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100477#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000478
Denys Vlasenkoef8985c2019-05-19 16:29:09 +0200479#define _SPECIAL_VARS_STR "_*@$!?#-"
480#define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
481#define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100482#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200483/* Support / and // replace ops */
484/* Note that // is stored as \ in "encoded" string representation */
485# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
486# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
487# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
488#else
489# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
490# define VAR_SUBST_OPS "%#:-=+?"
491# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
492#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200493
Denys Vlasenko932b9972018-01-11 12:39:48 +0100494#define SPECIAL_VAR_SYMBOL_STR "\3"
495#define SPECIAL_VAR_SYMBOL 3
496/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
497#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000498
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200499struct variable;
500
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000501static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
502
503/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000504 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000505 */
506#if !BB_MMU
507typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200508 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000509 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000510 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000511} nommu_save_t;
512#endif
513
Denys Vlasenko9b782552010-09-08 13:33:26 +0200514enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000515 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000516#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000517 RES_IF ,
518 RES_THEN ,
519 RES_ELIF ,
520 RES_ELSE ,
521 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000522#endif
523#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000524 RES_FOR ,
525 RES_WHILE ,
526 RES_UNTIL ,
527 RES_DO ,
528 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000529#endif
530#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000531 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000532#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000533#if ENABLE_HUSH_CASE
534 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200535 /* three pseudo-keywords support contrived "case" syntax: */
536 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
537 RES_MATCH , /* "word)" */
538 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000539 RES_ESAC ,
540#endif
541 RES_XXXX ,
542 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200543};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000544
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000545typedef struct o_string {
546 char *data;
547 int length; /* position where data is appended */
548 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200549 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000550 /* At least some part of the string was inside '' or "",
551 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200552 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000553 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200554 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000555} o_string;
556enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200557 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
558 EXP_FLAG_GLOB = 0x2,
559 /* Protect newly added chars against globbing
560 * by prepending \ to *, ?, [, \ */
561 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
562};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563/* Used for initialization: o_string foo = NULL_O_STRING; */
564#define NULL_O_STRING { NULL }
565
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200566#ifndef debug_printf_parse
567static const char *const assignment_flag[] = {
568 "MAYBE_ASSIGNMENT",
569 "DEFINITELY_ASSIGNMENT",
570 "NOT_ASSIGNMENT",
571 "WORD_IS_KEYWORD",
572};
573#endif
574
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200575/* We almost can use standard FILE api, but we need an ability to move
576 * its fd when redirects coincide with it. No api exists for that
577 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
578 * HFILE is our internal alternative. Only supports reading.
579 * Since we now can, we incorporate linked list of all opened HFILEs
580 * into the struct (used to be a separate mini-list).
581 */
582typedef struct HFILE {
583 char *cur;
584 char *end;
585 struct HFILE *next_hfile;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200586 int fd;
587 char buf[1024];
588} HFILE;
589
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000590typedef struct in_str {
591 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200592 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200593 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200594 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000595} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000596
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200597/* The descrip member of this structure is only used to make
598 * debugging output pretty */
599static const struct {
Denys Vlasenko965b7952020-11-30 13:03:03 +0100600 int32_t mode;
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200601 signed char default_fd;
602 char descrip[3];
Denys Vlasenko965b7952020-11-30 13:03:03 +0100603} redir_table[] ALIGN4 = {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200604 { O_RDONLY, 0, "<" },
605 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
606 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
607 { O_CREAT|O_RDWR, 1, "<>" },
608 { O_RDONLY, 0, "<<" },
609/* Should not be needed. Bogus default_fd helps in debugging */
610/* { O_RDONLY, 77, "<<" }, */
611};
612
Eric Andersen25f27032001-04-26 23:22:31 +0000613struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000614 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000615 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000616 int rd_fd; /* fd to redirect */
617 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
618 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000619 smallint rd_type; /* (enum redir_type) */
620 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000621 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200622 * bit 0: do we need to trim leading tabs?
623 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000624 */
Eric Andersen25f27032001-04-26 23:22:31 +0000625};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000626typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200627 REDIRECT_INPUT = 0,
628 REDIRECT_OVERWRITE = 1,
629 REDIRECT_APPEND = 2,
630 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000631 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200632 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000633
634 REDIRFD_CLOSE = -3,
635 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000636 REDIRFD_TO_FILE = -1,
637 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000638
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000639 HEREDOC_SKIPTABS = 1,
640 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000641} redir_type;
642
Eric Andersen25f27032001-04-26 23:22:31 +0000643
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000644struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000645 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200646 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100647#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100648 unsigned lineno;
649#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200650 smallint cmd_type; /* CMD_xxx */
651#define CMD_NORMAL 0
652#define CMD_SUBSHELL 1
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100653#if BASH_TEST2
654/* used for "[[ EXPR ]]" */
655# define CMD_TEST2_SINGLEWORD_NOGLOB 2
656#endif
Denys Vlasenko77a51a22020-12-29 16:53:11 +0100657#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100658/* used to prevent word splitting and globbing in "export v=t*" */
659# define CMD_SINGLEWORD_NOGLOB 3
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200661#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100662# define CMD_FUNCDEF 4
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200663#endif
664
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100665 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200666 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
667 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000668#if !BB_MMU
669 char *group_as_string;
670#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000671#if ENABLE_HUSH_FUNCTIONS
672 struct function *child_func;
673/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200674 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000675 * When we execute "f1() {a;}" cmd, we create new function and clear
676 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200677 * When we execute "f1() {b;}", we notice that f1 exists,
678 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000679 * we put those fields back into cmd->xxx
680 * (struct function has ->parent_cmd ptr to facilitate that).
681 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
682 * Without this trick, loop would execute a;b;b;b;...
683 * instead of correct sequence a;b;a;b;...
684 * When command is freed, it severs the link
685 * (sets ->child_func->parent_cmd to NULL).
686 */
687#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000688 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000689/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
690 * and on execution these are substituted with their values.
691 * Substitution can make _several_ words out of one argv[n]!
692 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000693 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000694 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000695 struct redir_struct *redirects; /* I/O redirections */
696};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000697/* Is there anything in this command at all? */
698#define IS_NULL_CMD(cmd) \
699 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
700
Eric Andersen25f27032001-04-26 23:22:31 +0000701struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000702 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000703 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000704 int alive_cmds; /* number of commands running (not exited) */
705 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000706#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100707 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000708 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000709 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000710#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000711 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000712 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000713 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
714 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000715};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000716typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100717 PIPE_SEQ = 0,
718 PIPE_AND = 1,
719 PIPE_OR = 2,
720 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000721} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000722/* Is there anything in this pipe at all? */
723#define IS_NULL_PIPE(pi) \
724 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000725
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000726/* This holds pointers to the various results of parsing */
727struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000728 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000729 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000730 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000731 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000732 /* last command in pipe (being constructed right now) */
733 struct command *command;
734 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000735 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200736 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000737#if !BB_MMU
738 o_string as_string;
739#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200740 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000741#if HAS_KEYWORDS
742 smallint ctx_res_w;
743 smallint ctx_inverted; /* "! cmd | cmd" */
744#if ENABLE_HUSH_CASE
745 smallint ctx_dsemicolon; /* ";;" seen */
746#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000747 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
748 int old_flag;
749 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000750 * example: "if pipe1; pipe2; then pipe3; fi"
751 * when we see "if" or "then", we malloc and copy current context,
752 * and make ->stack point to it. then we parse pipeN.
753 * when closing "then" / fi" / whatever is found,
754 * we move list_head into ->stack->command->group,
755 * copy ->stack into current context, and delete ->stack.
756 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000757 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000758 struct parse_context *stack;
759#endif
760};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200761enum {
762 MAYBE_ASSIGNMENT = 0,
763 DEFINITELY_ASSIGNMENT = 1,
764 NOT_ASSIGNMENT = 2,
765 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
766 WORD_IS_KEYWORD = 3,
767};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000768
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000769/* On program start, environ points to initial environment.
770 * putenv adds new pointers into it, unsetenv removes them.
771 * Neither of these (de)allocates the strings.
772 * setenv allocates new strings in malloc space and does putenv,
773 * and thus setenv is unusable (leaky) for shell's purposes */
774#define setenv(...) setenv_is_leaky_dont_use()
775struct variable {
776 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000777 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000778 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200779 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000780 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000781 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000782};
783
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000784enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000785 BC_BREAK = 1,
786 BC_CONTINUE = 2,
787};
788
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000789#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000790struct function {
791 struct function *next;
792 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000793 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000794 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200795# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000796 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200797# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000798};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000799#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000800
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000801
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100802/* set -/+o OPT support. (TODO: make it optional)
803 * bash supports the following opts:
804 * allexport off
805 * braceexpand on
806 * emacs on
807 * errexit off
808 * errtrace off
809 * functrace off
810 * hashall on
811 * histexpand off
812 * history on
813 * ignoreeof off
814 * interactive-comments on
815 * keyword off
816 * monitor on
817 * noclobber off
818 * noexec off
819 * noglob off
820 * nolog off
821 * notify off
822 * nounset off
823 * onecmd off
824 * physical off
825 * pipefail off
826 * posix off
827 * privileged off
828 * verbose off
829 * vi off
830 * xtrace off
831 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800832static const char o_opt_strings[] ALIGN1 =
833 "pipefail\0"
834 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200835 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800836#if ENABLE_HUSH_MODE_X
837 "xtrace\0"
838#endif
839 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100840enum {
841 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800842 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200843 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800844#if ENABLE_HUSH_MODE_X
845 OPT_O_XTRACE,
846#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100847 NUM_OPT_O
848};
849
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000851/* Sorted roughly by size (smaller offsets == smaller code) */
852struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000853 /* interactive_fd != 0 means we are an interactive shell.
854 * If we are, then saved_tty_pgrp can also be != 0, meaning
855 * that controlling tty is available. With saved_tty_pgrp == 0,
856 * job control still works, but terminal signals
857 * (^C, ^Z, ^Y, ^\) won't work at all, and background
858 * process groups can only be created with "cmd &".
859 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
860 * to give tty to the foreground process group,
861 * and will take it back when the group is stopped (^Z)
862 * or killed (^C).
863 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000864#if ENABLE_HUSH_INTERACTIVE
865 /* 'interactive_fd' is a fd# open to ctty, if we have one
866 * _AND_ if we decided to act interactively */
867 int interactive_fd;
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +0200868 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000869# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000870#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000871# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000872#endif
873#if ENABLE_FEATURE_EDITING
874 line_input_t *line_input_state;
875#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000876 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200877 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000878 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200879#if ENABLE_HUSH_RANDOM_SUPPORT
880 random_t random_gen;
881#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000882#if ENABLE_HUSH_JOB
883 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100884 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000885 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000886 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400887# define G_saved_tty_pgrp (G.saved_tty_pgrp)
888#else
889# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000890#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200891 /* How deeply are we in context where "set -e" is ignored */
892 int errexit_depth;
893 /* "set -e" rules (do we follow them correctly?):
894 * Exit if pipe, list, or compound command exits with a non-zero status.
895 * Shell does not exit if failed command is part of condition in
896 * if/while, part of && or || list except the last command, any command
897 * in a pipe but the last, or if the command's return value is being
898 * inverted with !. If a compound command other than a subshell returns a
899 * non-zero status because a command failed while -e was being ignored, the
900 * shell does not exit. A trap on ERR, if set, is executed before the shell
901 * exits [ERR is a bashism].
902 *
903 * If a compound command or function executes in a context where -e is
904 * ignored, none of the commands executed within are affected by the -e
905 * setting. If a compound command or function sets -e while executing in a
906 * context where -e is ignored, that setting does not have any effect until
907 * the compound command or the command containing the function call completes.
908 */
909
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100910 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100911#if ENABLE_HUSH_MODE_X
912# define G_x_mode (G.o_opt[OPT_O_XTRACE])
913#else
914# define G_x_mode 0
915#endif
Denys Vlasenkod8740b22019-05-19 19:11:21 +0200916 char opt_s;
Denys Vlasenkof3634582019-06-03 12:21:04 +0200917 char opt_c;
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200918#if ENABLE_HUSH_INTERACTIVE
919 smallint promptmode; /* 0: PS1, 1: PS2 */
920#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000921 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000922#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000923 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000924#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000925#if ENABLE_HUSH_FUNCTIONS
926 /* 0: outside of a function (or sourced file)
927 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000928 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000929 */
930 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200931# define G_flag_return_in_progress (G.flag_return_in_progress)
932#else
933# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000934#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000935 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100936 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000937 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200938 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200939 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100940#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000941 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000942 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100943# define G_global_args_malloced (G.global_args_malloced)
944#else
945# define G_global_args_malloced 0
946#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100947#if ENABLE_HUSH_BASH_COMPAT
948 int dead_job_exitcode; /* for "wait -n" */
949#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000950 /* how many non-NULL argv's we have. NB: $# + 1 */
951 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000952 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000953#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000954 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000955#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000956#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000957 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000958 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000959#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200960#if ENABLE_HUSH_GETOPTS
961 unsigned getopt_count;
962#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000963 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200964 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000965 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200966 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200967 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200968 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200969 unsigned var_nest_level;
970#if ENABLE_HUSH_FUNCTIONS
971# if ENABLE_HUSH_LOCAL
972 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200973# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200974 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000975#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000976 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200977#if ENABLE_HUSH_FAST
978 unsigned count_SIGCHLD;
979 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200980 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200981#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100982#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +0200983 unsigned parse_lineno;
984 unsigned execute_lineno;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100985#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200986 HFILE *HFILE_list;
Denys Vlasenko21806562019-11-01 14:16:07 +0100987 HFILE *HFILE_stdin;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200988 /* Which signals have non-DFL handler (even with no traps set)?
989 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200990 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200991 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200992 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200993 * Other than these two times, never modified.
994 */
995 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200996#if ENABLE_HUSH_JOB
997 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100998# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200999#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001000# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001001#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001002#if ENABLE_HUSH_TRAP
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01001003 int pre_trap_exitcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01001004# if ENABLE_HUSH_FUNCTIONS
1005 int return_exitcode;
1006# endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001007 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001008# define G_traps G.traps
1009#else
1010# define G_traps ((char**)NULL)
1011#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001012 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +01001013#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001014 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +01001015#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001016#if ENABLE_HUSH_MODE_X
1017 unsigned x_mode_depth;
1018 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1019 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1020 * for all subsequent output.
1021 */
1022 int x_mode_fd;
1023 o_string x_mode_buf;
1024#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001025#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001026 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001027#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001028 struct sigaction sa;
Denys Vlasenkof3634582019-06-03 12:21:04 +02001029 char optstring_buf[sizeof("eixcs")];
Ron Yorstona81700b2019-04-15 10:48:29 +01001030#if BASH_EPOCH_VARS
Denys Vlasenko3c13da32020-12-30 23:48:01 +01001031 char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
Ron Yorstona81700b2019-04-15 10:48:29 +01001032#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001033#if ENABLE_FEATURE_EDITING
1034 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1035#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001036};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001037#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001038/* Not #defining name to G.name - this quickly gets unwieldy
1039 * (too many defines). Also, I actually prefer to see when a variable
1040 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001041#define INIT_G() do { \
1042 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001043 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1044 sigfillset(&G.sa.sa_mask); \
1045 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001046} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001047
1048
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001049/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001050static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001051#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001052static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001053#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_eval(char **argv) FAST_FUNC;
1055static int builtin_exec(char **argv) FAST_FUNC;
1056static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001057#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001058static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001059#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001060#if ENABLE_HUSH_READONLY
1061static int builtin_readonly(char **argv) FAST_FUNC;
1062#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001063#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001064static int builtin_fg_bg(char **argv) FAST_FUNC;
1065static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001066#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001067#if ENABLE_HUSH_GETOPTS
1068static int builtin_getopts(char **argv) FAST_FUNC;
1069#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001070#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001071static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001072#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001073#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001074static int builtin_history(char **argv) FAST_FUNC;
1075#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001076#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001077static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001078#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001079#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001080static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001081#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001082#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001083static int builtin_printf(char **argv) FAST_FUNC;
1084#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001085static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001086#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001087static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001088#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001089#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001090static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001091#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001092static int builtin_shift(char **argv) FAST_FUNC;
1093static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001094#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001095static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001096#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001097#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001098static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001099#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001100#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001101static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001102#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001103#if ENABLE_HUSH_TIMES
1104static int builtin_times(char **argv) FAST_FUNC;
1105#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001106static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001107#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001108static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001109#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001110#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001111static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001112#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001113#if ENABLE_HUSH_KILL
1114static int builtin_kill(char **argv) FAST_FUNC;
1115#endif
1116#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001117static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001118#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001119#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001120static int builtin_break(char **argv) FAST_FUNC;
1121static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001122#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001123#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001124static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001125#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001126
1127/* Table of built-in functions. They can be forked or not, depending on
1128 * context: within pipes, they fork. As simple commands, they do not.
1129 * When used in non-forking context, they can change global variables
1130 * in the parent shell process. If forked, of course they cannot.
1131 * For example, 'unset foo | whatever' will parse and run, but foo will
1132 * still be set at the end. */
1133struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001134 const char *b_cmd;
1135 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001136#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001137 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001138# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001139#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001140# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001141#endif
1142};
1143
Denys Vlasenko965b7952020-11-30 13:03:03 +01001144static const struct built_in_command bltins1[] ALIGN_PTR = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001145 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001146 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001147#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001148 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001149#endif
1150#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001151 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001152#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001153 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001154#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001156#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001157 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1158 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001159 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001160#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001161 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001162#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001163#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001164 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001165#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001166#if ENABLE_HUSH_GETOPTS
1167 BLTIN("getopts" , builtin_getopts , NULL),
1168#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001169#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001171#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001172#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001173 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001174#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001175#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001176 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001177#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001178#if ENABLE_HUSH_KILL
1179 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1180#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001181#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001182 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001183#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001184#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001185 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001186#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001187#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001188 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001189#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001190#if ENABLE_HUSH_READONLY
1191 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1192#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001193#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001194 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001195#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001196#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001197 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001198#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001199 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001200#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001201 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001202#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001203#if ENABLE_HUSH_TIMES
1204 BLTIN("times" , builtin_times , NULL),
1205#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001206#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001207 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001208#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001209 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001210#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001211 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001212#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001213#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001214 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001215#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001216#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001217 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001218#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001219#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001220 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001221#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001222#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001223 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001224#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001225};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001226/* These builtins won't be used if we are on NOMMU and need to re-exec
1227 * (it's cheaper to run an external program in this case):
1228 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01001229static const struct built_in_command bltins2[] ALIGN_PTR = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001230#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001231 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001232#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001233#if BASH_TEST2
1234 BLTIN("[[" , builtin_test , NULL),
1235#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001236#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001237 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001238#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001239#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001240 BLTIN("printf" , builtin_printf , NULL),
1241#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001242 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001243#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001244 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001245#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001246};
1247
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001248
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001249/* Debug printouts.
1250 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001251#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001252/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001253# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001254# define debug_enter() (G.debug_indent++)
1255# define debug_leave() (G.debug_indent--)
1256#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001257# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258# define debug_enter() ((void)0)
1259# define debug_leave() ((void)0)
1260#endif
1261
1262#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001263# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001264#endif
1265
1266#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001267# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001268#endif
1269
Denys Vlasenko3675c372018-07-23 16:31:21 +02001270#ifndef debug_printf_heredoc
1271# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1272#endif
1273
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001274#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001275#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001276#endif
1277
1278#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001279# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001280#endif
1281
1282#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001283# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001284# define DEBUG_JOBS 1
1285#else
1286# define DEBUG_JOBS 0
1287#endif
1288
1289#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001290# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001291# define DEBUG_EXPAND 1
1292#else
1293# define DEBUG_EXPAND 0
1294#endif
1295
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001296#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001297# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001298#endif
1299
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001300#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001301# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001302# define DEBUG_GLOB 1
1303#else
1304# define DEBUG_GLOB 0
1305#endif
1306
Denys Vlasenko2db74612017-07-07 22:07:28 +02001307#ifndef debug_printf_redir
1308# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1309#endif
1310
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001311#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001312# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001313#endif
1314
1315#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001316# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001317#endif
1318
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001319#ifndef debug_printf_prompt
1320# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1321#endif
1322
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001323#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001324# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001325# define DEBUG_CLEAN 1
1326#else
1327# define DEBUG_CLEAN 0
1328#endif
1329
1330#if DEBUG_EXPAND
1331static void debug_print_strings(const char *prefix, char **vv)
1332{
1333 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001334 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001335 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001336 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001337}
1338#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001339# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001340#endif
1341
1342
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001343/* Leak hunting. Use hush_leaktool.sh for post-processing.
1344 */
1345#if LEAK_HUNTING
1346static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001347{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001348 void *ptr = xmalloc((size + 0xff) & ~0xff);
1349 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1350 return ptr;
1351}
1352static void *xxrealloc(int lineno, void *ptr, size_t size)
1353{
1354 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1355 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1356 return ptr;
1357}
1358static char *xxstrdup(int lineno, const char *str)
1359{
1360 char *ptr = xstrdup(str);
1361 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1362 return ptr;
1363}
1364static void xxfree(void *ptr)
1365{
1366 fdprintf(2, "free %p\n", ptr);
1367 free(ptr);
1368}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001369# define xmalloc(s) xxmalloc(__LINE__, s)
1370# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1371# define xstrdup(s) xxstrdup(__LINE__, s)
1372# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001373#endif
1374
1375
1376/* Syntax and runtime errors. They always abort scripts.
1377 * In interactive use they usually discard unparsed and/or unexecuted commands
1378 * and return to the prompt.
1379 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1380 */
1381#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001382# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001383# define syntax_error(lineno, msg) syntax_error(msg)
1384# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1385# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1386# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1387# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001388#endif
1389
Denys Vlasenko39701202017-08-02 19:44:05 +02001390static void die_if_script(void)
1391{
1392 if (!G_interactive_fd) {
1393 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1394 xfunc_error_retval = G.last_exitcode;
1395 xfunc_die();
1396 }
1397}
1398
1399static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001400{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001401 va_list p;
1402
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001403#if HUSH_DEBUG >= 2
1404 bb_error_msg("hush.c:%u", lineno);
1405#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001406 va_start(p, fmt);
1407 bb_verror_msg(fmt, p, NULL);
1408 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001409 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001410}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001411
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001412static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001413{
1414 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001415 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001416 else
James Byrne69374872019-07-02 11:35:03 +02001417 bb_simple_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001418 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001419}
1420
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001421static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001422{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001423 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001424 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001425}
1426
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001427static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001428{
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01001429 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001430//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1431// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001432}
1433
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001434static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001435{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001436 char msg[2] = { ch, '\0' };
1437 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001438}
1439
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001440static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001441{
1442 char msg[2];
1443 msg[0] = ch;
1444 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001445#if HUSH_DEBUG >= 2
1446 bb_error_msg("hush.c:%u", lineno);
1447#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001448 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001449 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001450}
1451
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001452#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001453# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001454# undef syntax_error
1455# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001456# undef syntax_error_unterm_ch
1457# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001458# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001459#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001460# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001461# define syntax_error(msg) syntax_error(__LINE__, msg)
1462# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1463# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1464# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1465# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001466#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001467
Denis Vlasenko552433b2009-04-04 19:29:21 +00001468
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001469/* Utility functions
1470 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001471/* Replace each \x with x in place, return ptr past NUL. */
1472static char *unbackslash(char *src)
1473{
Denys Vlasenko71885402009-09-24 01:44:13 +02001474 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001475 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001476 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001477 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001478 if (*src != '\0') {
1479 /* \x -> x */
1480 *dst++ = *src++;
1481 continue;
1482 }
1483 /* else: "\<nul>". Do not delete this backslash.
1484 * Testcase: eval 'echo ok\'
1485 */
1486 *dst++ = '\\';
1487 /* fallthrough */
1488 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001489 if ((*dst++ = *src++) == '\0')
1490 break;
1491 }
1492 return dst;
1493}
1494
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001495static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001496{
1497 int i;
1498 unsigned count1;
1499 unsigned count2;
1500 char **v;
1501
1502 v = strings;
1503 count1 = 0;
1504 if (v) {
1505 while (*v) {
1506 count1++;
1507 v++;
1508 }
1509 }
1510 count2 = 0;
1511 v = add;
1512 while (*v) {
1513 count2++;
1514 v++;
1515 }
1516 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1517 v[count1 + count2] = NULL;
1518 i = count2;
1519 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001520 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001521 return v;
1522}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001523#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001524static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1525{
1526 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1527 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1528 return ptr;
1529}
1530#define add_strings_to_strings(strings, add, need_to_dup) \
1531 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1532#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001533
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001534/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001535static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001536{
1537 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001538 v[0] = add;
1539 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001540 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001541}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001542#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001543static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1544{
1545 char **ptr = add_string_to_strings(strings, add);
1546 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1547 return ptr;
1548}
1549#define add_string_to_strings(strings, add) \
1550 xx_add_string_to_strings(__LINE__, strings, add)
1551#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001552
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001553static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001554{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001555 char **v;
1556
1557 if (!strings)
1558 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001559 v = strings;
1560 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001561 free(*v);
1562 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001563 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001564 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001565}
1566
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001567static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001568{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001569 int newfd;
1570 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001571 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1572 if (newfd >= 0) {
1573 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1574 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1575 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001576 if (errno == EBUSY)
1577 goto repeat;
1578 if (errno == EINTR)
1579 goto repeat;
1580 }
1581 return newfd;
1582}
1583
Denys Vlasenko657e9002017-07-30 23:34:04 +02001584static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001585{
1586 int newfd;
1587 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001588 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001589 if (newfd < 0) {
1590 if (errno == EBUSY)
1591 goto repeat;
1592 if (errno == EINTR)
1593 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001594 /* fd was not open? */
1595 if (errno == EBADF)
1596 return fd;
1597 xfunc_die();
1598 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001599 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1600 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001601 close(fd);
1602 return newfd;
1603}
1604
1605
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001606/* Manipulating HFILEs */
1607static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001608{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001609 HFILE *fp;
1610 int fd;
1611
1612 fd = STDIN_FILENO;
1613 if (name) {
1614 fd = open(name, O_RDONLY | O_CLOEXEC);
1615 if (fd < 0)
1616 return NULL;
1617 if (O_CLOEXEC == 0) /* ancient libc */
1618 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001619 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001620
1621 fp = xmalloc(sizeof(*fp));
Denys Vlasenko21806562019-11-01 14:16:07 +01001622 if (name == NULL)
1623 G.HFILE_stdin = fp;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001624 fp->fd = fd;
1625 fp->cur = fp->end = fp->buf;
1626 fp->next_hfile = G.HFILE_list;
1627 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001628 return fp;
1629}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001630static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001631{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001632 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001633 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001634 HFILE *cur = *pp;
1635 if (cur == fp) {
1636 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001637 break;
1638 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001639 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001640 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001641 if (fp->fd >= 0)
1642 close(fp->fd);
1643 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001644}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001645static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001646{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001647 int n;
1648
1649 if (fp->fd < 0) {
1650 /* Already saw EOF */
1651 return EOF;
1652 }
Denys Vlasenko521220e2020-12-23 23:44:55 +01001653#if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
1654 /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
1655 * IOW: ^C will not immediately stop line input.
1656 * But poll() is different: it does NOT restart after signals.
1657 */
1658 if (fp == G.HFILE_stdin) {
1659 struct pollfd pfd[1];
1660 pfd[0].fd = fp->fd;
1661 pfd[0].events = POLLIN;
1662 n = poll(pfd, 1, -1);
1663 if (n < 0
1664 /*&& errno == EINTR - assumed true */
1665 && sigismember(&G.pending_set, SIGINT)
1666 ) {
1667 return '\0';
1668 }
1669 }
1670#else
1671/* if FEATURE_EDITING=y, we do not use this routine for interactive input */
1672#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001673 /* Try to buffer more input */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001674 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1675 if (n < 0) {
James Byrne69374872019-07-02 11:35:03 +02001676 bb_simple_perror_msg("read error");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001677 n = 0;
1678 }
Denys Vlasenko93e2a222020-12-23 12:23:21 +01001679 fp->cur = fp->buf;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001680 fp->end = fp->buf + n;
1681 if (n == 0) {
1682 /* EOF/error */
1683 close(fp->fd);
1684 fp->fd = -1;
1685 return EOF;
1686 }
1687 return (unsigned char)(*fp->cur++);
1688}
1689/* Inlined for common case of non-empty buffer.
1690 */
1691static ALWAYS_INLINE int hfgetc(HFILE *fp)
1692{
1693 if (fp->cur < fp->end)
1694 return (unsigned char)(*fp->cur++);
1695 /* Buffer empty */
1696 return refill_HFILE_and_getc(fp);
1697}
1698static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1699{
1700 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001701 while (fl) {
1702 if (fd == fl->fd) {
1703 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001704 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001705 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001706 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001707 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001708 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001709 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001710#if ENABLE_HUSH_MODE_X
1711 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1712 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1713 return 1; /* "found and moved" */
1714 }
1715#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001716 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001717}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001718#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001719static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001720{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001721 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001722 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001723 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001724 * It is disastrous if we share memory with a vforked parent.
1725 * I'm not sure we never come here after vfork.
1726 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001727 *
1728 * ">" instead of ">=": we don't close fd#0,
1729 * interactive shell uses hfopen(NULL) as stdin input
1730 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1731 * If we'd close it here, then e.g. interactive "set | sort"
1732 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001733 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001734 if (fl->fd > 0)
1735 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001736 close(fl->fd);
1737 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001738 }
1739}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001740#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001741static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001742{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001743 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001744 while (fl) {
1745 if (fl->fd == fd)
1746 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001747 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001748 }
1749 return 0;
1750}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001751
1752
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001753/* Helpers for setting new $n and restoring them back
1754 */
1755typedef struct save_arg_t {
1756 char *sv_argv0;
1757 char **sv_g_argv;
1758 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001759 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001760} save_arg_t;
1761
1762static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1763{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001764 sv->sv_argv0 = argv[0];
1765 sv->sv_g_argv = G.global_argv;
1766 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001767 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001768
1769 argv[0] = G.global_argv[0]; /* retain $0 */
1770 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001771 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001772
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001773 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001774}
1775
1776static void restore_G_args(save_arg_t *sv, char **argv)
1777{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001778#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001779 if (G.global_args_malloced) {
1780 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001781 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001782 while (*++pp) /* note: does not free $0 */
1783 free(*pp);
1784 free(G.global_argv);
1785 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001786#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001787 argv[0] = sv->sv_argv0;
1788 G.global_argv = sv->sv_g_argv;
1789 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001790 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001791}
1792
1793
Denis Vlasenkod5762932009-03-31 11:22:57 +00001794/* Basic theory of signal handling in shell
1795 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001796 * This does not describe what hush does, rather, it is current understanding
1797 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001798 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1799 *
1800 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1801 * is finished or backgrounded. It is the same in interactive and
1802 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001803 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001804 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001805 * backgrounds (i.e. stops) or kills all members of currently running
1806 * pipe.
1807 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001808 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001809 * or by SIGINT in interactive shell.
1810 *
1811 * Trap handlers will execute even within trap handlers. (right?)
1812 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001813 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1814 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001815 *
1816 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001817 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001818 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001819 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001820 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001821 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001822 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001823 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001824 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001825 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001826 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001827 *
1828 * SIGQUIT: ignore
1829 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001830 * SIGHUP (interactive):
1831 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001832 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001833 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1834 * that all pipe members are stopped. Try this in bash:
1835 * while :; do :; done - ^Z does not background it
1836 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001837 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001838 * of the command line, show prompt. NB: ^C does not send SIGINT
1839 * to interactive shell while shell is waiting for a pipe,
1840 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001841 * Example 1: this waits 5 sec, but does not execute ls:
1842 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1843 * Example 2: this does not wait and does not execute ls:
1844 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1845 * Example 3: this does not wait 5 sec, but executes ls:
1846 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001847 * Example 4: this does not wait and does not execute ls:
1848 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001849 *
1850 * (What happens to signals which are IGN on shell start?)
1851 * (What happens with signal mask on shell start?)
1852 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001853 * Old implementation
1854 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001855 * We use in-kernel pending signal mask to determine which signals were sent.
1856 * We block all signals which we don't want to take action immediately,
1857 * i.e. we block all signals which need to have special handling as described
1858 * above, and all signals which have traps set.
1859 * After each pipe execution, we extract any pending signals via sigtimedwait()
1860 * and act on them.
1861 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001862 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001863 * sigset_t blocked_set: current blocked signal set
1864 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001865 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001866 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001867 * "trap 'cmd' SIGxxx":
1868 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001869 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001870 * unblock signals with special interactive handling
1871 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001872 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001873 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001874 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001875 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001876 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001877 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001878 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001879 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001880 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001881 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001882 * Standard says "When a subshell is entered, traps that are not being ignored
1883 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001884 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001885 *
1886 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001887 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001888 * masked signals are not visible!
1889 *
1890 * New implementation
1891 * ==================
1892 * We record each signal we are interested in by installing signal handler
1893 * for them - a bit like emulating kernel pending signal mask in userspace.
1894 * We are interested in: signals which need to have special handling
1895 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001896 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001897 * After each pipe execution, we extract any pending signals
1898 * and act on them.
1899 *
1900 * unsigned special_sig_mask: a mask of shell-special signals.
1901 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1902 * char *traps[sig] if trap for sig is set (even if it's '').
1903 * sigset_t pending_set: set of sigs we received.
1904 *
1905 * "trap - SIGxxx":
1906 * if sig is in special_sig_mask, set handler back to:
1907 * record_pending_signo, or to IGN if it's a tty stop signal
1908 * if sig is in fatal_sig_mask, set handler back to sigexit.
1909 * else: set handler back to SIG_DFL
1910 * "trap 'cmd' SIGxxx":
1911 * set handler to record_pending_signo.
1912 * "trap '' SIGxxx":
1913 * set handler to SIG_IGN.
1914 * after [v]fork, if we plan to be a shell:
1915 * set signals with special interactive handling to SIG_DFL
1916 * (because child shell is not interactive),
1917 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1918 * after [v]fork, if we plan to exec:
1919 * POSIX says fork clears pending signal mask in child - no need to clear it.
1920 *
1921 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1922 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1923 *
1924 * Note (compat):
1925 * Standard says "When a subshell is entered, traps that are not being ignored
1926 * are set to the default actions". bash interprets it so that traps which
1927 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001928 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001929enum {
1930 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001931 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001932 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001933 | (1 << SIGHUP)
1934 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001935 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001936#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001937 | (1 << SIGTTIN)
1938 | (1 << SIGTTOU)
1939 | (1 << SIGTSTP)
1940#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001941 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001942};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001943
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001944static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001945{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001946 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001947#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001948 if (sig == SIGCHLD) {
1949 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001950//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001951 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001952#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001953}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001954
Denys Vlasenko0806e402011-05-12 23:06:20 +02001955static sighandler_t install_sighandler(int sig, sighandler_t handler)
1956{
1957 struct sigaction old_sa;
1958
1959 /* We could use signal() to install handlers... almost:
1960 * except that we need to mask ALL signals while handlers run.
1961 * I saw signal nesting in strace, race window isn't small.
1962 * SA_RESTART is also needed, but in Linux, signal()
1963 * sets SA_RESTART too.
1964 */
1965 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1966 /* sigfillset(&G.sa.sa_mask); - already done */
1967 /* G.sa.sa_flags = SA_RESTART; - already done */
1968 G.sa.sa_handler = handler;
1969 sigaction(sig, &G.sa, &old_sa);
1970 return old_sa.sa_handler;
1971}
1972
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001973static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001974
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001975static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001976static void restore_ttypgrp_and__exit(void)
1977{
1978 /* xfunc has failed! die die die */
1979 /* no EXIT traps, this is an escape hatch! */
1980 G.exiting = 1;
1981 hush_exit(xfunc_error_retval);
1982}
1983
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001984#if ENABLE_HUSH_JOB
1985
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001986/* Needed only on some libc:
1987 * It was observed that on exit(), fgetc'ed buffered data
1988 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1989 * With the net effect that even after fork(), not vfork(),
1990 * exit() in NOEXECed applet in "sh SCRIPT":
1991 * noexec_applet_here
1992 * echo END_OF_SCRIPT
1993 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1994 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001995 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001996 * and in `cmd` handling.
1997 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1998 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001999static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002000static void fflush_and__exit(void)
2001{
2002 fflush_all();
2003 _exit(xfunc_error_retval);
2004}
2005
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002006/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002007# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00002008/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002009# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002010
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002011/* Restores tty foreground process group, and exits.
2012 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002013 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002014 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002015 * We also call it if xfunc is exiting.
2016 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002017static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002018static void sigexit(int sig)
2019{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002020 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00002021 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002022 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
2023 /* Disable all signals: job control, SIGPIPE, etc.
2024 * Mostly paranoid measure, to prevent infinite SIGTTOU.
2025 */
2026 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04002027 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002028 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002029
2030 /* Not a signal, just exit */
2031 if (sig <= 0)
2032 _exit(- sig);
2033
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00002034 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002035}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002036#else
2037
Denys Vlasenko8391c482010-05-22 17:50:43 +02002038# define disable_restore_tty_pgrp_on_exit() ((void)0)
2039# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002040
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002041#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002042
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002043static sighandler_t pick_sighandler(unsigned sig)
2044{
2045 sighandler_t handler = SIG_DFL;
2046 if (sig < sizeof(unsigned)*8) {
2047 unsigned sigmask = (1 << sig);
2048
2049#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002050 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002051 if (G_fatal_sig_mask & sigmask)
2052 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002053 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002054#endif
2055 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002056 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002057 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002058 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002059 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002060 * in an endless loop when we try to do some
2061 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002062 */
2063 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2064 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002065 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002066 }
2067 return handler;
2068}
2069
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002070/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002071static void hush_exit(int exitcode)
2072{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002073#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
Denys Vlasenko00eb23b2020-12-21 21:36:58 +01002074 save_history(G.line_input_state); /* may be NULL */
Denys Vlasenkobede2152011-09-04 16:12:33 +02002075#endif
2076
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002077 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002078 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002079 char *argv[3];
2080 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002081 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002082 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002083 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002084 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002085 * "trap" will still show it, if executed
2086 * in the handler */
2087 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002088 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002089
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002090#if ENABLE_FEATURE_CLEAN_UP
2091 {
2092 struct variable *cur_var;
2093 if (G.cwd != bb_msg_unknown)
2094 free((char*)G.cwd);
2095 cur_var = G.top_var;
2096 while (cur_var) {
2097 struct variable *tmp = cur_var;
2098 if (!cur_var->max_len)
2099 free(cur_var->varstr);
2100 cur_var = cur_var->next;
2101 free(tmp);
2102 }
2103 }
2104#endif
2105
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002106 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002107#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002108 sigexit(- (exitcode & 0xff));
2109#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002110 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002111#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002112}
2113
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002114//TODO: return a mask of ALL handled sigs?
2115static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002116{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002117 int last_sig = 0;
2118
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002119 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002120 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002121
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002122 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002123 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002124 sig = 0;
2125 do {
2126 sig++;
2127 if (sigismember(&G.pending_set, sig)) {
2128 sigdelset(&G.pending_set, sig);
2129 goto got_sig;
2130 }
2131 } while (sig < NSIG);
2132 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002133 got_sig:
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002134#if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002135 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002136 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002137 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002138 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002139 smalluint save_rcode;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002140 int save_pre;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002141 char *argv[3];
2142 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002143 argv[1] = xstrdup(G_traps[sig]);
2144 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002145 argv[2] = NULL;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002146 save_pre = G.pre_trap_exitcode;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01002147 G.pre_trap_exitcode = save_rcode = G.last_exitcode;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002148 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002149 free(argv[1]);
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002150 G.pre_trap_exitcode = save_pre;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002151 G.last_exitcode = save_rcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002152# if ENABLE_HUSH_FUNCTIONS
2153 if (G.return_exitcode >= 0) {
2154 debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
2155 G.last_exitcode = G.return_exitcode;
2156 }
2157# endif
Denys Vlasenkob8709032011-05-08 21:20:01 +02002158 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002159 } /* else: "" trap, ignoring signal */
2160 continue;
2161 }
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002162#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002163 /* not a trap: special action */
2164 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002165 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002166 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002167 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002168 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002169 break;
2170#if ENABLE_HUSH_JOB
2171 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002172//TODO: why are we doing this? ash and dash don't do this,
2173//they have no handler for SIGHUP at all,
2174//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002175 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002176 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002177 /* bash is observed to signal whole process groups,
2178 * not individual processes */
2179 for (job = G.job_list; job; job = job->next) {
2180 if (job->pgrp <= 0)
2181 continue;
2182 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2183 if (kill(- job->pgrp, SIGHUP) == 0)
2184 kill(- job->pgrp, SIGCONT);
2185 }
2186 sigexit(SIGHUP);
2187 }
2188#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002189#if ENABLE_HUSH_FAST
2190 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002191 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002192 G.count_SIGCHLD++;
2193//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2194 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002195 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002196 * This simplifies wait builtin a bit.
2197 */
2198 break;
2199#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002200 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002201 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002202 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002203 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002204 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002205 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002206 * in interactive shell, because TERM is ignored.
2207 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002208 break;
2209 }
2210 }
2211 return last_sig;
2212}
2213
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002214
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002215static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002216{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002217 if (force || G.cwd == NULL) {
2218 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2219 * we must not try to free(bb_msg_unknown) */
2220 if (G.cwd == bb_msg_unknown)
2221 G.cwd = NULL;
2222 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2223 if (!G.cwd)
2224 G.cwd = bb_msg_unknown;
2225 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002226 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002227}
2228
Denis Vlasenko83506862007-11-23 13:11:42 +00002229
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002230/*
2231 * Shell and environment variable support
2232 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002233static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002234{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002235 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002236 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002237
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002238 pp = &G.top_var;
2239 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002240 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002241 return pp;
2242 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002243 }
2244 return NULL;
2245}
2246
Denys Vlasenko03dad222010-01-12 23:29:57 +01002247static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002248{
Denys Vlasenko29082232010-07-16 13:52:32 +02002249 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002250 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002251
2252 if (G.expanded_assignments) {
2253 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002254 while (*cpp) {
2255 char *cp = *cpp;
2256 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2257 return cp + len + 1;
2258 cpp++;
2259 }
2260 }
2261
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002262 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002263 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002264 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002265
Denys Vlasenkodea47882009-10-09 15:40:49 +02002266 if (strcmp(name, "PPID") == 0)
2267 return utoa(G.root_ppid);
2268 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002269#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002270 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002271 return utoa(next_random(&G.random_gen));
2272#endif
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002273#if ENABLE_HUSH_LINENO_VAR
2274 if (strcmp(name, "LINENO") == 0)
2275 return utoa(G.execute_lineno);
2276#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002277#if BASH_EPOCH_VARS
2278 {
2279 const char *fmt = NULL;
2280 if (strcmp(name, "EPOCHSECONDS") == 0)
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002281 fmt = "%llu";
Ron Yorstona81700b2019-04-15 10:48:29 +01002282 else if (strcmp(name, "EPOCHREALTIME") == 0)
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002283 fmt = "%llu.%06u";
Ron Yorstona81700b2019-04-15 10:48:29 +01002284 if (fmt) {
2285 struct timeval tv;
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002286 xgettimeofday(&tv);
2287 sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
Ron Yorstona81700b2019-04-15 10:48:29 +01002288 (unsigned)tv.tv_usec);
2289 return G.epoch_buf;
2290 }
2291 }
2292#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002293 return NULL;
2294}
2295
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002296#if ENABLE_HUSH_GETOPTS
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002297static void handle_changed_special_names(const char *name, unsigned name_len)
2298{
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002299 if (name_len == 6) {
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002300 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002301 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002302 return;
2303 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002304 }
2305}
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002306#else
2307/* Do not even bother evaluating arguments */
2308# define handle_changed_special_names(...) ((void)0)
2309#endif
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002310
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002311/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002312 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002313 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002314#define SETFLAG_EXPORT (1 << 0)
2315#define SETFLAG_UNEXPORT (1 << 1)
2316#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002317#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002318static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002319{
Denys Vlasenko61407802018-04-04 21:14:28 +02002320 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002321 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002322 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002323 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002324 int name_len;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002325 int retval;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002326 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002327
Denis Vlasenko950bd722009-04-21 11:23:56 +00002328 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002329 if (HUSH_DEBUG && !eq_sign)
James Byrne69374872019-07-02 11:35:03 +02002330 bb_simple_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002331
Denis Vlasenko950bd722009-04-21 11:23:56 +00002332 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002333 cur_pp = &G.top_var;
2334 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002335 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002336 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002337 continue;
2338 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002339
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002340 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002341 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002342 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002343 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002344//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2345//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002346 return -1;
2347 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002348 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002349 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2350 *eq_sign = '\0';
2351 unsetenv(str);
2352 *eq_sign = '=';
2353 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002354 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002355 /* bash 3.2.33(1) and exported vars:
2356 * # export z=z
2357 * # f() { local z=a; env | grep ^z; }
2358 * # f
2359 * z=a
2360 * # env | grep ^z
2361 * z=z
2362 */
2363 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002364 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002365 /* New variable is local ("local VAR=VAL" or
2366 * "VAR=VAL cmd")
2367 * and existing one is global, or local
2368 * on a lower level that new one.
2369 * Remove it from global variable list:
2370 */
2371 *cur_pp = cur->next;
2372 if (G.shadowed_vars_pp) {
2373 /* Save in "shadowed" list */
2374 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2375 cur->flg_export ? "exported " : "",
2376 cur->varstr, cur->var_nest_level, str, local_lvl
2377 );
2378 cur->next = *G.shadowed_vars_pp;
2379 *G.shadowed_vars_pp = cur;
2380 } else {
2381 /* Came from pseudo_exec_argv(), no need to save: delete it */
2382 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2383 cur->flg_export ? "exported " : "",
2384 cur->varstr, cur->var_nest_level, str, local_lvl
2385 );
2386 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2387 free_me = cur->varstr; /* then free it later */
2388 free(cur);
2389 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002390 break;
2391 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002392
Denis Vlasenko950bd722009-04-21 11:23:56 +00002393 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002394 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002395 free_and_exp:
2396 free(str);
2397 goto exp;
2398 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002399
2400 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002401 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002402 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002403 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002404 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002405 strcpy(cur->varstr, str);
2406 goto free_and_exp;
2407 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002408 /* Can't reuse */
2409 cur->max_len = 0;
2410 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002411 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002412 /* max_len == 0 signifies "malloced" var, which we can
2413 * (and have to) free. But we can't free(cur->varstr) here:
2414 * if cur->flg_export is 1, it is in the environment.
2415 * We should either unsetenv+free, or wait until putenv,
2416 * then putenv(new)+free(old).
2417 */
2418 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002419 goto set_str_and_exp;
2420 }
2421
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002422 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002423 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002424 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002425 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002426 cur->next = *cur_pp;
2427 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002428
2429 set_str_and_exp:
2430 cur->varstr = str;
2431 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002432#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002433 if (flags & SETFLAG_MAKE_RO) {
2434 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002435 }
2436#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002437 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002438 cur->flg_export = 1;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002439 retval = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002440 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002441 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002442 cur->flg_export = 0;
2443 /* unsetenv was already done */
2444 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002445 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002446 retval = putenv(cur->varstr);
2447 /* fall through to "free(free_me)" -
2448 * only now we can free old exported malloced string
2449 */
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002450 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002451 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002452 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002453
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002454 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002455
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002456 return retval;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002457}
2458
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002459static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2460{
2461 char *var = xasprintf("%s=%s", name, val);
2462 set_local_var(var, /*flag:*/ 0);
2463}
2464
Denys Vlasenko6db47842009-09-05 20:15:17 +02002465/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002466static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002467{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002468 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002469}
2470
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002471#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002472static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002473{
2474 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002475 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002476
Denys Vlasenko61407802018-04-04 21:14:28 +02002477 cur_pp = &G.top_var;
2478 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002479 if (strncmp(cur->varstr, name, name_len) == 0
2480 && cur->varstr[name_len] == '='
2481 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002482 if (cur->flg_read_only) {
2483 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002484 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002485 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002486
Denys Vlasenko61407802018-04-04 21:14:28 +02002487 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002488 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2489 bb_unsetenv(cur->varstr);
2490 if (!cur->max_len)
2491 free(cur->varstr);
2492 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002493
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002494 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002495 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002496 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002497 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002498
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002499 /* Handle "unset LINENO" et al even if did not find the variable to unset */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002500 handle_changed_special_names(name, name_len);
2501
Mike Frysingerd690f682009-03-30 06:50:54 +00002502 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002503}
2504
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002505static int unset_local_var(const char *name)
2506{
2507 return unset_local_var_len(name, strlen(name));
2508}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002509#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002510
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002511
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002512/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002513 * Helpers for "var1=val1 var2=val2 cmd" feature
2514 */
2515static void add_vars(struct variable *var)
2516{
2517 struct variable *next;
2518
2519 while (var) {
2520 next = var->next;
2521 var->next = G.top_var;
2522 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002523 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002524 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002525 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002526 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002527 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002528 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002529 var = next;
2530 }
2531}
2532
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002533/* We put strings[i] into variable table and possibly putenv them.
2534 * If variable is read only, we can free the strings[i]
2535 * which attempts to overwrite it.
2536 * The strings[] vector itself is freed.
2537 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002538static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002539{
2540 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002541
2542 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002543 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002544
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002545 s = strings;
2546 while (*s) {
2547 struct variable *var_p;
2548 struct variable **var_pp;
2549 char *eq;
2550
2551 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002552 if (HUSH_DEBUG && !eq)
James Byrne69374872019-07-02 11:35:03 +02002553 bb_simple_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002554 var_pp = get_ptr_to_local_var(*s, eq - *s);
2555 if (var_pp) {
2556 var_p = *var_pp;
2557 if (var_p->flg_read_only) {
2558 char **p;
2559 bb_error_msg("%s: readonly variable", *s);
2560 /*
2561 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2562 * If VAR is readonly, leaving it in the list
2563 * after asssignment error (msg above)
2564 * causes doubled error message later, on unset.
2565 */
2566 debug_printf_env("removing/freeing '%s' element\n", *s);
2567 free(*s);
2568 p = s;
2569 do { *p = p[1]; p++; } while (*p);
2570 goto next;
2571 }
2572 /* below, set_local_var() with nest level will
2573 * "shadow" (remove) this variable from
2574 * global linked list.
2575 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002576 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002577 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2578 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002579 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002580 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002581 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002582 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002583}
2584
2585
2586/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002587 * Unicode helper
2588 */
2589static void reinit_unicode_for_hush(void)
2590{
2591 /* Unicode support should be activated even if LANG is set
2592 * _during_ shell execution, not only if it was set when
2593 * shell was started. Therefore, re-check LANG every time:
2594 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002595 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2596 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002597 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002598 const char *s = get_local_var_value("LC_ALL");
2599 if (!s) s = get_local_var_value("LC_CTYPE");
2600 if (!s) s = get_local_var_value("LANG");
2601 reinit_unicode(s);
2602 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002603}
2604
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002605/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002606 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002607 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002608
2609#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002610/* To test correct lineedit/interactive behavior, type from command line:
2611 * echo $P\
2612 * \
2613 * AT\
2614 * H\
2615 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002616 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002617 */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002618static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002619{
2620 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002621
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002622 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002623
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002624# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2625 prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
2626 if (!prompt_str)
2627 prompt_str = "";
2628# else
2629 prompt_str = "> "; /* if PS2, else... */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002630 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002631 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2632 free(G.PS1);
2633 /* bash uses $PWD value, even if it is set by user.
2634 * It uses current dir only if PWD is unset.
2635 * We always use current dir. */
Denys Vlasenko649acb92020-12-23 15:29:13 +01002636 prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002637 }
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002638# endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002639 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002640 return prompt_str;
2641}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002642static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002643{
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002644# if ENABLE_FEATURE_EDITING
2645 /* In EDITING case, this function reads next input line,
2646 * saves it in i->p, then returns 1st char of it.
2647 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002648 int r;
2649 const char *prompt_str;
2650
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002651 prompt_str = setup_prompt_string();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002652 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002653 reinit_unicode_for_hush();
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002654 G.flag_SIGINT = 0;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002655 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002656 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002657 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002658 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002659 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002660 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002661 if (r == 0) {
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002662 raise(SIGINT);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002663 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002664 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002665 if (r != 0 && !G.flag_SIGINT)
2666 break;
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01002667 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002668 /* bash prints ^C even on real SIGINT (non-kbd generated) */
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002669 write(STDOUT_FILENO, "^C\n", 3);
Denys Vlasenko93e2a222020-12-23 12:23:21 +01002670 G.last_exitcode = 128 | SIGINT;
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002671 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002672 if (r < 0) {
2673 /* EOF/error detected */
Denys Vlasenkof0c0c562021-04-13 16:42:17 +02002674 /* ^D on interactive input goes to next line before exiting: */
2675 write(STDOUT_FILENO, "\n", 1);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002676 i->p = NULL;
2677 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002678 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002679 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002680 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002681 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002682# else
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002683 /* In !EDITING case, this function gets called for every char.
2684 * Buffering happens deeper in the call chain, in hfgetc(i->file).
2685 */
2686 int r;
2687
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002688 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002689 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002690 if (i->last_char == '\0' || i->last_char == '\n') {
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002691 const char *prompt_str = setup_prompt_string();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002692 /* Why check_and_run_traps here? Try this interactively:
2693 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2694 * $ <[enter], repeatedly...>
2695 * Without check_and_run_traps, handler never runs.
2696 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002697 check_and_run_traps();
Ron Yorstoncad3fc72021-02-03 20:47:14 +01002698 fputs_stdout(prompt_str);
Denys Vlasenko521220e2020-12-23 23:44:55 +01002699 fflush_all();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002700 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002701 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002702 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2703 * no ^C masking happens during fgetc, no special code for ^C:
2704 * it generates SIGINT as usual.
2705 */
2706 check_and_run_traps();
Denys Vlasenko521220e2020-12-23 23:44:55 +01002707 if (r != '\0' && !G.flag_SIGINT)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002708 break;
Denys Vlasenko521220e2020-12-23 23:44:55 +01002709 if (G.flag_SIGINT) {
2710 /* ^C or SIGINT: repeat */
2711 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2712 /* kernel prints "^C" itself, just print newline: */
2713 write(STDOUT_FILENO, "\n", 1);
2714 G.last_exitcode = 128 | SIGINT;
2715 }
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002716 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002717 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002718# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002719}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002720/* This is the magic location that prints prompts
2721 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002722static int fgetc_interactive(struct in_str *i)
2723{
2724 int ch;
2725 /* If it's interactive stdin, get new line. */
Denys Vlasenko21806562019-11-01 14:16:07 +01002726 if (G_interactive_fd && i->file == G.HFILE_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002727 /* Returns first char (or EOF), the rest is in i->p[] */
2728 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002729 G.promptmode = 1; /* PS2 */
2730 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002731 } else {
2732 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002733 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002734 }
2735 return ch;
2736}
Denys Vlasenko649acb92020-12-23 15:29:13 +01002737#else /* !INTERACTIVE */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002738static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002739{
2740 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002741 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002742 return ch;
2743}
Denys Vlasenko649acb92020-12-23 15:29:13 +01002744#endif /* !INTERACTIVE */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002745
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002746static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002747{
2748 int ch;
2749
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002750 if (!i->file) {
2751 /* string-based in_str */
2752 ch = (unsigned char)*i->p;
2753 if (ch != '\0') {
2754 i->p++;
2755 i->last_char = ch;
2756 return ch;
2757 }
2758 return EOF;
2759 }
2760
2761 /* FILE-based in_str */
2762
Denys Vlasenko4074d492016-09-30 01:49:53 +02002763#if ENABLE_FEATURE_EDITING
2764 /* This can be stdin, check line editing char[] buffer */
2765 if (i->p && *i->p != '\0') {
2766 ch = (unsigned char)*i->p++;
2767 goto out;
2768 }
2769#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002770 /* peek_buf[] is an int array, not char. Can contain EOF. */
2771 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002772 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002773 int ch2 = i->peek_buf[1];
2774 i->peek_buf[0] = ch2;
2775 if (ch2 == 0) /* very likely, avoid redundant write */
2776 goto out;
2777 i->peek_buf[1] = 0;
2778 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002779 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002780
Denys Vlasenko4074d492016-09-30 01:49:53 +02002781 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002782 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002783 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002784 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002785#if ENABLE_HUSH_LINENO_VAR
2786 if (ch == '\n') {
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002787 G.parse_lineno++;
2788 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
Denys Vlasenko5807e182018-02-08 19:19:04 +01002789 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002790#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002791 return ch;
2792}
2793
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002794static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002795{
2796 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002797
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002798 if (!i->file) {
2799 /* string-based in_str */
2800 /* Doesn't report EOF on NUL. None of the callers care. */
2801 return (unsigned char)*i->p;
2802 }
2803
2804 /* FILE-based in_str */
2805
Denys Vlasenko4074d492016-09-30 01:49:53 +02002806#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002807 /* This can be stdin, check line editing char[] buffer */
2808 if (i->p && *i->p != '\0')
2809 return (unsigned char)*i->p;
2810#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002811 /* peek_buf[] is an int array, not char. Can contain EOF. */
2812 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002813 if (ch != 0)
2814 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002815
Denys Vlasenko4074d492016-09-30 01:49:53 +02002816 /* Need to get a new char */
2817 ch = fgetc_interactive(i);
2818 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2819
2820 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2821#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2822 if (i->p) {
2823 i->p -= 1;
2824 return ch;
2825 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002826#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002827 i->peek_buf[0] = ch;
2828 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002829 return ch;
2830}
2831
Denys Vlasenko4074d492016-09-30 01:49:53 +02002832/* Only ever called if i_peek() was called, and did not return EOF.
2833 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2834 * not end-of-line. Therefore we never need to read a new editing line here.
2835 */
2836static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002837{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002838 int ch;
2839
2840 /* There are two cases when i->p[] buffer exists.
2841 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002842 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002843 * In both cases, we know that i->p[0] exists and not NUL, and
2844 * the peek2 result is in i->p[1].
2845 */
2846 if (i->p)
2847 return (unsigned char)i->p[1];
2848
2849 /* Now we know it is a file-based in_str. */
2850
2851 /* peek_buf[] is an int array, not char. Can contain EOF. */
2852 /* Is there 2nd char? */
2853 ch = i->peek_buf[1];
2854 if (ch == 0) {
2855 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002856 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002857 i->peek_buf[1] = ch;
2858 }
2859
2860 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2861 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002862}
2863
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002864static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2865{
2866 for (;;) {
2867 int ch, ch2;
2868
2869 ch = i_getch(input);
2870 if (ch != '\\')
2871 return ch;
2872 ch2 = i_peek(input);
2873 if (ch2 != '\n')
2874 return ch;
2875 /* backslash+newline, skip it */
2876 i_getch(input);
2877 }
2878}
2879
2880/* Note: this function _eats_ \<newline> pairs, safe to use plain
2881 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2882 */
2883static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2884{
2885 for (;;) {
2886 int ch, ch2;
2887
2888 ch = i_peek(input);
2889 if (ch != '\\')
2890 return ch;
2891 ch2 = i_peek2(input);
2892 if (ch2 != '\n')
2893 return ch;
2894 /* backslash+newline, skip it */
2895 i_getch(input);
2896 i_getch(input);
2897 }
2898}
2899
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002900static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002901{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002902 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002903 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002904 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002905}
2906
2907static void setup_string_in_str(struct in_str *i, const char *s)
2908{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002909 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002910 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002911 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002912}
2913
2914
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002915/*
2916 * o_string support
2917 */
2918#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002919
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002920static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002921{
2922 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002923 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002924 if (o->data)
2925 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002926}
2927
Denys Vlasenko18567402018-07-20 17:51:31 +02002928static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002929{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002930 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002931 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002932}
2933
Denys Vlasenko18567402018-07-20 17:51:31 +02002934static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002935{
2936 free(o->data);
2937}
2938
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002939static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002940{
2941 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002942 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002943 o->data = xrealloc(o->data, 1 + o->maxlen);
2944 }
2945}
2946
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002947static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002948{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002949 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002950 if (o->length < o->maxlen) {
2951 /* likely. avoid o_grow_by() call */
2952 add:
2953 o->data[o->length] = ch;
2954 o->length++;
2955 o->data[o->length] = '\0';
2956 return;
2957 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002958 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002959 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002960}
2961
Denys Vlasenko657086a2016-09-29 18:07:42 +02002962#if 0
2963/* Valid only if we know o_string is not empty */
2964static void o_delchr(o_string *o)
2965{
2966 o->length--;
2967 o->data[o->length] = '\0';
2968}
2969#endif
2970
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002971static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002972{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002973 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002974 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002975 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002976}
2977
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002978static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002979{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002980 o_addblock(o, str, strlen(str));
2981}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002982
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002983static void o_addstr_with_NUL(o_string *o, const char *str)
2984{
2985 o_addblock(o, str, strlen(str) + 1);
2986}
2987
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002988#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002989static void nommu_addchr(o_string *o, int ch)
2990{
2991 if (o)
2992 o_addchr(o, ch);
2993}
2994#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002995# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002996#endif
2997
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002998#if ENABLE_HUSH_MODE_X
2999static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003000{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003001 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00003002}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003003static void x_mode_addstr(const char *str)
3004{
3005 o_addstr(&G.x_mode_buf, str);
3006}
3007static void x_mode_addblock(const char *str, int len)
3008{
3009 o_addblock(&G.x_mode_buf, str, len);
3010}
3011static void x_mode_prefix(void)
3012{
3013 int n = G.x_mode_depth;
3014 do x_mode_addchr('+'); while (--n >= 0);
3015}
3016static void x_mode_flush(void)
3017{
3018 int len = G.x_mode_buf.length;
3019 if (len <= 0)
3020 return;
3021 if (G.x_mode_fd > 0) {
3022 G.x_mode_buf.data[len] = '\n';
3023 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
3024 }
3025 G.x_mode_buf.length = 0;
3026}
3027#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00003028
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003029/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02003030 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003031 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
3032 * Apparently, on unquoted $v bash still does globbing
3033 * ("v='*.txt'; echo $v" prints all .txt files),
3034 * but NOT brace expansion! Thus, there should be TWO independent
3035 * quoting mechanisms on $v expansion side: one protects
3036 * $v from brace expansion, and other additionally protects "$v" against globbing.
3037 * We have only second one.
3038 */
3039
Denys Vlasenko9e800222010-10-03 14:28:04 +02003040#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003041# define MAYBE_BRACES "{}"
3042#else
3043# define MAYBE_BRACES ""
3044#endif
3045
Eric Andersen25f27032001-04-26 23:22:31 +00003046/* My analysis of quoting semantics tells me that state information
3047 * is associated with a destination, not a source.
3048 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003049static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00003050{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003051 int sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003052 /* '-' is included because of this case:
3053 * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
3054 */
3055 char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003056 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003057 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003058 o_grow_by(o, sz);
3059 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003060 o->data[o->length] = '\\';
3061 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003062 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003063 o->data[o->length] = ch;
3064 o->length++;
3065 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003066}
3067
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003068static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003069{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003070 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003071 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003072 && strchr("*?[-\\" MAYBE_BRACES, ch)
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003073 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003074 sz++;
3075 o->data[o->length] = '\\';
3076 o->length++;
3077 }
3078 o_grow_by(o, sz);
3079 o->data[o->length] = ch;
3080 o->length++;
3081 o->data[o->length] = '\0';
3082}
3083
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003084static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003085{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003086 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003087 char ch;
3088 int sz;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003089 int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003090 if (ordinary_cnt > len) /* paranoia */
3091 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003092 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003093 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003094 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003095 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003096 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003097
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003098 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003099 sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003100 if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003101 sz++;
3102 o->data[o->length] = '\\';
3103 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003104 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003105 o_grow_by(o, sz);
3106 o->data[o->length] = ch;
3107 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003108 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003109 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003110}
3111
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003112static void o_addQblock(o_string *o, const char *str, int len)
3113{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003114 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003115 o_addblock(o, str, len);
3116 return;
3117 }
3118 o_addqblock(o, str, len);
3119}
3120
Denys Vlasenko38292b62010-09-05 14:49:40 +02003121static void o_addQstr(o_string *o, const char *str)
3122{
3123 o_addQblock(o, str, strlen(str));
3124}
3125
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003126/* A special kind of o_string for $VAR and `cmd` expansion.
3127 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003128 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003129 * list[i] contains an INDEX (int!) into this string data.
3130 * It means that if list[] needs to grow, data needs to be moved higher up
3131 * but list[i]'s need not be modified.
3132 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003133 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003134 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3135 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003136#if DEBUG_EXPAND || DEBUG_GLOB
3137static void debug_print_list(const char *prefix, o_string *o, int n)
3138{
3139 char **list = (char**)o->data;
3140 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3141 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003142
3143 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003144 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 +02003145 prefix, list, n, string_start, o->length, o->maxlen,
3146 !!(o->o_expflags & EXP_FLAG_GLOB),
3147 o->has_quoted_part,
3148 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003149 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003150 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003151 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3152 o->data + (int)(uintptr_t)list[i] + string_start,
3153 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003154 i++;
3155 }
3156 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003157 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003158 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003159 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003160 }
3161}
3162#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003163# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003164#endif
3165
3166/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3167 * in list[n] so that it points past last stored byte so far.
3168 * It returns n+1. */
3169static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003170{
3171 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003172 int string_start;
3173 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003174
3175 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003176 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3177 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003178 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003179 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003180 /* list[n] points to string_start, make space for 16 more pointers */
3181 o->maxlen += 0x10 * sizeof(list[0]);
3182 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003183 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003184 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003185 /*
3186 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3187 * check. (grep for -prev-ifs-check-).
3188 * Ensure that argv[-1][last] is not garbage
3189 * but zero bytes, to save index check there.
3190 */
3191 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003192 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003193 } else {
3194 debug_printf_list("list[%d]=%d string_start=%d\n",
3195 n, string_len, string_start);
3196 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003197 } else {
3198 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003199 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3200 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003201 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3202 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003203 o->has_empty_slot = 0;
3204 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003205 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003206 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003207 return n + 1;
3208}
3209
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003210/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003211static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003212{
3213 char **list = (char**)o->data;
3214 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3215
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003216 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003217}
3218
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003219/*
3220 * Globbing routines.
3221 *
3222 * Most words in commands need to be globbed, even ones which are
3223 * (single or double) quoted. This stems from the possiblity of
3224 * constructs like "abc"* and 'abc'* - these should be globbed.
3225 * Having a different code path for fully-quoted strings ("abc",
3226 * 'abc') would only help performance-wise, but we still need
3227 * code for partially-quoted strings.
3228 *
3229 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003230 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003231 * to a string, then globbed, and if globbing does not match anything,
3232 * it is used verbatim". Here are two examples where it fails:
3233 *
3234 * echo 'b\*'?
3235 *
3236 * The globbing can't be avoided (because of '?' at the end).
3237 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3238 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003239 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003240 * Now, look at this:
3241 *
3242 * v='\\\*'; echo b$v?
3243 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003244 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003245 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003246 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003247 *
3248 * ash implements this by having an encoded representation of the word
3249 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3250 * Glob pattern is derived from it. If glob fails, the decision what result
3251 * should be is made using that encoded representation. Not glob pattern.
3252 */
3253
Denys Vlasenko9e800222010-10-03 14:28:04 +02003254#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003255/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3256 * first, it processes even {a} (no commas), second,
3257 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003258 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003259 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003260
3261/* Helper */
3262static int glob_needed(const char *s)
3263{
3264 while (*s) {
3265 if (*s == '\\') {
3266 if (!s[1])
3267 return 0;
3268 s += 2;
3269 continue;
3270 }
3271 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3272 return 1;
3273 s++;
3274 }
3275 return 0;
3276}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003277/* Return pointer to next closing brace or to comma */
3278static const char *next_brace_sub(const char *cp)
3279{
3280 unsigned depth = 0;
3281 cp++;
3282 while (*cp != '\0') {
3283 if (*cp == '\\') {
3284 if (*++cp == '\0')
3285 break;
3286 cp++;
3287 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003288 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003289 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003290 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003291 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003292 depth++;
3293 }
3294
3295 return *cp != '\0' ? cp : NULL;
3296}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003297/* Recursive brace globber. Note: may garble pattern[]. */
3298static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003299{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003300 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003301 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003302 const char *next;
3303 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003304 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003305 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003306
3307 debug_printf_glob("glob_brace('%s')\n", pattern);
3308
3309 begin = pattern;
3310 while (1) {
3311 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003312 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003313 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003314 /* Find the first sub-pattern and at the same time
3315 * find the rest after the closing brace */
3316 next = next_brace_sub(begin);
3317 if (next == NULL) {
3318 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003319 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003320 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003321 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003322 /* "{abc}" with no commas - illegal
3323 * brace expr, disregard and skip it */
3324 begin = next + 1;
3325 continue;
3326 }
3327 break;
3328 }
3329 if (*begin == '\\' && begin[1] != '\0')
3330 begin++;
3331 begin++;
3332 }
3333 debug_printf_glob("begin:%s\n", begin);
3334 debug_printf_glob("next:%s\n", next);
3335
3336 /* Now find the end of the whole brace expression */
3337 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003338 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003339 rest = next_brace_sub(rest);
3340 if (rest == NULL) {
3341 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003342 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003343 }
3344 debug_printf_glob("rest:%s\n", rest);
3345 }
3346 rest_len = strlen(++rest) + 1;
3347
3348 /* We are sure the brace expression is well-formed */
3349
3350 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003351 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003352
3353 /* We have a brace expression. BEGIN points to the opening {,
3354 * NEXT points past the terminator of the first element, and REST
3355 * points past the final }. We will accumulate result names from
3356 * recursive runs for each brace alternative in the buffer using
3357 * GLOB_APPEND. */
3358
3359 p = begin + 1;
3360 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003361 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003362 memcpy(
3363 mempcpy(
3364 mempcpy(new_pattern_buf,
3365 /* We know the prefix for all sub-patterns */
3366 pattern, begin - pattern),
3367 p, next - p),
3368 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003369
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003370 /* Note: glob_brace() may garble new_pattern_buf[].
3371 * That's why we re-copy prefix every time (1st memcpy above).
3372 */
3373 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003374 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003375 /* We saw the last entry */
3376 break;
3377 }
3378 p = next + 1;
3379 next = next_brace_sub(next);
3380 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003381 free(new_pattern_buf);
3382 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003383
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003384 simple_glob:
3385 {
3386 int gr;
3387 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003388
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003389 memset(&globdata, 0, sizeof(globdata));
3390 gr = glob(pattern, 0, NULL, &globdata);
3391 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3392 if (gr != 0) {
3393 if (gr == GLOB_NOMATCH) {
3394 globfree(&globdata);
3395 /* NB: garbles parameter */
3396 unbackslash(pattern);
3397 o_addstr_with_NUL(o, pattern);
3398 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3399 return o_save_ptr_helper(o, n);
3400 }
3401 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003402 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003403 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3404 * but we didn't specify it. Paranoia again. */
3405 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3406 }
3407 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3408 char **argv = globdata.gl_pathv;
3409 while (1) {
3410 o_addstr_with_NUL(o, *argv);
3411 n = o_save_ptr_helper(o, n);
3412 argv++;
3413 if (!*argv)
3414 break;
3415 }
3416 }
3417 globfree(&globdata);
3418 }
3419 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003420}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003421/* Performs globbing on last list[],
3422 * saving each result as a new list[].
3423 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003424static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003425{
3426 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003427
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003428 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003429 if (!o->data)
3430 return o_save_ptr_helper(o, n);
3431 pattern = o->data + o_get_last_ptr(o, n);
3432 debug_printf_glob("glob pattern '%s'\n", pattern);
3433 if (!glob_needed(pattern)) {
3434 /* unbackslash last string in o in place, fix length */
3435 o->length = unbackslash(pattern) - o->data;
3436 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3437 return o_save_ptr_helper(o, n);
3438 }
3439
3440 copy = xstrdup(pattern);
3441 /* "forget" pattern in o */
3442 o->length = pattern - o->data;
3443 n = glob_brace(copy, o, n);
3444 free(copy);
3445 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003446 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003447 return n;
3448}
3449
Denys Vlasenko238081f2010-10-03 14:26:26 +02003450#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003451
3452/* Helper */
3453static int glob_needed(const char *s)
3454{
3455 while (*s) {
3456 if (*s == '\\') {
3457 if (!s[1])
3458 return 0;
3459 s += 2;
3460 continue;
3461 }
3462 if (*s == '*' || *s == '[' || *s == '?')
3463 return 1;
3464 s++;
3465 }
3466 return 0;
3467}
3468/* Performs globbing on last list[],
3469 * saving each result as a new list[].
3470 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003471static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003472{
3473 glob_t globdata;
3474 int gr;
3475 char *pattern;
3476
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003477 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003478 if (!o->data)
3479 return o_save_ptr_helper(o, n);
3480 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003481 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003482 if (!glob_needed(pattern)) {
3483 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003484 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003485 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003486 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003487 return o_save_ptr_helper(o, n);
3488 }
3489
3490 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003491 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3492 * If we glob "*.\*" and don't find anything, we need
3493 * to fall back to using literal "*.*", but GLOB_NOCHECK
3494 * will return "*.\*"!
3495 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003496 gr = glob(pattern, 0, NULL, &globdata);
3497 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003498 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003499 if (gr == GLOB_NOMATCH) {
3500 globfree(&globdata);
3501 goto literal;
3502 }
3503 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003504 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003505 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3506 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003507 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003508 }
3509 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3510 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003511 /* "forget" pattern in o */
3512 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003513 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003514 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003515 n = o_save_ptr_helper(o, n);
3516 argv++;
3517 if (!*argv)
3518 break;
3519 }
3520 }
3521 globfree(&globdata);
3522 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003523 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003524 return n;
3525}
3526
Denys Vlasenko238081f2010-10-03 14:26:26 +02003527#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003528
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003529/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003530 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003531static int o_save_ptr(o_string *o, int n)
3532{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003533 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003534 /* If o->has_empty_slot, list[n] was already globbed
3535 * (if it was requested back then when it was filled)
3536 * so don't do that again! */
3537 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003538 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003539 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003540 return o_save_ptr_helper(o, n);
3541}
3542
3543/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003544static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003545{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003546 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003547 int string_start;
3548
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003549 if (DEBUG_EXPAND)
3550 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003551 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003552 list = (char**)o->data;
3553 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3554 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003555 while (n) {
3556 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003557 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003558 }
3559 return list;
3560}
3561
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003562static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003563
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003564/* Returns pi->next - next pipe in the list */
3565static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003566{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003567 struct pipe *next;
3568 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003569
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003570 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003571 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003572 struct command *command;
3573 struct redir_struct *r, *rnext;
3574
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003575 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003576 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003577 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003578 if (DEBUG_CLEAN) {
3579 int a;
3580 char **p;
3581 for (a = 0, p = command->argv; *p; a++, p++) {
3582 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3583 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003584 }
3585 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003586 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003587 }
3588 /* not "else if": on syntax error, we may have both! */
3589 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003590 debug_printf_clean(" begin group (cmd_type:%d)\n",
3591 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003592 free_pipe_list(command->group);
3593 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003594 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003595 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003596 /* else is crucial here.
3597 * If group != NULL, child_func is meaningless */
3598#if ENABLE_HUSH_FUNCTIONS
3599 else if (command->child_func) {
3600 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3601 command->child_func->parent_cmd = NULL;
3602 }
3603#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003604#if !BB_MMU
3605 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003606 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003607#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003608 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003609 debug_printf_clean(" redirect %d%s",
3610 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003611 /* guard against the case >$FOO, where foo is unset or blank */
3612 if (r->rd_filename) {
3613 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3614 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003615 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003616 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003617 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003618 rnext = r->next;
3619 free(r);
3620 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003621 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003622 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003623 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003624 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003625#if ENABLE_HUSH_JOB
3626 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003627 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003628#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003629
3630 next = pi->next;
3631 free(pi);
3632 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003633}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003634
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003635static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003636{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003637 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003638#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003639 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003640#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003641 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003642 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003643 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003644}
3645
3646
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003647/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003648
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003649#ifndef debug_print_tree
3650static void debug_print_tree(struct pipe *pi, int lvl)
3651{
3652 static const char *const PIPE[] = {
3653 [PIPE_SEQ] = "SEQ",
3654 [PIPE_AND] = "AND",
3655 [PIPE_OR ] = "OR" ,
3656 [PIPE_BG ] = "BG" ,
3657 };
3658 static const char *RES[] = {
3659 [RES_NONE ] = "NONE" ,
3660# if ENABLE_HUSH_IF
3661 [RES_IF ] = "IF" ,
3662 [RES_THEN ] = "THEN" ,
3663 [RES_ELIF ] = "ELIF" ,
3664 [RES_ELSE ] = "ELSE" ,
3665 [RES_FI ] = "FI" ,
3666# endif
3667# if ENABLE_HUSH_LOOPS
3668 [RES_FOR ] = "FOR" ,
3669 [RES_WHILE] = "WHILE",
3670 [RES_UNTIL] = "UNTIL",
3671 [RES_DO ] = "DO" ,
3672 [RES_DONE ] = "DONE" ,
3673# endif
3674# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3675 [RES_IN ] = "IN" ,
3676# endif
3677# if ENABLE_HUSH_CASE
3678 [RES_CASE ] = "CASE" ,
3679 [RES_CASE_IN ] = "CASE_IN" ,
3680 [RES_MATCH] = "MATCH",
3681 [RES_CASE_BODY] = "CASE_BODY",
3682 [RES_ESAC ] = "ESAC" ,
3683# endif
3684 [RES_XXXX ] = "XXXX" ,
3685 [RES_SNTX ] = "SNTX" ,
3686 };
3687 static const char *const CMDTYPE[] = {
3688 "{}",
3689 "()",
3690 "[noglob]",
3691# if ENABLE_HUSH_FUNCTIONS
3692 "func()",
3693# endif
3694 };
3695
3696 int pin, prn;
3697
3698 pin = 0;
3699 while (pi) {
Denys Vlasenko83a49672021-06-15 18:12:13 +02003700 fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
Denys Vlasenko5807e182018-02-08 19:19:04 +01003701 lvl*2, "",
3702 pin,
Denys Vlasenko83a49672021-06-15 18:12:13 +02003703 pi->num_cmds,
Denys Vlasenko5807e182018-02-08 19:19:04 +01003704 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3705 RES[pi->res_word],
3706 pi->followup, PIPE[pi->followup]
3707 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003708 prn = 0;
3709 while (prn < pi->num_cmds) {
3710 struct command *command = &pi->cmds[prn];
3711 char **argv = command->argv;
3712
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003713 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003714 lvl*2, "", prn,
3715 command->assignment_cnt);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003716# if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko5807e182018-02-08 19:19:04 +01003717 fdprintf(2, " LINENO:%u", command->lineno);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003718# endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003719 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003720 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003721 CMDTYPE[command->cmd_type],
3722 argv
3723# if !BB_MMU
3724 , " group_as_string:", command->group_as_string
3725# else
3726 , "", ""
3727# endif
3728 );
3729 debug_print_tree(command->group, lvl+1);
3730 prn++;
3731 continue;
3732 }
3733 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003734 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003735 argv++;
3736 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003737 if (command->redirects)
3738 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003739 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003740 prn++;
3741 }
3742 pi = pi->next;
3743 pin++;
3744 }
3745}
3746#endif /* debug_print_tree */
3747
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003748static struct pipe *new_pipe(void)
3749{
Eric Andersen25f27032001-04-26 23:22:31 +00003750 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003751 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003752 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003753 return pi;
3754}
3755
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003756/* Command (member of a pipe) is complete, or we start a new pipe
3757 * if ctx->command is NULL.
3758 * No errors possible here.
3759 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003760static int done_command(struct parse_context *ctx)
3761{
3762 /* The command is really already in the pipe structure, so
3763 * advance the pipe counter and make a new, null command. */
3764 struct pipe *pi = ctx->pipe;
3765 struct command *command = ctx->command;
3766
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003767#if 0 /* Instead we emit error message at run time */
3768 if (ctx->pending_redirect) {
3769 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003770 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003771 ctx->pending_redirect = NULL;
3772 }
3773#endif
3774
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003775 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003776 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003777 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003778 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003779 }
3780 pi->num_cmds++;
3781 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003782 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003783 } else {
3784 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3785 }
3786
3787 /* Only real trickiness here is that the uncommitted
3788 * command structure is not counted in pi->num_cmds. */
3789 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003790 ctx->command = command = &pi->cmds[pi->num_cmds];
3791 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003792 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003793#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02003794 command->lineno = G.parse_lineno;
3795 debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003796#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003797 return pi->num_cmds; /* used only for 0/nonzero check */
3798}
3799
3800static void done_pipe(struct parse_context *ctx, pipe_style type)
3801{
3802 int not_null;
3803
3804 debug_printf_parse("done_pipe entered, followup %d\n", type);
3805 /* Close previous command */
3806 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003807#if HAS_KEYWORDS
3808 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3809 ctx->ctx_inverted = 0;
3810 ctx->pipe->res_word = ctx->ctx_res_w;
3811#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003812 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3813 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003814 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3815 * in a backgrounded subshell.
3816 */
3817 struct pipe *pi;
3818 struct command *command;
3819
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003820 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003821 pi = ctx->list_head;
3822 while (pi != ctx->pipe) {
3823 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3824 goto no_conv;
3825 pi = pi->next;
3826 }
3827
3828 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3829 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3830 pi = xzalloc(sizeof(*pi));
3831 pi->followup = PIPE_BG;
3832 pi->num_cmds = 1;
3833 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3834 command = &pi->cmds[0];
3835 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3836 command->cmd_type = CMD_NORMAL;
3837 command->group = ctx->list_head;
3838#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003839 command->group_as_string = xstrndup(
3840 ctx->as_string.data,
3841 ctx->as_string.length - 1 /* do not copy last char, "&" */
3842 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003843#endif
3844 /* Replace all pipes in ctx with one newly created */
3845 ctx->list_head = ctx->pipe = pi;
Denys Vlasenko83a49672021-06-15 18:12:13 +02003846 /* for cases like "cmd && &", do not be tricked by last command
3847 * being null - the entire {...} & is NOT null! */
3848 not_null = 1;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003849 } else {
3850 no_conv:
3851 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003852 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003853
3854 /* Without this check, even just <enter> on command line generates
3855 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003856 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003857 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003858#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003859 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003860#endif
3861#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003862 || ctx->ctx_res_w == RES_DONE
3863 || ctx->ctx_res_w == RES_FOR
3864 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003865#endif
3866#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003867 || ctx->ctx_res_w == RES_ESAC
3868#endif
3869 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003870 struct pipe *new_p;
3871 debug_printf_parse("done_pipe: adding new pipe: "
3872 "not_null:%d ctx->ctx_res_w:%d\n",
3873 not_null, ctx->ctx_res_w);
3874 new_p = new_pipe();
3875 ctx->pipe->next = new_p;
3876 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003877 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003878 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003879 * This is used to control execution.
3880 * RES_FOR and RES_IN are NOT sticky (needed to support
3881 * cases where variable or value happens to match a keyword):
3882 */
3883#if ENABLE_HUSH_LOOPS
3884 if (ctx->ctx_res_w == RES_FOR
3885 || ctx->ctx_res_w == RES_IN)
3886 ctx->ctx_res_w = RES_NONE;
3887#endif
3888#if ENABLE_HUSH_CASE
3889 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003890 ctx->ctx_res_w = RES_CASE_BODY;
3891 if (ctx->ctx_res_w == RES_CASE)
3892 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003893#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003894 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003895 /* Create the memory for command, roughly:
3896 * ctx->pipe->cmds = new struct command;
3897 * ctx->command = &ctx->pipe->cmds[0];
3898 */
3899 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003900 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003901 }
3902 debug_printf_parse("done_pipe return\n");
3903}
3904
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003905static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003906{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003907 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003908 if (MAYBE_ASSIGNMENT != 0)
3909 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003910 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003911 /* Create the memory for command, roughly:
3912 * ctx->pipe->cmds = new struct command;
3913 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003914 */
3915 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003916}
3917
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003918/* If a reserved word is found and processed, parse context is modified
3919 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003920 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003921#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003922struct reserved_combo {
3923 char literal[6];
3924 unsigned char res;
3925 unsigned char assignment_flag;
Denys Vlasenko965b7952020-11-30 13:03:03 +01003926 uint32_t flag;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003927};
3928enum {
3929 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003930# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003931 FLAG_IF = (1 << RES_IF ),
3932 FLAG_THEN = (1 << RES_THEN ),
3933 FLAG_ELIF = (1 << RES_ELIF ),
3934 FLAG_ELSE = (1 << RES_ELSE ),
3935 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003936# endif
3937# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003938 FLAG_FOR = (1 << RES_FOR ),
3939 FLAG_WHILE = (1 << RES_WHILE),
3940 FLAG_UNTIL = (1 << RES_UNTIL),
3941 FLAG_DO = (1 << RES_DO ),
3942 FLAG_DONE = (1 << RES_DONE ),
3943 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003944# endif
3945# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003946 FLAG_MATCH = (1 << RES_MATCH),
3947 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003948# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003949 FLAG_START = (1 << RES_XXXX ),
3950};
3951
3952static const struct reserved_combo* match_reserved_word(o_string *word)
3953{
Eric Andersen25f27032001-04-26 23:22:31 +00003954 /* Mostly a list of accepted follow-up reserved words.
3955 * FLAG_END means we are done with the sequence, and are ready
3956 * to turn the compound list into a command.
3957 * FLAG_START means the word must start a new compound list.
3958 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01003959 static const struct reserved_combo reserved_list[] ALIGN4 = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003960# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003961 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3962 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3963 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3964 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3965 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3966 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003967# endif
3968# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003969 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3970 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3971 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3972 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3973 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3974 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003975# endif
3976# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003977 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3978 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003979# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003980 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003981 const struct reserved_combo *r;
3982
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003983 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003984 if (strcmp(word->data, r->literal) == 0)
3985 return r;
3986 }
3987 return NULL;
3988}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003989/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003990 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003991static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003992{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003993# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003994 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003995 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003996 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003997# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003998 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003999
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004000 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004001 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004002 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004003 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01004004 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004005
4006 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004007# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004008 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4009 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004010 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004011 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004012# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004013 if (r->flag == 0) { /* '!' */
4014 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004015 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004016 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004017 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004018 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01004019 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004020 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004021 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004022 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004023
Denys Vlasenko9e55a152017-07-10 10:01:12 +02004024 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004025 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004026 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004027 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004028 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004029 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004030 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01004031 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004032 } else {
4033 /* "{...} fi" is ok. "{...} if" is not
4034 * Example:
4035 * if { echo foo; } then { echo bar; } fi */
4036 if (ctx->command->group)
4037 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004038 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004039
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004040 ctx->ctx_res_w = r->res;
4041 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004042 ctx->is_assignment = r->assignment_flag;
4043 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004044
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004045 if (ctx->old_flag & FLAG_END) {
4046 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004047
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004048 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004049 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004050 old = ctx->stack;
4051 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004052 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004053# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004054 /* At this point, the compound command's string is in
4055 * ctx->as_string... except for the leading keyword!
4056 * Consider this example: "echo a | if true; then echo a; fi"
4057 * ctx->as_string will contain "true; then echo a; fi",
4058 * with "if " remaining in old->as_string!
4059 */
4060 {
4061 char *str;
4062 int len = old->as_string.length;
4063 /* Concatenate halves */
4064 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004065 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004066 /* Find where leading keyword starts in first half */
4067 str = old->as_string.data + len;
4068 if (str > old->as_string.data)
4069 str--; /* skip whitespace after keyword */
4070 while (str > old->as_string.data && isalpha(str[-1]))
4071 str--;
4072 /* Ugh, we're done with this horrid hack */
4073 old->command->group_as_string = xstrdup(str);
4074 debug_printf_parse("pop, remembering as:'%s'\n",
4075 old->command->group_as_string);
4076 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004077# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004078 *ctx = *old; /* physical copy */
4079 free(old);
4080 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004081 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004082}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004083#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004084
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004085/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004086 * Normal return is 0. Syntax errors return 1.
4087 * Note: on return, word is reset, but not o_free'd!
4088 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004089static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004090{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004091 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004092
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004093 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4094 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004095 debug_printf_parse("done_word return 0: true null, ignored\n");
4096 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004097 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004098
Eric Andersen25f27032001-04-26 23:22:31 +00004099 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004100 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4101 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004102 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004103 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004104 * If the redirection operator is "<<" or "<<-", the word
4105 * that follows the redirection operator shall be
4106 * subjected to quote removal; it is unspecified whether
4107 * any of the other expansions occur. For the other
4108 * redirection operators, the word that follows the
4109 * redirection operator shall be subjected to tilde
4110 * expansion, parameter expansion, command substitution,
4111 * arithmetic expansion, and quote removal.
4112 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004113 * on the word by a non-interactive shell; an interactive
4114 * shell may perform it, but shall do so only when
4115 * the expansion would result in one word."
4116 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004117//bash does not do parameter/command substitution or arithmetic expansion
4118//for _heredoc_ redirection word: these constructs look for exact eof marker
4119// as written:
4120// <<EOF$t
4121// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004122// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4123
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004124 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004125 /* Cater for >\file case:
4126 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4127 * Same with heredocs:
4128 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4129 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004130 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4131 unbackslash(ctx->pending_redirect->rd_filename);
4132 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004133 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004134 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4135 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004136 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004137 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004138 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004139 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004140#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004141# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004142 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004143 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004144 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004145 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004146 /* ctx->ctx_res_w = RES_MATCH; */
4147 ctx->ctx_dsemicolon = 0;
4148 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004149# endif
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004150# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4151 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
4152 && strcmp(ctx->word.data, "]]") == 0
4153 ) {
4154 /* allow "[[ ]] >file" etc */
4155 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4156 } else
4157# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004158 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004159# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004160 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4161 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004162# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004163# if ENABLE_HUSH_CASE
4164 && ctx->ctx_res_w != RES_CASE
4165# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004166 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004167 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004168 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004169 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004170 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004171# if ENABLE_HUSH_LINENO_VAR
4172/* Case:
4173 * "while ...; do
4174 * cmd ..."
4175 * If we don't close the pipe _now_, immediately after "do", lineno logic
4176 * sees "cmd" as starting at "do" - i.e., at the previous line.
4177 */
4178 if (0
4179 IF_HUSH_IF(|| reserved->res == RES_THEN)
4180 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4181 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4182 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4183 ) {
4184 done_pipe(ctx, PIPE_SEQ);
4185 }
4186# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004187 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004188 debug_printf_parse("done_word return %d\n",
4189 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004190 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004191 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004192# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4193 if (strcmp(ctx->word.data, "[[") == 0) {
4194 command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
4195 } else
4196# endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02004197# if defined(CMD_SINGLEWORD_NOGLOB)
4198 if (0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004199 /* In bash, local/export/readonly are special, args
4200 * are assignments and therefore expansion of them
4201 * should be "one-word" expansion:
4202 * $ export i=`echo 'a b'` # one arg: "i=a b"
4203 * compare with:
4204 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4205 * ls: cannot access i=a: No such file or directory
4206 * ls: cannot access b: No such file or directory
4207 * Note: bash 3.2.33(1) does this only if export word
4208 * itself is not quoted:
4209 * $ export i=`echo 'aaa bbb'`; echo "$i"
4210 * aaa bbb
4211 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4212 * aaa
4213 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004214 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4215 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4216 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004217 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004218 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4219 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004220# else
4221 { /* empty block to pair "if ... else" */ }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004222# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004223 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004224#endif /* HAS_KEYWORDS */
4225
Denis Vlasenkobb929512009-04-16 10:59:40 +00004226 if (command->group) {
4227 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004228 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004229 debug_printf_parse("done_word return 1: syntax error, "
4230 "groups and arglists don't mix\n");
4231 return 1;
4232 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004233
4234 /* If this word wasn't an assignment, next ones definitely
4235 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004236 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4237 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004238 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004239 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004240 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004241 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004242 command->assignment_cnt++;
4243 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4244 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004245 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4246 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004247 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004248 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4249 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004250 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004251 }
Eric Andersen25f27032001-04-26 23:22:31 +00004252
Denis Vlasenko06810332007-05-21 23:30:54 +00004253#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004254 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004255 if (ctx->word.has_quoted_part
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02004256 || endofname(command->argv[0])[0] != '\0'
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004257 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004258 /* bash says just "not a valid identifier" */
Denys Vlasenko457825f2021-06-06 12:07:11 +02004259 syntax_error("bad variable name in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004260 return 1;
4261 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004262 /* Force FOR to have just one word (variable name) */
4263 /* NB: basically, this makes hush see "for v in ..."
4264 * syntax as if it is "for v; in ...". FOR and IN become
4265 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004266 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004267 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004268#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004269#if ENABLE_HUSH_CASE
4270 /* Force CASE to have just one word */
4271 if (ctx->ctx_res_w == RES_CASE) {
4272 done_pipe(ctx, PIPE_SEQ);
4273 }
4274#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004275
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004276 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004277
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004278 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004279 return 0;
4280}
4281
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004282
4283/* Peek ahead in the input to find out if we have a "&n" construct,
4284 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004285 * Return:
4286 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4287 * REDIRFD_SYNTAX_ERR if syntax error,
4288 * REDIRFD_TO_FILE if no & was seen,
4289 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004290 */
4291#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004292#define parse_redir_right_fd(as_string, input) \
4293 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004294#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004295static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004296{
4297 int ch, d, ok;
4298
4299 ch = i_peek(input);
4300 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004301 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004302
4303 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004304 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004305 ch = i_peek(input);
4306 if (ch == '-') {
4307 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004308 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004309 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004310 }
4311 d = 0;
4312 ok = 0;
4313 while (ch != EOF && isdigit(ch)) {
4314 d = d*10 + (ch-'0');
4315 ok = 1;
4316 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004317 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004318 ch = i_peek(input);
4319 }
4320 if (ok) return d;
4321
4322//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4323
James Byrne69374872019-07-02 11:35:03 +02004324 bb_simple_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004325 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004326}
4327
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004328/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004329 */
4330static int parse_redirect(struct parse_context *ctx,
4331 int fd,
4332 redir_type style,
4333 struct in_str *input)
4334{
4335 struct command *command = ctx->command;
4336 struct redir_struct *redir;
4337 struct redir_struct **redirp;
4338 int dup_num;
4339
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004340 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004341 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004342 /* Check for a '>&1' type redirect */
4343 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4344 if (dup_num == REDIRFD_SYNTAX_ERR)
4345 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004346 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004347 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004348 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004349 if (dup_num) { /* <<-... */
4350 ch = i_getch(input);
4351 nommu_addchr(&ctx->as_string, ch);
4352 ch = i_peek(input);
4353 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004354 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004355
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004356 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004357 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004358 if (ch == '|') {
4359 /* >|FILE redirect ("clobbering" >).
4360 * Since we do not support "set -o noclobber" yet,
4361 * >| and > are the same for now. Just eat |.
4362 */
4363 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004364 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004365 }
4366 }
4367
4368 /* Create a new redir_struct and append it to the linked list */
4369 redirp = &command->redirects;
4370 while ((redir = *redirp) != NULL) {
4371 redirp = &(redir->next);
4372 }
4373 *redirp = redir = xzalloc(sizeof(*redir));
4374 /* redir->next = NULL; */
4375 /* redir->rd_filename = NULL; */
4376 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004377 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004378
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004379 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4380 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004381
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004382 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004383 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004384 /* Erik had a check here that the file descriptor in question
4385 * is legit; I postpone that to "run time"
4386 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004387 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4388 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004389 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004390#if 0 /* Instead we emit error message at run time */
4391 if (ctx->pending_redirect) {
4392 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004393 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004394 }
4395#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004396 /* Set ctx->pending_redirect, so we know what to do at the
4397 * end of the next parsed word. */
4398 ctx->pending_redirect = redir;
4399 }
4400 return 0;
4401}
4402
Eric Andersen25f27032001-04-26 23:22:31 +00004403/* If a redirect is immediately preceded by a number, that number is
4404 * supposed to tell which file descriptor to redirect. This routine
4405 * looks for such preceding numbers. In an ideal world this routine
4406 * needs to handle all the following classes of redirects...
4407 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4408 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4409 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4410 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004411 *
4412 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4413 * "2.7 Redirection
4414 * ... If n is quoted, the number shall not be recognized as part of
4415 * the redirection expression. For example:
4416 * echo \2>a
4417 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004418 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004419 *
4420 * A -1 return means no valid number was found,
4421 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004422 */
4423static int redirect_opt_num(o_string *o)
4424{
4425 int num;
4426
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004427 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004428 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004429 num = bb_strtou(o->data, NULL, 10);
4430 if (errno || num < 0)
4431 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004432 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004433 return num;
4434}
4435
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004436#if BB_MMU
4437#define fetch_till_str(as_string, input, word, skip_tabs) \
4438 fetch_till_str(input, word, skip_tabs)
4439#endif
4440static char *fetch_till_str(o_string *as_string,
4441 struct in_str *input,
4442 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004443 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004444{
4445 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004446 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004447 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004448 int ch;
4449
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004450 /* Starting with "" is necessary for this case:
4451 * cat <<EOF
4452 *
4453 * xxx
4454 * EOF
4455 */
4456 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4457
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004458 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004459
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004460 while (1) {
4461 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004462 if (ch != EOF)
4463 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004464 if (ch == '\n' || ch == EOF) {
4465 check_heredoc_end:
4466 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004467 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004468 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4469 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004470 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004471 return heredoc.data;
4472 }
4473 if (ch == '\n') {
4474 /* This is a new line.
4475 * Remember position and backslash-escaping status.
4476 */
4477 o_addchr(&heredoc, ch);
4478 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004479 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004480 past_EOL = heredoc.length;
4481 /* Get 1st char of next line, possibly skipping leading tabs */
4482 do {
4483 ch = i_getch(input);
4484 if (ch != EOF)
4485 nommu_addchr(as_string, ch);
4486 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4487 /* If this immediately ended the line,
4488 * go back to end-of-line checks.
4489 */
4490 if (ch == '\n')
4491 goto check_heredoc_end;
4492 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004493 } else {
4494 /* Backslash-line continuation in an unquoted
4495 * heredoc. This does not need special handling
4496 * for heredoc body (unquoted heredocs are
4497 * expanded on "execution" and that would take
4498 * care of this case too), but not the case
4499 * of line continuation *in terminator*:
4500 * cat <<EOF
4501 * Ok1
4502 * EO\
4503 * F
4504 */
4505 heredoc.data[--heredoc.length] = '\0';
4506 prev = 0; /* not '\' */
4507 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004508 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004509 }
4510 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004511 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004512 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004513 }
4514 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004515 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004516 if (prev == '\\' && ch == '\\')
4517 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004518 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004519 else
4520 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004521 }
4522}
4523
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004524/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4525 * and load them all. There should be exactly heredoc_cnt of them.
4526 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004527#if BB_MMU
4528#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4529 fetch_heredocs(pi, heredoc_cnt, input)
4530#endif
4531static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004532{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004533 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004534 int i;
4535 struct command *cmd = pi->cmds;
4536
Denys Vlasenko3675c372018-07-23 16:31:21 +02004537 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004538 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004539 cmd->argv ? cmd->argv[0] : "NONE"
4540 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004541 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004542 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004543
Denys Vlasenko3675c372018-07-23 16:31:21 +02004544 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004545 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004546 while (redir) {
4547 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004548 char *p;
4549
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004550 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004551 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004552 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004553 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004554 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004555 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004556 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004557 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004558 free(redir->rd_filename);
4559 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004560 heredoc_cnt--;
4561 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004562 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004563 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004564 if (cmd->group) {
4565 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4566 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4567 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4568 if (heredoc_cnt < 0)
4569 return heredoc_cnt; /* error */
4570 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004571 cmd++;
4572 }
4573 pi = pi->next;
4574 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004575 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004576}
4577
4578
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004579static int run_list(struct pipe *pi);
4580#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004581#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4582 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004583#endif
4584static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004585 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004586 struct in_str *input,
4587 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004588
Denys Vlasenko474cb202018-07-24 13:03:03 +02004589/* Returns number of heredocs not yet consumed,
4590 * or -1 on error.
4591 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004592static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004593 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004594{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004595 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004596 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004597 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004598#if BB_MMU
4599# define as_string NULL
4600#else
4601 char *as_string = NULL;
4602#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004603 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004604 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004605 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004606 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004607
4608 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004609#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004610 if (ch == '(' && !ctx->word.has_quoted_part) {
4611 if (ctx->word.length)
4612 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004613 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004614 if (!command->argv)
4615 goto skip; /* (... */
4616 if (command->argv[1]) { /* word word ... (... */
4617 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004618 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004619 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004620 /* it is "word(..." or "word (..." */
4621 do
4622 ch = i_getch(input);
4623 while (ch == ' ' || ch == '\t');
4624 if (ch != ')') {
4625 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004626 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004627 }
4628 nommu_addchr(&ctx->as_string, ch);
4629 do
4630 ch = i_getch(input);
4631 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004632 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004633 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004634 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004635 }
4636 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004637 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004638 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004639 }
4640#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004641
4642#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004643 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004644 || ctx->word.length /* word{... */
4645 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004646 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004647 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004648 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004649 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004650 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004651 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004652#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004653
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004654 IF_HUSH_FUNCTIONS(skip:)
4655
Denis Vlasenko240c2552009-04-03 03:45:05 +00004656 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004657 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004658 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004659 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4660 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004661 } else {
4662 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004663 ch = i_peek(input);
4664 if (ch != ' ' && ch != '\t' && ch != '\n'
4665 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4666 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004667 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004668 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004669 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004670 if (ch != '(') {
4671 ch = i_getch(input);
4672 nommu_addchr(&ctx->as_string, ch);
4673 }
Eric Andersen25f27032001-04-26 23:22:31 +00004674 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004675
Denys Vlasenko474cb202018-07-24 13:03:03 +02004676 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4677 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4678 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004679#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004680 if (as_string)
4681 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004682#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004683
4684 /* empty ()/{} or parse error? */
4685 if (!pipe_list || pipe_list == ERR_PTR) {
4686 /* parse_stream already emitted error msg */
4687 if (!BB_MMU)
4688 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004689 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004690 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004691 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004692 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004693#if !BB_MMU
4694 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4695 command->group_as_string = as_string;
4696 debug_printf_parse("end of group, remembering as:'%s'\n",
4697 command->group_as_string);
4698#endif
4699
4700#if ENABLE_HUSH_FUNCTIONS
4701 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4702 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4703 struct command *cmd2;
4704
4705 cmd2 = xzalloc(sizeof(*cmd2));
4706 cmd2->cmd_type = CMD_SUBSHELL;
4707 cmd2->group = pipe_list;
4708# if !BB_MMU
4709//UNTESTED!
4710 cmd2->group_as_string = command->group_as_string;
4711 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4712# endif
4713
4714 pipe_list = new_pipe();
4715 pipe_list->cmds = cmd2;
4716 pipe_list->num_cmds = 1;
4717 }
4718#endif
4719
4720 command->group = pipe_list;
4721
Denys Vlasenko474cb202018-07-24 13:03:03 +02004722 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4723 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004724 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004725#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004726}
4727
Denys Vlasenko0b883582016-12-23 16:49:07 +01004728#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004729/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004730/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004731static int add_till_single_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 Vlasenko82dfec32008-06-16 12:47:11 +00004741 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004742 }
4743}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004744static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4745{
4746 while (1) {
4747 int ch = i_getch(input);
4748 if (ch == EOF) {
4749 syntax_error_unterm_ch('\'');
4750 return 0;
4751 }
4752 if (ch == '\'')
4753 return 1;
4754 o_addqchr(dest, ch);
4755 }
4756}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004757/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004758static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004759static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004760{
4761 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004762 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004763 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004764 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004765 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004766 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004767 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004768 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004769 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004770 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004771 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004772 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004773 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004774 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004775 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4776 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004777 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004778 continue;
4779 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004780 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004781 }
4782}
4783/* Process `cmd` - copy contents until "`" is seen. Complicated by
4784 * \` quoting.
4785 * "Within the backquoted style of command substitution, backslash
4786 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4787 * The search for the matching backquote shall be satisfied by the first
4788 * backquote found without a preceding backslash; during this search,
4789 * if a non-escaped backquote is encountered within a shell comment,
4790 * a here-document, an embedded command substitution of the $(command)
4791 * form, or a quoted string, undefined results occur. A single-quoted
4792 * or double-quoted string that begins, but does not end, within the
4793 * "`...`" sequence produces undefined results."
4794 * Example Output
4795 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4796 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004797static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004798{
4799 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004800 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004801 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004802 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004803 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004804 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4805 ch = i_getch(input);
4806 if (ch != '`'
4807 && ch != '$'
4808 && ch != '\\'
4809 && (!in_dquote || ch != '"')
4810 ) {
4811 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004812 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004813 }
4814 if (ch == EOF) {
4815 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004816 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004817 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004818 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004819 }
4820}
4821/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4822 * quoting and nested ()s.
4823 * "With the $(command) style of command substitution, all characters
4824 * following the open parenthesis to the matching closing parenthesis
4825 * constitute the command. Any valid shell script can be used for command,
4826 * except a script consisting solely of redirections which produces
4827 * unspecified results."
4828 * Example Output
4829 * echo $(echo '(TEST)' BEST) (TEST) BEST
4830 * echo $(echo 'TEST)' BEST) TEST) BEST
4831 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004832 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004833 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004834 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004835 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4836 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004837 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004838#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004839static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004840{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004841 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004842 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004843# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004844 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004845# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004846 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4847
Denys Vlasenko259747c2019-11-28 10:28:14 +01004848# if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004849 G.promptmode = 1; /* PS2 */
Denys Vlasenko259747c2019-11-28 10:28:14 +01004850# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004851 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4852
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004853 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004854 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004855 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004856 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004857 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004858 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004859 if (ch == end_ch
4860# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004861 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004862# endif
4863 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004864 if (!dbl)
4865 break;
4866 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004867 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004868 i_getch(input); /* eat second ')' */
4869 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004870 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004871 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004872 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004873 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004874 if (ch == '(' || ch == '{') {
4875 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004876 if (!add_till_closing_bracket(dest, input, ch))
4877 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004878 o_addchr(dest, ch);
4879 continue;
4880 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004881 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004882 if (!add_till_single_quote(dest, input))
4883 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004884 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004885 continue;
4886 }
4887 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004888 if (!add_till_double_quote(dest, input))
4889 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004890 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004891 continue;
4892 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004893 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004894 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4895 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004896 o_addchr(dest, ch);
4897 continue;
4898 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004899 if (ch == '\\') {
4900 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004901 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004902 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004903 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004904 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004905 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004906# if 0
Denys Vlasenko657086a2016-09-29 18:07:42 +02004907 if (ch == '\n') {
4908 /* "backslash+newline", ignore both */
4909 o_delchr(dest); /* undo insertion of '\' */
4910 continue;
4911 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004912# endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004913 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004914 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004915 continue;
4916 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004917 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004918 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004919 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004920}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004921#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004922
Denys Vlasenkob278d822021-07-26 15:29:13 +02004923#if BASH_DOLLAR_SQUOTE
4924/* Return code: 1 for "found and parsed", 0 for "seen something else" */
Denys Vlasenko8dd676c2021-07-27 04:09:45 +02004925# if BB_MMU
Denys Vlasenkob278d822021-07-26 15:29:13 +02004926#define parse_dollar_squote(as_string, dest, input) \
4927 parse_dollar_squote(dest, input)
4928#define as_string NULL
Denys Vlasenko8dd676c2021-07-27 04:09:45 +02004929# endif
Denys Vlasenkob278d822021-07-26 15:29:13 +02004930static int parse_dollar_squote(o_string *as_string, o_string *dest, struct in_str *input)
4931{
4932 int start;
4933 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4934 debug_printf_parse("parse_dollar_squote entered: ch='%c'\n", ch);
4935 if (ch != '\'')
4936 return 0;
4937
4938 dest->has_quoted_part = 1;
4939 start = dest->length;
4940
4941 ch = i_getch(input); /* eat ' */
4942 nommu_addchr(as_string, ch);
4943 while (1) {
4944 ch = i_getch(input);
4945 nommu_addchr(as_string, ch);
4946 if (ch == EOF) {
4947 syntax_error_unterm_ch('\'');
4948 return 0;
4949 }
4950 if (ch == '\'')
4951 break;
4952 if (ch == SPECIAL_VAR_SYMBOL) {
4953 /* Convert raw ^C to corresponding special variable reference */
4954 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4955 o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
4956 /* will addchr() another SPECIAL_VAR_SYMBOL (see after the if() block) */
4957 } else if (ch == '\\') {
4958 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
4959
4960 ch = i_getch(input);
4961 nommu_addchr(as_string, ch);
4962 if (strchr(C_escapes, ch)) {
4963 char buf[4];
4964 char *p = buf;
4965 int cnt = 2;
4966
4967 buf[0] = ch;
4968 if ((unsigned char)(ch - '0') <= 7) { /* \ooo */
4969 do {
4970 ch = i_peek(input);
4971 if ((unsigned char)(ch - '0') > 7)
4972 break;
4973 *++p = ch = i_getch(input);
4974 nommu_addchr(as_string, ch);
4975 } while (--cnt != 0);
4976 } else if (ch == 'x') { /* \xHH */
4977 do {
4978 ch = i_peek(input);
4979 if (!isxdigit(ch))
4980 break;
4981 *++p = ch = i_getch(input);
4982 nommu_addchr(as_string, ch);
4983 } while (--cnt != 0);
4984 if (cnt == 2) { /* \x but next char is "bad" */
4985 ch = 'x';
4986 goto unrecognized;
4987 }
4988 } /* else simple seq like \\ or \t */
4989 *++p = '\0';
4990 p = buf;
4991 ch = bb_process_escape_sequence((void*)&p);
4992 //bb_error_msg("buf:'%s' ch:%x", buf, ch);
4993 if (ch == '\0')
4994 continue; /* bash compat: $'...\0...' emits nothing */
4995 } else { /* unrecognized "\z": encode both chars unless ' or " */
4996 if (ch != '\'' && ch != '"') {
4997 unrecognized:
4998 o_addqchr(dest, '\\');
4999 }
5000 }
5001 } /* if (\...) */
5002 o_addqchr(dest, ch);
5003 }
5004
5005 if (dest->length == start) {
5006 /* $'', $'\0', $'\000\x00' and the like */
5007 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5008 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5009 }
5010
5011 return 1;
Denys Vlasenko8dd676c2021-07-27 04:09:45 +02005012# undef as_string
Denys Vlasenkob278d822021-07-26 15:29:13 +02005013}
5014#else
5015# #define parse_dollar_squote(as_string, dest, input) 0
5016#endif /* BASH_DOLLAR_SQUOTE */
5017
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005018/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005019#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005020#define parse_dollar(as_string, dest, input, quote_mask) \
5021 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005022#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005023#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005024static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005025 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005026 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00005027{
Denys Vlasenko657086a2016-09-29 18:07:42 +02005028 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005029
Denys Vlasenkob278d822021-07-26 15:29:13 +02005030 debug_printf_parse("parse_dollar entered: ch='%c' quote_mask:0x%x\n", ch, quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005031 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005032 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005033 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005034 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005035 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005036 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005037 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005038 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005039 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005040 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02005041 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02005042 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02005043 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005044 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02005045 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005046 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005047 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005048 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005049 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005050 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005051 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005052 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005053 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005054 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005055 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005056 o_addchr(dest, ch | quote_mask);
5057 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005058 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005059 case '$': /* pid */
5060 case '!': /* last bg pid */
5061 case '?': /* last exit code */
5062 case '#': /* number of args */
5063 case '*': /* args */
5064 case '@': /* args */
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005065 case '-': /* $- option flags set by set builtin or shell options (-i etc) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005066 goto make_one_char_var;
5067 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005068 char len_single_ch;
5069
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005070 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5071
Denys Vlasenko74369502010-05-21 19:52:01 +02005072 ch = i_getch(input); /* eat '{' */
5073 nommu_addchr(as_string, ch);
5074
Denys Vlasenko46e64982016-09-29 19:50:55 +02005075 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02005076 /* It should be ${?}, or ${#var},
5077 * or even ${?+subst} - operator acting on a special variable,
5078 * or the beginning of variable name.
5079 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005080 if (ch == EOF
5081 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
5082 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02005083 bad_dollar_syntax:
5084 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005085 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
5086 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02005087 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02005088 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005089 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02005090 ch |= quote_mask;
5091
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005092 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02005093 * However, this regresses some of our testsuite cases
5094 * which check invalid constructs like ${%}.
5095 * Oh well... let's check that the var name part is fine... */
5096
Denys Vlasenko97c3b5e2021-06-19 15:28:10 +02005097 if (isdigit(len_single_ch)
5098 || (len_single_ch == '#' && isdigit(i_peek_and_eat_bkslash_nl(input)))
5099 ) {
5100 /* Execution engine uses plain xatoi_positive()
5101 * to interpret ${NNN} and {#NNN},
5102 * check syntax here in the parser.
5103 * (bash does not support expressions in ${#NN},
5104 * e.g. ${#$var} and {#1:+WORD} are not supported).
5105 */
5106 unsigned cnt = 9; /* max 9 digits for ${NN} and 8 for {#NN} */
5107 while (1) {
5108 o_addchr(dest, ch);
5109 debug_printf_parse(": '%c'\n", ch);
5110 ch = i_getch_and_eat_bkslash_nl(input);
5111 nommu_addchr(as_string, ch);
5112 if (ch == '}')
5113 break;
5114 if (--cnt == 0)
5115 goto bad_dollar_syntax;
5116 if (len_single_ch != '#' && strchr(VAR_SUBST_OPS, ch))
5117 /* ${NN<op>...} is valid */
5118 goto eat_until_closing;
5119 if (!isdigit(ch))
5120 goto bad_dollar_syntax;
5121 }
5122 } else
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005123 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005124 unsigned pos;
5125
Denys Vlasenko74369502010-05-21 19:52:01 +02005126 o_addchr(dest, ch);
5127 debug_printf_parse(": '%c'\n", ch);
5128
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005129 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005130 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02005131 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00005132 break;
Denys Vlasenko74369502010-05-21 19:52:01 +02005133 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005134 unsigned end_ch;
5135 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005136 /* handle parameter expansions
5137 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5138 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005139 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
5140 if (len_single_ch != '#'
5141 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
5142 || i_peek(input) != '}'
5143 ) {
5144 goto bad_dollar_syntax;
5145 }
5146 /* else: it's "length of C" ${#C} op,
5147 * where C is a single char
5148 * special var name, e.g. ${#!}.
5149 */
5150 }
Denys Vlasenko97c3b5e2021-06-19 15:28:10 +02005151 eat_until_closing:
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005152 /* Eat everything until closing '}' (or ':') */
5153 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005154 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005155 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005156 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005157 ) {
5158 /* It's ${var:N[:M]} thing */
5159 end_ch = '}' * 0x100 + ':';
5160 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005161 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005162 && ch == '/'
5163 ) {
5164 /* It's ${var/[/]pattern[/repl]} thing */
5165 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
5166 i_getch(input);
5167 nommu_addchr(as_string, '/');
5168 ch = '\\';
5169 }
5170 end_ch = '}' * 0x100 + '/';
5171 }
5172 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02005173 /* The pattern can't be empty.
5174 * IOW: if the first char after "${v//" is a slash,
5175 * it does not terminate the pattern - it's the first char of the pattern:
5176 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
5177 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
5178 */
5179 if (i_peek(input) == '/') {
5180 o_addchr(dest, i_getch(input));
5181 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005182 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005183 if (!BB_MMU)
5184 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005185#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005186 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005187 if (last_ch == 0) /* error? */
5188 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005189#else
Denys Vlasenko259747c2019-11-28 10:28:14 +01005190# error Simple code to only allow ${var} is not implemented
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005191#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005192 if (as_string) {
5193 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005194 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005195 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005196
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005197 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5198 && (end_ch & 0xff00)
5199 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005200 /* close the first block: */
5201 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005202 /* while parsing N from ${var:N[:M]}
5203 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005204 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005205 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005206 end_ch = '}';
5207 goto again;
5208 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005209 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005210 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005211 /* it's ${var:N} - emulate :999999999 */
5212 o_addstr(dest, "999999999");
5213 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005214 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005215 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005216 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005217 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005218 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005219 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5220 break;
5221 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005222#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005223 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005224 unsigned pos;
5225
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005226 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005227 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005228# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005229 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005230 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005231 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005232 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01005233 o_addchr(dest, quote_mask | '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005234 if (!BB_MMU)
5235 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005236 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5237 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005238 if (as_string) {
5239 o_addstr(as_string, dest->data + pos);
5240 o_addchr(as_string, ')');
5241 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005242 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005243 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005244 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005245 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005246# endif
5247# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005248 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5249 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005250 if (!BB_MMU)
5251 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005252 if (!add_till_closing_bracket(dest, input, ')'))
5253 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005254 if (as_string) {
5255 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005256 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005257 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005258 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005259# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005260 break;
5261 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005262#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005263 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005264 goto make_var;
5265#if 0
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005266 /* TODO: $_: */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005267 /* $_ Shell or shell script name; or last argument of last command
5268 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5269 * but in command's env, set to full pathname used to invoke it */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005270 ch = i_getch(input);
5271 nommu_addchr(as_string, ch);
5272 ch = i_peek_and_eat_bkslash_nl(input);
5273 if (isalnum(ch)) { /* it's $_name or $_123 */
5274 ch = '_';
5275 goto make_var1;
5276 }
5277 /* else: it's $_ */
5278#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005279 default:
5280 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005281 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005282 debug_printf_parse("parse_dollar return 1 (ok)\n");
5283 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005284#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005285}
5286
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005287#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005288#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005289 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005290#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005291#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005292static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005293 o_string *dest,
5294 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005295 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005296{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005297 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005298 int next;
5299
5300 again:
5301 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005302 if (ch != EOF)
5303 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005304 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005305 debug_printf_parse("encode_string return 1 (ok)\n");
5306 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005307 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005308 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005309 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005310 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005311 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005312 }
5313 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005314 if (ch != '\n') {
5315 next = i_peek(input);
5316 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005317 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005318 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005319 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005320 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005321 /* Testcase: in interactive shell a file with
5322 * echo "unterminated string\<eof>
5323 * is sourced.
5324 */
5325 syntax_error_unterm_ch('"');
5326 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005327 }
5328 /* bash:
5329 * "The backslash retains its special meaning [in "..."]
5330 * only when followed by one of the following characters:
5331 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005332 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005333 * NB: in (unquoted) heredoc, above does not apply to ",
5334 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005335 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005336 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005337 ch = i_getch(input); /* eat next */
5338 if (ch == '\n')
5339 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005340 } /* else: ch remains == '\\', and we double it below: */
5341 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005342 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005343 goto again;
5344 }
5345 if (ch == '$') {
Denys Vlasenkob278d822021-07-26 15:29:13 +02005346 //if (parse_dollar_squote(as_string, dest, input))
5347 // goto again;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005348 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5349 debug_printf_parse("encode_string return 0: "
5350 "parse_dollar returned 0 (error)\n");
5351 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005352 }
5353 goto again;
5354 }
5355#if ENABLE_HUSH_TICK
5356 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005357 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005358 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5359 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005360 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5361 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005362 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5363 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005364 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005365 }
5366#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005367 o_addQchr(dest, ch);
Denys Vlasenko1b7a9b62021-06-15 16:05:57 +02005368 if (ch == SPECIAL_VAR_SYMBOL) {
5369 /* Convert "^C" to corresponding special variable reference */
5370 o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
5371 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5372 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005373 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005374#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005375}
5376
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005377/*
5378 * Scan input until EOF or end_trigger char.
5379 * Return a list of pipes to execute, or NULL on EOF
5380 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005381 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005382 * reset parsing machinery and start parsing anew,
5383 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005384 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005385static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005386 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005387 struct in_str *input,
5388 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005389{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005390 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005391 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005392
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005393 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005394 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005395 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005396 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005397 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005398 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005399
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005400 initialize_context(&ctx);
5401
5402 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5403 * Preventing this:
5404 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005405 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005406
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005407 /* We used to separate words on $IFS here. This was wrong.
5408 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005409 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005410 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005411
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005412 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005413 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005414 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005415 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005416 int ch;
5417 int next;
5418 int redir_fd;
5419 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005420
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005421 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005422 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005423 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005424 if (ch == EOF) {
5425 struct pipe *pi;
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01005426
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005427 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005428 syntax_error_unterm_str("here document");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005429 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005430 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005431 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005432 syntax_error_unterm_ch('(');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005433 goto parse_error_exitcode1;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005434 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005435 if (end_trigger == '}') {
5436 syntax_error_unterm_ch('{');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005437 goto parse_error_exitcode1;
Denys Vlasenko42246472016-11-07 16:22:35 +01005438 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005439
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005440 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005441 goto parse_error_exitcode1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005442 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005443 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005444 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005445 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005446 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005447 /* (this makes bare "&" cmd a no-op.
5448 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005449 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005450 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005451 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005452 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005453 pi = NULL;
5454 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005455#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005456 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005457 if (pstring)
5458 *pstring = ctx.as_string.data;
5459 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005460 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005461#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005462 // heredoc_cnt must be 0 here anyway
5463 //if (heredoc_cnt_ptr)
5464 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005465 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005466 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005467 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005468 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005469 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005470
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005471 /* Handle "'" and "\" first, as they won't play nice with
5472 * i_peek_and_eat_bkslash_nl() anyway:
5473 * echo z\\
5474 * and
5475 * echo '\
5476 * '
5477 * would break.
5478 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005479 if (ch == '\\') {
5480 ch = i_getch(input);
5481 if (ch == '\n')
5482 continue; /* drop \<newline>, get next char */
5483 nommu_addchr(&ctx.as_string, '\\');
Denys Vlasenko1b7a9b62021-06-15 16:05:57 +02005484 if (ch == SPECIAL_VAR_SYMBOL) {
5485 nommu_addchr(&ctx.as_string, ch);
5486 /* Convert \^C to corresponding special variable reference */
5487 goto case_SPECIAL_VAR_SYMBOL;
5488 }
Denys Vlasenkof693b602018-04-11 20:00:43 +02005489 o_addchr(&ctx.word, '\\');
5490 if (ch == EOF) {
5491 /* Testcase: eval 'echo Ok\' */
5492 /* bash-4.3.43 was removing backslash,
5493 * but 4.4.19 retains it, most other shells too
5494 */
5495 continue; /* get next char */
5496 }
5497 /* Example: echo Hello \2>file
5498 * we need to know that word 2 is quoted
5499 */
5500 ctx.word.has_quoted_part = 1;
5501 nommu_addchr(&ctx.as_string, ch);
5502 o_addchr(&ctx.word, ch);
5503 continue; /* get next char */
5504 }
5505 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005506 if (ch == '\'') {
5507 ctx.word.has_quoted_part = 1;
5508 next = i_getch(input);
5509 if (next == '\'' && !ctx.pending_redirect)
5510 goto insert_empty_quoted_str_marker;
5511
5512 ch = next;
5513 while (1) {
5514 if (ch == EOF) {
5515 syntax_error_unterm_ch('\'');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005516 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005517 }
5518 nommu_addchr(&ctx.as_string, ch);
5519 if (ch == '\'')
5520 break;
5521 if (ch == SPECIAL_VAR_SYMBOL) {
5522 /* Convert raw ^C to corresponding special variable reference */
5523 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5524 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5525 }
5526 o_addqchr(&ctx.word, ch);
5527 ch = i_getch(input);
5528 }
5529 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005530 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005531
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005532 next = '\0';
5533 if (ch != '\n')
5534 next = i_peek_and_eat_bkslash_nl(input);
5535
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005536 is_special = "{}<>&|();#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005537 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005538 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005539#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
5540 if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
5541 /* In [[ ]], {}<>&|() are not special */
5542 is_special += 8;
5543 } else
5544#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005545 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005546 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005547 || ctx.word.length /* word{... - non-special */
5548 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005549 || (next != ';' /* }; - special */
5550 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005551 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005552 && next != '&' /* }& and }&& ... - special */
5553 && next != '|' /* }|| ... - special */
5554 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005555 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005556 ) {
5557 /* They are not special, skip "{}" */
5558 is_special += 2;
5559 }
5560 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005561 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005562
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005563 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005564 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005565 o_addQchr(&ctx.word, ch);
5566 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5567 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005568 && ch == '='
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02005569 && endofname(ctx.word.data)[0] == '='
Denis Vlasenko55789c62008-06-18 16:30:42 +00005570 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005571 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5572 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005573 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005574 continue;
5575 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005576
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005577 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005578#if ENABLE_HUSH_LINENO_VAR
5579/* Case:
5580 * "while ...; do<whitespace><newline>
5581 * cmd ..."
5582 * would think that "cmd" starts in <whitespace> -
5583 * i.e., at the previous line.
5584 * We need to skip all whitespace before newlines.
5585 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005586 while (ch != '\n') {
5587 next = i_peek(input);
5588 if (next != ' ' && next != '\t' && next != '\n')
5589 break; /* next char is not ws */
5590 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005591 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005592 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005593#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005594 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005595 goto parse_error_exitcode1;
Eric Andersenaac75e52001-04-30 18:18:45 +00005596 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005597 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005598 /* Is this a case when newline is simply ignored?
5599 * Some examples:
5600 * "cmd | <newline> cmd ..."
5601 * "case ... in <newline> word) ..."
5602 */
5603 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005604 && ctx.word.length == 0
5605 && !ctx.word.has_quoted_part
5606 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005607 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005608 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005609 * Without check #1, interactive shell
5610 * ignores even bare <newline>,
5611 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005612 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005613 * ps2> _ <=== wrong, should be ps1
5614 * Without check #2, "cmd & <newline>"
5615 * is similarly mistreated.
5616 * (BTW, this makes "cmd & cmd"
5617 * and "cmd && cmd" non-orthogonal.
5618 * Really, ask yourself, why
5619 * "cmd && <newline>" doesn't start
5620 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005621 * The only reason is that it might be
5622 * a "cmd1 && <nl> cmd2 &" construct,
5623 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005624 */
5625 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005626 if (pi->num_cmds != 0 /* check #1 */
5627 && pi->followup != PIPE_BG /* check #2 */
5628 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005629 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005630 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005631 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005632 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005633 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005634 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005635 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005636 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5637 if (heredoc_cnt != 0)
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005638 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005639 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005640 ctx.is_assignment = MAYBE_ASSIGNMENT;
5641 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005642 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005643 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005644 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005645 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005646 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005647
5648 /* "cmd}" or "cmd }..." without semicolon or &:
5649 * } is an ordinary char in this case, even inside { cmd; }
5650 * Pathological example: { ""}; } should exec "}" cmd
5651 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005652 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005653 if (ctx.word.length != 0 /* word} */
5654 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005655 ) {
5656 goto ordinary_char;
5657 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005658 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5659 /* Generally, there should be semicolon: "cmd; }"
5660 * However, bash allows to omit it if "cmd" is
5661 * a group. Examples:
5662 * { { echo 1; } }
5663 * {(echo 1)}
5664 * { echo 0 >&2 | { echo 1; } }
5665 * { while false; do :; done }
5666 * { case a in b) ;; esac }
5667 */
5668 if (ctx.command->group)
5669 goto term_group;
5670 goto ordinary_char;
5671 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005672 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005673 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005674 goto skip_end_trigger;
5675 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005676 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005677 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005678 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005679 && (ch != ';' || heredoc_cnt == 0)
5680#if ENABLE_HUSH_CASE
5681 && (ch != ')'
5682 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005683 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005684 )
5685#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005686 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005687 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005688 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005689 }
5690 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005691 ctx.is_assignment = MAYBE_ASSIGNMENT;
5692 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005693 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005694 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005695 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005696 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005697 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005698#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005699 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005700 if (pstring)
5701 *pstring = ctx.as_string.data;
5702 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005703 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005704#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005705 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5706 /* Example: bare "{ }", "()" */
5707 G.last_exitcode = 2; /* bash compat */
5708 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005709 goto parse_error;
Denys Vlasenko39701202017-08-02 19:44:05 +02005710 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005711 if (heredoc_cnt_ptr)
5712 *heredoc_cnt_ptr = heredoc_cnt;
5713 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005714 debug_printf_parse("parse_stream return %p: "
5715 "end_trigger char found\n",
5716 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005717 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005718 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005719 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005720 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005721
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005722 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005723 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005724
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005725 /* Catch <, > before deciding whether this word is
5726 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5727 switch (ch) {
5728 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005729 redir_fd = redirect_opt_num(&ctx.word);
5730 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005731 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005732 }
5733 redir_style = REDIRECT_OVERWRITE;
5734 if (next == '>') {
5735 redir_style = REDIRECT_APPEND;
5736 ch = i_getch(input);
5737 nommu_addchr(&ctx.as_string, ch);
5738 }
5739#if 0
5740 else if (next == '(') {
5741 syntax_error(">(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005742 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005743 }
5744#endif
5745 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005746 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005747 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005748 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005749 redir_fd = redirect_opt_num(&ctx.word);
5750 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005751 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005752 }
5753 redir_style = REDIRECT_INPUT;
5754 if (next == '<') {
5755 redir_style = REDIRECT_HEREDOC;
5756 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005757 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005758 ch = i_getch(input);
5759 nommu_addchr(&ctx.as_string, ch);
5760 } else if (next == '>') {
5761 redir_style = REDIRECT_IO;
5762 ch = i_getch(input);
5763 nommu_addchr(&ctx.as_string, ch);
5764 }
5765#if 0
5766 else if (next == '(') {
5767 syntax_error("<(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005768 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005769 }
5770#endif
5771 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005772 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005773 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005774 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005775 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005776 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005777 /* note: we do not add it to &ctx.as_string */
5778/* TODO: in bash:
5779 * comment inside $() goes to the next \n, even inside quoted string (!):
5780 * cmd "$(cmd2 #comment)" - syntax error
5781 * cmd "`cmd2 #comment`" - ok
5782 * We accept both (comment ends where command subst ends, in both cases).
5783 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005784 while (1) {
5785 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005786 if (ch == '\n') {
5787 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005788 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005789 }
5790 ch = i_getch(input);
5791 if (ch == EOF)
5792 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005793 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005794 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005795 }
5796 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005797 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005798 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005799
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005800 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005801 /* check that we are not in word in "a=1 2>word b=1": */
5802 && !ctx.pending_redirect
5803 ) {
5804 /* ch is a special char and thus this word
5805 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005806 ctx.is_assignment = NOT_ASSIGNMENT;
5807 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005808 }
5809
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005810 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5811
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005812 switch (ch) {
Denys Vlasenko1b7a9b62021-06-15 16:05:57 +02005813 case_SPECIAL_VAR_SYMBOL:
Denys Vlasenko932b9972018-01-11 12:39:48 +01005814 case SPECIAL_VAR_SYMBOL:
5815 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005816 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5817 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005818 /* fall through */
5819 case '#':
5820 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005821 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005822 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005823 case '$':
Denys Vlasenkob278d822021-07-26 15:29:13 +02005824 if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
5825 continue; /* get next char */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005826 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005827 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005828 "parse_dollar returned 0 (error)\n");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005829 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005830 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005831 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005832 case '"':
5833 ctx.word.has_quoted_part = 1;
5834 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005835 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005836 insert_empty_quoted_str_marker:
5837 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005838 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5839 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005840 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005841 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005842 if (ctx.is_assignment == NOT_ASSIGNMENT)
5843 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005844 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005845 goto parse_error_exitcode1;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005846 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005847 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005848#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005849 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005850 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005851
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005852 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5853 o_addchr(&ctx.word, '`');
5854 USE_FOR_NOMMU(pos = ctx.word.length;)
5855 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005856 goto parse_error_exitcode1;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005857# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005858 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005859 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005860# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005861 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5862 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005863 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005864 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005865#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005866 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005867#if ENABLE_HUSH_CASE
5868 case_semi:
5869#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005870 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005871 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005872 }
5873 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005874#if ENABLE_HUSH_CASE
5875 /* Eat multiple semicolons, detect
5876 * whether it means something special */
5877 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005878 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005879 if (ch != ';')
5880 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005881 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005882 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005883 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005884 ctx.ctx_dsemicolon = 1;
5885 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005886 break;
5887 }
5888 }
5889#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005890 new_cmd:
5891 /* We just finished a cmd. New one may start
5892 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005893 ctx.is_assignment = MAYBE_ASSIGNMENT;
5894 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005895 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005896 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005897 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005898 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005899 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005900 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005901 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005902 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005903 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005904 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005905 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005906 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005907 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005908 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005909 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005910 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005911 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005912#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005913 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005914 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005915#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005916 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005917 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005918 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005919 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005920 } else {
5921 /* we could pick up a file descriptor choice here
5922 * with redirect_opt_num(), but bash doesn't do it.
5923 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005924 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005925 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005926 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005927 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005928#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005929 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005930 if (ctx.ctx_res_w == RES_MATCH
5931 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005932 && ctx.word.length == 0 /* not word(... */
5933 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005934 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005935 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005936 }
5937#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005938 /* fall through */
5939 case '{': {
5940 int n = parse_group(&ctx, input, ch);
5941 if (n < 0) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005942 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005943 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005944 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5945 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005946 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005947 }
Eric Andersen25f27032001-04-26 23:22:31 +00005948 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005949#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005950 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005951 goto case_semi;
5952#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005953 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005954 /* proper use of this character is caught by end_trigger:
5955 * if we see {, we call parse_group(..., end_trigger='}')
5956 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005957 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005958 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005959 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005960 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005961 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005962 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005963 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005964 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005965
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005966 parse_error_exitcode1:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005967 G.last_exitcode = 1;
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005968 parse_error:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005969 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005970 struct parse_context *pctx;
5971 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005972
5973 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005974 * Sample for finding leaks on syntax error recovery path.
5975 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005976 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005977 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005978 * while if (true | { true;}); then echo ok; fi; do break; done
5979 * 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 +00005980 */
5981 pctx = &ctx;
5982 do {
5983 /* Update pipe/command counts,
5984 * otherwise freeing may miss some */
5985 done_pipe(pctx, PIPE_SEQ);
5986 debug_printf_clean("freeing list %p from ctx %p\n",
5987 pctx->list_head, pctx);
5988 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005989 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005990 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005991#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005992 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005993#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005994 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005995 if (pctx != &ctx) {
5996 free(pctx);
5997 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005998 IF_HAS_KEYWORDS(pctx = p2;)
5999 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006000
Denys Vlasenko474cb202018-07-24 13:03:03 +02006001 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006002#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006003 if (pstring)
6004 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006005#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006006 debug_leave();
6007 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006008 }
Eric Andersen25f27032001-04-26 23:22:31 +00006009}
6010
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006011
6012/*** Execution routines ***/
6013
6014/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02006015#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02006016#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006017 expand_string_to_string(str)
6018#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02006019static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006020#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006021static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006022#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006023static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006024
6025/* expand_strvec_to_strvec() takes a list of strings, expands
6026 * all variable references within and returns a pointer to
6027 * a list of expanded strings, possibly with larger number
6028 * of strings. (Think VAR="a b"; echo $VAR).
6029 * This new list is allocated as a single malloc block.
6030 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006031 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006032 * Caller can deallocate entire list by single free(list). */
6033
Denys Vlasenko238081f2010-10-03 14:26:26 +02006034/* A horde of its helpers come first: */
6035
6036static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
6037{
6038 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02006039 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02006040
Denys Vlasenko9e800222010-10-03 14:28:04 +02006041#if ENABLE_HUSH_BRACE_EXPANSION
6042 if (c == '{' || c == '}') {
6043 /* { -> \{, } -> \} */
6044 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02006045 /* And now we want to add { or } and continue:
6046 * o_addchr(o, c);
6047 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006048 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02006049 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02006050 }
6051#endif
6052 o_addchr(o, c);
6053 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02006054 /* \z -> \\\z; \<eol> -> \\<eol> */
6055 o_addchr(o, '\\');
6056 if (len) {
6057 len--;
6058 o_addchr(o, '\\');
6059 o_addchr(o, *str++);
6060 }
6061 }
6062 }
6063}
6064
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006065/* Store given string, finalizing the word and starting new one whenever
6066 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006067 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02006068 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006069 * 1 - ended with IFS char, else 0 (this includes case of empty str).
6070 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006071static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006072{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006073 int last_is_ifs = 0;
6074
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006075 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006076 int word_len;
6077
6078 if (!*str) /* EOL - do not finalize word */
6079 break;
6080 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006081 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006082 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02006083 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006084 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02006085 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006086 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02006087 * Example: "v='\*'; echo b$v" prints "b\*"
6088 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006089 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006090 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006091 /*/ Why can't we do it easier? */
6092 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
6093 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
6094 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006095 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006096 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006097 if (!*str) /* EOL - do not finalize word */
6098 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006099 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006100
6101 /* We know str here points to at least one IFS char */
6102 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02006103 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006104 if (!*str) /* EOL - do not finalize word */
6105 break;
6106
Denys Vlasenko96786362018-04-11 16:02:58 +02006107 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
6108 && strchr(G.ifs, *str) /* the second check would fail */
6109 ) {
6110 /* This is a non-whitespace $IFS char */
6111 /* Skip it and IFS whitespace chars, start new word */
6112 str++;
6113 str += strspn(str, G.ifs_whitespace);
6114 goto new_word;
6115 }
6116
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006117 /* Start new word... but not always! */
6118 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006119 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02006120 /*
6121 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006122 * here nothing precedes the space in $v expansion,
6123 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006124 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02006125 * It's okay if this accesses the byte before first argv[]:
6126 * past call to o_save_ptr() cleared it to zero byte
6127 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006128 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02006129 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006130 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02006131 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006132 o_addchr(output, '\0');
6133 debug_print_list("expand_on_ifs", output, n);
6134 n = o_save_ptr(output, n);
6135 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006136 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006137
Denys Vlasenko168579a2018-07-19 13:45:54 +02006138 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006139 debug_print_list("expand_on_ifs[1]", output, n);
6140 return n;
6141}
6142
6143/* Helper to expand $((...)) and heredoc body. These act as if
6144 * they are in double quotes, with the exception that they are not :).
6145 * Just the rules are similar: "expand only $var and `cmd`"
6146 *
6147 * Returns malloced string.
6148 * As an optimization, we return NULL if expansion is not needed.
6149 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006150static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006151{
6152 char *exp_str;
6153 struct in_str input;
6154 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006155 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006156
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006157 cp = str;
6158 for (;;) {
6159 if (!*cp) return NULL; /* string has no special chars */
6160 if (*cp == '$') break;
6161 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006162#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006163 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006164#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006165 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006166 }
6167
6168 /* We need to expand. Example:
6169 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
6170 */
6171 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006172 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01006173//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006174 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02006175 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02006176 EXP_FLAG_ESC_GLOB_CHARS,
6177 /*unbackslash:*/ 1
6178 );
6179 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006180 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006181 return exp_str;
6182}
6183
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006184static const char *first_special_char_in_vararg(const char *cp)
6185{
6186 for (;;) {
6187 if (!*cp) return NULL; /* string has no special chars */
6188 if (*cp == '$') return cp;
6189 if (*cp == '\\') return cp;
6190 if (*cp == '\'') return cp;
6191 if (*cp == '"') return cp;
6192#if ENABLE_HUSH_TICK
6193 if (*cp == '`') return cp;
6194#endif
6195 /* dquoted "${x:+ARG}" should not glob, therefore
6196 * '*' et al require some non-literal processing: */
6197 if (*cp == '*') return cp;
6198 if (*cp == '?') return cp;
6199 if (*cp == '[') return cp;
6200 cp++;
6201 }
6202}
6203
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006204/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
6205 * These can contain single- and double-quoted strings,
6206 * and treated as if the ARG string is initially unquoted. IOW:
6207 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
6208 * a dquoted string: "${var#"zz"}"), the difference only comes later
6209 * (word splitting and globbing of the ${var...} result).
6210 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006211#if !BASH_PATTERN_SUBST
6212#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
6213 encode_then_expand_vararg(str, handle_squotes)
6214#endif
6215static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6216{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006217#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006218 const int do_unbackslash = 0;
6219#endif
6220 char *exp_str;
6221 struct in_str input;
6222 o_string dest = NULL_O_STRING;
6223
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006224 if (!first_special_char_in_vararg(str)) {
6225 /* string has no special chars */
6226 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006227 }
6228
Denys Vlasenkob762c782018-07-17 14:21:38 +02006229 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006230 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006231 exp_str = NULL;
6232
6233 for (;;) {
6234 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006235
6236 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006237 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6238 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006239
6240 if (!dest.o_expflags) {
6241 if (ch == EOF)
6242 break;
6243 if (handle_squotes && ch == '\'') {
6244 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006245 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006246 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006247 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006248 }
6249 if (ch == EOF) {
6250 syntax_error_unterm_ch('"');
6251 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006252 }
6253 if (ch == '"') {
6254 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6255 continue;
6256 }
6257 if (ch == '\\') {
6258 ch = i_getch(&input);
6259 if (ch == EOF) {
6260//example? error message? syntax_error_unterm_ch('"');
6261 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6262 goto ret;
6263 }
6264 o_addqchr(&dest, ch);
6265 continue;
6266 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006267 if (ch == '$') {
Denys Vlasenkob278d822021-07-26 15:29:13 +02006268 if (parse_dollar_squote(NULL, &dest, &input))
6269 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006270 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6271 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6272 goto ret;
6273 }
6274 continue;
6275 }
6276#if ENABLE_HUSH_TICK
6277 if (ch == '`') {
6278 //unsigned pos = dest->length;
6279 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6280 o_addchr(&dest, 0x80 | '`');
6281 if (!add_till_backquote(&dest, &input,
6282 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6283 )
6284 ) {
6285 goto ret; /* error */
6286 }
6287 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6288 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6289 continue;
6290 }
6291#endif
6292 o_addQchr(&dest, ch);
6293 } /* for (;;) */
6294
6295 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6296 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006297 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6298 do_unbackslash
6299 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006300 ret:
6301 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006302 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006303 return exp_str;
6304}
6305
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006306/* Expanding ARG in ${var+ARG}, ${var-ARG}
6307 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006308static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006309 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006310{
6311 struct in_str input;
6312 o_string dest = NULL_O_STRING;
6313
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006314 if (!first_special_char_in_vararg(str)
6315 && '\0' == str[strcspn(str, G.ifs)]
6316 ) {
6317 /* string has no special chars
6318 * && string has no $IFS chars
6319 */
Denys Vlasenko9e0adb92019-05-15 13:39:19 +02006320 if (dquoted) {
6321 /* Prints 1 (quoted expansion is a "" word, not nothing):
6322 * set -- "${notexist-}"; echo $#
6323 */
6324 output->has_quoted_part = 1;
6325 }
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006326 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006327 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006328
Denys Vlasenko294eb462018-07-20 16:18:59 +02006329 setup_string_in_str(&input, str);
6330
6331 for (;;) {
6332 int ch;
6333
6334 ch = i_getch(&input);
6335 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6336 __func__, ch, ch, dest.o_expflags);
6337
6338 if (!dest.o_expflags) {
6339 if (ch == EOF)
6340 break;
6341 if (!dquoted && strchr(G.ifs, ch)) {
6342 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6343 * do not assume we are at the start of the word (PREFIX above).
6344 */
6345 if (dest.data) {
6346 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006347 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006348 o_addchr(output, '\0');
6349 n = o_save_ptr(output, n); /* create next word */
6350 } else
6351 if (output->length != o_get_last_ptr(output, n)
6352 || output->has_quoted_part
6353 ) {
6354 /* For these cases:
6355 * f() { for i; do echo "|$i|"; done; }; x=x
6356 * f a${x:+ }b # 1st condition
6357 * |a|
6358 * |b|
6359 * f ""${x:+ }b # 2nd condition
6360 * ||
6361 * |b|
6362 */
6363 o_addchr(output, '\0');
6364 n = o_save_ptr(output, n); /* create next word */
6365 }
6366 continue;
6367 }
6368 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006369 if (!add_till_single_quote_dquoted(&dest, &input))
6370 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006371 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6372 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006373 continue;
6374 }
6375 }
6376 if (ch == EOF) {
6377 syntax_error_unterm_ch('"');
6378 goto ret; /* error */
6379 }
6380 if (ch == '"') {
6381 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006382 if (dest.o_expflags) {
6383 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6384 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6385 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006386 continue;
6387 }
6388 if (ch == '\\') {
6389 ch = i_getch(&input);
6390 if (ch == EOF) {
6391//example? error message? syntax_error_unterm_ch('"');
6392 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6393 goto ret;
6394 }
6395 o_addqchr(&dest, ch);
6396 continue;
6397 }
6398 if (ch == '$') {
6399 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6400 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6401 goto ret;
6402 }
6403 continue;
6404 }
6405#if ENABLE_HUSH_TICK
6406 if (ch == '`') {
6407 //unsigned pos = dest->length;
6408 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6409 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6410 if (!add_till_backquote(&dest, &input,
6411 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6412 )
6413 ) {
6414 goto ret; /* error */
6415 }
6416 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6417 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6418 continue;
6419 }
6420#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006421 if (dquoted) {
6422 /* Always glob-protect if in dquotes:
6423 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6424 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6425 */
6426 o_addqchr(&dest, ch);
6427 } else {
6428 /* Glob-protect only if char is quoted:
6429 * x=x; echo ${x:+/bin/c*} - prints many filenames
6430 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6431 */
6432 o_addQchr(&dest, ch);
6433 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006434 } /* for (;;) */
6435
6436 if (dest.data) {
6437 n = expand_vars_to_list(output, n, dest.data);
6438 }
6439 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006440 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006441 return n;
6442}
6443
Denys Vlasenko0b883582016-12-23 16:49:07 +01006444#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006445static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006446{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006447 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006448 arith_t res;
6449 char *exp_str;
6450
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006451 math_state.lookupvar = get_local_var_value;
6452 math_state.setvar = set_local_var_from_halves;
6453 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006454 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006455 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006456 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006457 if (errmsg_p)
6458 *errmsg_p = math_state.errmsg;
6459 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006460 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006461 return res;
6462}
6463#endif
6464
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006465#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006466/* ${var/[/]pattern[/repl]} helpers */
6467static char *strstr_pattern(char *val, const char *pattern, int *size)
6468{
Denys Vlasenko49cc3ca2021-07-27 17:53:55 +02006469 if (!strpbrk(pattern, "*?[\\")) {
6470 /* Optimization for trivial patterns.
6471 * Testcase for very slow replace (performs about 22k replaces):
6472 * x=::::::::::::::::::::::
6473 * x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;echo ${#x}
6474 * echo "${x//:/|}"
6475 */
6476 char *found = strstr(val, pattern);
6477 if (found)
6478 *size = strlen(pattern);
6479 return found;
6480 }
6481
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006482 while (1) {
6483 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6484 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6485 if (end) {
6486 *size = end - val;
6487 return val;
6488 }
6489 if (*val == '\0')
6490 return NULL;
6491 /* Optimization: if "*pat" did not match the start of "string",
6492 * we know that "tring", "ring" etc will not match too:
6493 */
6494 if (pattern[0] == '*')
6495 return NULL;
6496 val++;
6497 }
6498}
6499static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6500{
6501 char *result = NULL;
6502 unsigned res_len = 0;
6503 unsigned repl_len = strlen(repl);
6504
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006505 /* Null pattern never matches, including if "var" is empty */
6506 if (!pattern[0])
6507 return result; /* NULL, no replaces happened */
6508
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006509 while (1) {
6510 int size;
6511 char *s = strstr_pattern(val, pattern, &size);
6512 if (!s)
6513 break;
6514
6515 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006516 strcpy(mempcpy(result + res_len, val, s - val), repl);
6517 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006518 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6519
6520 val = s + size;
6521 if (exp_op == '/')
6522 break;
6523 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006524 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006525 result = xrealloc(result, res_len + strlen(val) + 1);
6526 strcpy(result + res_len, val);
6527 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6528 }
6529 debug_printf_varexp("result:'%s'\n", result);
6530 return result;
6531}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006532#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006533
Denys Vlasenko168579a2018-07-19 13:45:54 +02006534static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006535 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006536{
6537 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6538 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6539 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6540 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006541 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006542 } else { /* quoted "$VAR" */
6543 output->has_quoted_part = 1;
6544 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6545 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6546 if (val && val[0])
6547 o_addQstr(output, val);
6548 }
6549 return n;
6550}
6551
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006552/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006553 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006554static NOINLINE int expand_one_var(o_string *output, int n,
6555 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006556{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006557 const char *val;
6558 char *to_be_freed;
6559 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006560 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006561 char exp_op;
6562 char exp_save = exp_save; /* for compiler */
6563 char *exp_saveptr; /* points to expansion operator */
6564 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006565 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006566
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006567 val = NULL;
6568 to_be_freed = NULL;
6569 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006570 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006571 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006572 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006573 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006574 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006575 exp_op = 0;
6576
Denys Vlasenkob762c782018-07-17 14:21:38 +02006577 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006578 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6579 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6580 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006581 ) {
6582 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006583 var++;
6584 exp_op = 'L';
6585 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006586 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006587 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006588 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006589 ) {
6590 /* ${?:0}, ${#[:]%0} etc */
6591 exp_saveptr = var + 1;
6592 } else {
6593 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6594 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6595 }
6596 exp_op = exp_save = *exp_saveptr;
6597 if (exp_op) {
6598 exp_word = exp_saveptr + 1;
6599 if (exp_op == ':') {
6600 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006601//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006602 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006603 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006604 ) {
6605 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6606 exp_op = ':';
6607 exp_word--;
6608 }
6609 }
6610 *exp_saveptr = '\0';
6611 } /* else: it's not an expansion op, but bare ${var} */
6612 }
6613
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006614 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006615 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006616 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006617 int nn = xatoi_positive(var);
6618 if (nn < G.global_argc)
6619 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006620 /* else val remains NULL: $N with too big N */
6621 } else {
6622 switch (var[0]) {
6623 case '$': /* pid */
6624 val = utoa(G.root_pid);
6625 break;
6626 case '!': /* bg pid */
6627 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6628 break;
6629 case '?': /* exitcode */
6630 val = utoa(G.last_exitcode);
6631 break;
6632 case '#': /* argc */
6633 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6634 break;
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006635 case '-': { /* active options */
6636 /* Check set_mode() to see what option chars we support */
6637 char *cp;
6638 val = cp = G.optstring_buf;
6639 if (G.o_opt[OPT_O_ERREXIT])
6640 *cp++ = 'e';
6641 if (G_interactive_fd)
6642 *cp++ = 'i';
6643 if (G_x_mode)
6644 *cp++ = 'x';
6645 /* If G.o_opt[OPT_O_NOEXEC] is true,
6646 * commands read but are not executed,
6647 * so $- can not execute too, 'n' is never seen in $-.
6648 */
Denys Vlasenkof3634582019-06-03 12:21:04 +02006649 if (G.opt_c)
6650 *cp++ = 'c';
Denys Vlasenkod8740b22019-05-19 19:11:21 +02006651 if (G.opt_s)
6652 *cp++ = 's';
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006653 *cp = '\0';
6654 break;
6655 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006656 default:
6657 val = get_local_var_value(var);
6658 }
6659 }
6660
6661 /* Handle any expansions */
6662 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006663 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006664 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006665 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006666 debug_printf_expand("%s\n", val);
6667 } else if (exp_op) {
6668 if (exp_op == '%' || exp_op == '#') {
6669 /* Standard-mandated substring removal ops:
6670 * ${parameter%word} - remove smallest suffix pattern
6671 * ${parameter%%word} - remove largest suffix pattern
6672 * ${parameter#word} - remove smallest prefix pattern
6673 * ${parameter##word} - remove largest prefix pattern
6674 *
6675 * Word is expanded to produce a glob pattern.
6676 * Then var's value is matched to it and matching part removed.
6677 */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006678 /* bash compat: if x is "" and no shrinking of it is possible,
6679 * inner ${...} is not evaluated. Example:
6680 * unset b; : ${a%${b=B}}; echo $b
6681 * assignment b=B only happens if $a is not "".
6682 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006683 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006684 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006685 char *exp_exp_word;
6686 char *loc;
6687 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006688 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006689 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006690 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006691 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006692 if (exp_exp_word)
6693 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006694 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6695 /*
6696 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006697 * G.global_argv and results of utoa and get_local_var_value
6698 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006699 * scan_and_match momentarily stores NULs there.
6700 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006701 t = (char*)val;
6702 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006703 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 +02006704 free(exp_exp_word);
6705 if (loc) { /* match was found */
6706 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006707 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006708 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006709 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006710 }
6711 }
6712 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006713#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006714 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006715 /* It's ${var/[/]pattern[/repl]} thing.
6716 * Note that in encoded form it has TWO parts:
6717 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006718 * and if // is used, it is encoded as \:
6719 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006720 */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006721 /* bash compat: if var is "", both pattern and repl
6722 * are still evaluated, if it is unset, then not:
6723 * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
6724 * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
6725 */
6726 if (val /*&& val[0]*/) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006727 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006728 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006729 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006730 * >az >bz
6731 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6732 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6733 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6734 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006735 * (note that a*z _pattern_ is never globbed!)
6736 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006737 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006738 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006739 if (!pattern)
6740 pattern = xstrdup(exp_word);
6741 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6742 *p++ = SPECIAL_VAR_SYMBOL;
6743 exp_word = p;
6744 p = strchr(p, SPECIAL_VAR_SYMBOL);
6745 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006746 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006747 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6748 /* HACK ALERT. We depend here on the fact that
6749 * G.global_argv and results of utoa and get_local_var_value
6750 * are actually in writable memory:
6751 * replace_pattern momentarily stores NULs there. */
6752 t = (char*)val;
6753 to_be_freed = replace_pattern(t,
6754 pattern,
6755 (repl ? repl : exp_word),
6756 exp_op);
6757 if (to_be_freed) /* at least one replace happened */
6758 val = to_be_freed;
6759 free(pattern);
6760 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006761 } else {
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006762 /* Unset variable always gives nothing */
6763 // a=; echo ${a/*/w} # "w"
6764 // unset a; echo ${a/*/w} # ""
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006765 /* Just skip "replace" part */
6766 *p++ = SPECIAL_VAR_SYMBOL;
6767 p = strchr(p, SPECIAL_VAR_SYMBOL);
6768 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006769 }
6770 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006771#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006772 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006773#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006774 /* It's ${var:N[:M]} bashism.
6775 * Note that in encoded form it has TWO parts:
6776 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6777 */
6778 arith_t beg, len;
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006779 unsigned vallen;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006780 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006781
Denys Vlasenko063847d2010-09-15 13:33:02 +02006782 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6783 if (errmsg)
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006784 goto empty_result;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006785 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6786 *p++ = SPECIAL_VAR_SYMBOL;
6787 exp_word = p;
6788 p = strchr(p, SPECIAL_VAR_SYMBOL);
6789 *p = '\0';
Denys Vlasenkoa7b52d22020-12-23 12:38:03 +01006790 vallen = val ? strlen(val) : 0;
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006791 if (beg < 0) {
6792 /* negative beg counts from the end */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006793 beg = (arith_t)vallen + beg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006794 }
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006795 /* If expansion will be empty, do not even evaluate len */
6796 if (!val || beg < 0 || beg > vallen) {
6797 /* Why > vallen, not >=? bash:
6798 * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
6799 * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
6800 */
6801 goto empty_result;
6802 }
6803 len = expand_and_evaluate_arith(exp_word, &errmsg);
6804 if (errmsg)
6805 goto empty_result;
6806 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006807 debug_printf_varexp("from val:'%s'\n", val);
6808 if (len < 0) {
6809 /* in bash, len=-n means strlen()-n */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006810 len = (arith_t)vallen - beg + len;
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006811 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006812 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006813 }
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006814 if (len <= 0 || !val /*|| beg >= vallen*/) {
6815 empty_result:
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006816 val = NULL;
6817 } else {
6818 /* Paranoia. What if user entered 9999999999999
6819 * which fits in arith_t but not int? */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006820 if (len > INT_MAX)
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006821 len = INT_MAX;
6822 val = to_be_freed = xstrndup(val + beg, len);
6823 }
6824 debug_printf_varexp("val:'%s'\n", val);
6825#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006826 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006827 val = NULL;
6828#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006829 } else { /* one of "-=+?" */
6830 /* Standard-mandated substitution ops:
6831 * ${var?word} - indicate error if unset
6832 * If var is unset, word (or a message indicating it is unset
6833 * if word is null) is written to standard error
6834 * and the shell exits with a non-zero exit status.
6835 * Otherwise, the value of var is substituted.
6836 * ${var-word} - use default value
6837 * If var is unset, word is substituted.
6838 * ${var=word} - assign and use default value
6839 * If var is unset, word is assigned to var.
6840 * In all cases, final value of var is substituted.
6841 * ${var+word} - use alternative value
6842 * If var is unset, null is substituted.
6843 * Otherwise, word is substituted.
6844 *
6845 * Word is subjected to tilde expansion, parameter expansion,
6846 * command substitution, and arithmetic expansion.
6847 * If word is not needed, it is not expanded.
6848 *
6849 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6850 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006851 *
6852 * Word-splitting and single quote behavior:
6853 *
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006854 * $ f() { for i; do echo "|$i|"; done; }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006855 *
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006856 * $ x=; f ${x:?'x y' z}; echo $?
6857 * bash: x: x y z # neither f nor "echo $?" executes
6858 * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006859 * $ x=; f "${x:?'x y' z}"
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006860 * bash: x: x y z # dash prints: dash: x: 'x y' z
Denys Vlasenko294eb462018-07-20 16:18:59 +02006861 *
6862 * $ x=; f ${x:='x y' z}
6863 * |x|
6864 * |y|
6865 * |z|
6866 * $ x=; f "${x:='x y' z}"
6867 * |'x y' z|
6868 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006869 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006870 * |x y|
6871 * |z|
6872 * $ x=x; f "${x:+'x y' z}"
6873 * |'x y' z|
6874 *
6875 * $ x=; f ${x:-'x y' z}
6876 * |x y|
6877 * |z|
6878 * $ x=; f "${x:-'x y' z}"
6879 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006880 */
6881 int use_word = (!val || ((exp_save == ':') && !val[0]));
6882 if (exp_op == '+')
6883 use_word = !use_word;
6884 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6885 (exp_save == ':') ? "true" : "false", use_word);
6886 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006887 if (exp_op == '+' || exp_op == '-') {
6888 /* ${var+word} - use alternative value */
6889 /* ${var-word} - use default value */
6890 n = encode_then_append_var_plusminus(output, n, exp_word,
6891 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006892 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006893 val = NULL;
6894 } else {
6895 /* ${var?word} - indicate error if unset */
6896 /* ${var=word} - assign and use default value */
6897 to_be_freed = encode_then_expand_vararg(exp_word,
6898 /*handle_squotes:*/ !(arg0 & 0x80),
6899 /*unbackslash:*/ 0
6900 );
6901 if (to_be_freed)
6902 exp_word = to_be_freed;
6903 if (exp_op == '?') {
6904 /* mimic bash message */
6905 msg_and_die_if_script("%s: %s",
6906 var,
6907 exp_word[0]
6908 ? exp_word
6909 : "parameter null or not set"
6910 /* ash has more specific messages, a-la: */
6911 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6912 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006913//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006914//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006915// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6916// bash: x: x y z
6917// $
6918// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006919 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006920 val = exp_word;
6921 }
6922 if (exp_op == '=') {
6923 /* ${var=[word]} or ${var:=[word]} */
6924 if (isdigit(var[0]) || var[0] == '#') {
6925 /* mimic bash message */
6926 msg_and_die_if_script("$%s: cannot assign in this way", var);
6927 val = NULL;
6928 } else {
6929 char *new_var = xasprintf("%s=%s", var, val);
6930 set_local_var(new_var, /*flag:*/ 0);
6931 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006932 }
6933 }
6934 }
6935 } /* one of "-=+?" */
6936
6937 *exp_saveptr = exp_save;
6938 } /* if (exp_op) */
6939
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006940 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006941 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006942
Denys Vlasenko168579a2018-07-19 13:45:54 +02006943 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006944
6945 free(to_be_freed);
6946 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006947}
6948
6949/* Expand all variable references in given string, adding words to list[]
6950 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6951 * to be filled). This routine is extremely tricky: has to deal with
6952 * variables/parameters with whitespace, $* and $@, and constructs like
6953 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006954static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006955{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006956 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006957 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006958 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006959 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006960 char *p;
6961
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006962 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6963 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006964 debug_print_list("expand_vars_to_list[0]", output, n);
6965
6966 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6967 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006968#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006969 char arith_buf[sizeof(arith_t)*3 + 2];
6970#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006971
Denys Vlasenko168579a2018-07-19 13:45:54 +02006972 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006973 o_addchr(output, '\0');
6974 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006975 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006976 }
6977
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006978 o_addblock(output, arg, p - arg);
6979 debug_print_list("expand_vars_to_list[1]", output, n);
6980 arg = ++p;
6981 p = strchr(p, SPECIAL_VAR_SYMBOL);
6982
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006983 /* Fetch special var name (if it is indeed one of them)
6984 * and quote bit, force the bit on if singleword expansion -
6985 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006986 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006987
6988 /* Is this variable quoted and thus expansion can't be null?
6989 * "$@" is special. Even if quoted, it can still
6990 * expand to nothing (not even an empty string),
6991 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006992 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006993 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006994
6995 switch (first_ch & 0x7f) {
6996 /* Highest bit in first_ch indicates that var is double-quoted */
6997 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006998 case '@': {
6999 int i;
7000 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007001 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02007002 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007003 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007004 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007005 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02007006 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007007 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
7008 if (G.global_argv[i++][0] && G.global_argv[i]) {
7009 /* this argv[] is not empty and not last:
7010 * put terminating NUL, start new word */
7011 o_addchr(output, '\0');
7012 debug_print_list("expand_vars_to_list[2]", output, n);
7013 n = o_save_ptr(output, n);
7014 debug_print_list("expand_vars_to_list[3]", output, n);
7015 }
7016 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007017 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007018 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007019 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02007020 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007021 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007022 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007023 while (1) {
7024 o_addQstr(output, G.global_argv[i]);
7025 if (++i >= G.global_argc)
7026 break;
7027 o_addchr(output, '\0');
7028 debug_print_list("expand_vars_to_list[4]", output, n);
7029 n = o_save_ptr(output, n);
7030 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007031 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007032 while (1) {
7033 o_addQstr(output, G.global_argv[i]);
7034 if (!G.global_argv[++i])
7035 break;
7036 if (G.ifs[0])
7037 o_addchr(output, G.ifs[0]);
7038 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02007039 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007040 }
7041 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02007042 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007043 case SPECIAL_VAR_SYMBOL: {
7044 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007045 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02007046 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007047 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007048 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007049 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007050 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01007051 case SPECIAL_VAR_QUOTED_SVS:
7052 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007053 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02007054 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01007055 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01007056 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007057#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007058 case '`': {
7059 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02007060 o_string subst_result = NULL_O_STRING;
7061
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007062 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007063 arg++;
7064 /* Can't just stuff it into output o_string,
7065 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02007066 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007067 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
7068 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02007069 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007070 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02007071 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02007072 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007073 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02007074 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007075#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01007076#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007077 case '+': {
7078 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007079 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007080
7081 arg++; /* skip '+' */
7082 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
7083 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02007084 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02007085 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
7086 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01007087 if (res < 0
7088 && first_ch == (char)('+'|0x80)
7089 /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
7090 ) {
7091 /* Quoted negative ariths, like filename[0"$((-9))"],
7092 * should not be interpreted as glob ranges.
7093 * Convert leading '-' to '\-':
7094 */
7095 o_grow_by(output, 1);
7096 output->data[output->length++] = '\\';
7097 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007098 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007099 break;
7100 }
7101#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02007102 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007103 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02007104 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02007105 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007106 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
7107
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02007108 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
7109 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007110 if (*p != SPECIAL_VAR_SYMBOL)
7111 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007112 arg = ++p;
7113 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
7114
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02007115 if (*arg) {
7116 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02007117 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02007118 o_addchr(output, '\0');
7119 n = o_save_ptr(output, n);
7120 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007121 debug_print_list("expand_vars_to_list[a]", output, n);
7122 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02007123 * if needed (much earlier), do not use o_addQstr here!
7124 */
7125 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007126 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02007127 } else
7128 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02007129 && !(cant_be_null & 0x80) /* and all vars were not quoted */
7130 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007131 ) {
7132 n--;
7133 /* allow to reuse list[n] later without re-growth */
7134 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007135 }
7136
7137 return n;
7138}
7139
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007140static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007141{
7142 int n;
7143 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007144 o_string output = NULL_O_STRING;
7145
Denys Vlasenko95d48f22010-09-08 13:58:55 +02007146 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007147
7148 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02007149 for (;;) {
7150 /* go to next list[n] */
7151 output.ended_in_ifs = 0;
7152 n = o_save_ptr(&output, n);
7153
7154 if (!*argv)
7155 break;
7156
7157 /* expand argv[i] */
7158 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02007159 /* if (!output->has_empty_slot) -- need this?? */
7160 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007161 }
7162 debug_print_list("expand_variables", &output, n);
7163
7164 /* output.data (malloced in one block) gets returned in "list" */
7165 list = o_finalize_list(&output, n);
7166 debug_print_strings("expand_variables[1]", list);
7167 return list;
7168}
7169
7170static char **expand_strvec_to_strvec(char **argv)
7171{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007172 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007173}
7174
Denys Vlasenkod2241f52020-10-31 03:34:07 +01007175#if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007176static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
7177{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007178 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007179}
7180#endif
7181
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007182/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007183 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007184 *
7185 * NB: should NOT do globbing!
7186 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
7187 */
Denys Vlasenko34179952018-04-11 13:47:59 +02007188static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007189{
Denys Vlasenko637982f2017-07-06 01:52:23 +02007190#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007191 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02007192 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007193#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007194 char *argv[2], **list;
7195
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007196 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007197 /* This is generally an optimization, but it also
7198 * handles "", which otherwise trips over !list[0] check below.
7199 * (is this ever happens that we actually get str="" here?)
7200 */
7201 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
7202 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007203 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007204 return xstrdup(str);
7205 }
7206
7207 argv[0] = (char*)str;
7208 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02007209 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02007210 if (!list[0]) {
7211 /* Example where it happens:
7212 * x=; echo ${x:-"$@"}
7213 */
7214 ((char*)list)[0] = '\0';
7215 } else {
7216 if (HUSH_DEBUG)
7217 if (list[1])
James Byrne69374872019-07-02 11:35:03 +02007218 bb_simple_error_msg_and_die("BUG in varexp2");
Denys Vlasenko2e711012018-07-18 16:02:25 +02007219 /* actually, just move string 2*sizeof(char*) bytes back */
7220 overlapping_strcpy((char*)list, list[0]);
7221 if (do_unbackslash)
7222 unbackslash((char*)list);
7223 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007224 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007225 return (char*)list;
7226}
7227
Denys Vlasenkoabf75562018-04-02 17:25:18 +02007228#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007229static char* expand_strvec_to_string(char **argv)
7230{
7231 char **list;
7232
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007233 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007234 /* Convert all NULs to spaces */
7235 if (list[0]) {
7236 int n = 1;
7237 while (list[n]) {
7238 if (HUSH_DEBUG)
7239 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
7240 bb_error_msg_and_die("BUG in varexp3");
7241 /* bash uses ' ' regardless of $IFS contents */
7242 list[n][-1] = ' ';
7243 n++;
7244 }
7245 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02007246 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007247 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
7248 return (char*)list;
7249}
Denys Vlasenko1f191122018-01-11 13:17:30 +01007250#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007251
7252static char **expand_assignments(char **argv, int count)
7253{
7254 int i;
7255 char **p;
7256
7257 G.expanded_assignments = p = NULL;
7258 /* Expand assignments into one string each */
7259 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02007260 p = add_string_to_strings(p,
7261 expand_string_to_string(argv[i],
7262 EXP_FLAG_ESC_GLOB_CHARS,
7263 /*unbackslash:*/ 1
7264 )
7265 );
7266 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007267 }
7268 G.expanded_assignments = NULL;
7269 return p;
7270}
7271
7272
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007273static void switch_off_special_sigs(unsigned mask)
7274{
7275 unsigned sig = 0;
7276 while ((mask >>= 1) != 0) {
7277 sig++;
7278 if (!(mask & 1))
7279 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007280#if ENABLE_HUSH_TRAP
7281 if (G_traps) {
7282 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007283 /* trap is '', has to remain SIG_IGN */
7284 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007285 free(G_traps[sig]);
7286 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007287 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007288#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007289 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007290 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007291 }
7292}
7293
Denys Vlasenkob347df92011-08-09 22:49:15 +02007294#if BB_MMU
7295/* never called */
7296void re_execute_shell(char ***to_free, const char *s,
7297 char *g_argv0, char **g_argv,
7298 char **builtin_argv) NORETURN;
7299
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007300static void reset_traps_to_defaults(void)
7301{
7302 /* This function is always called in a child shell
7303 * after fork (not vfork, NOMMU doesn't use this function).
7304 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007305 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007306 unsigned mask;
7307
7308 /* Child shells are not interactive.
7309 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7310 * Testcase: (while :; do :; done) + ^Z should background.
7311 * Same goes for SIGTERM, SIGHUP, SIGINT.
7312 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007313 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007314 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007315 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007316
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007317 /* Switch off special sigs */
7318 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007319# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007320 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007321# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007322 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007323 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7324 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007325
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007326# if ENABLE_HUSH_TRAP
7327 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007328 return;
7329
7330 /* Reset all sigs to default except ones with empty traps */
7331 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007332 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007333 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007334 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007335 continue; /* empty trap: has to remain SIG_IGN */
7336 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007337 free(G_traps[sig]);
7338 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007339 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007340 if (sig == 0)
7341 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007342 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007343 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007344# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007345}
7346
7347#else /* !BB_MMU */
7348
7349static void re_execute_shell(char ***to_free, const char *s,
7350 char *g_argv0, char **g_argv,
7351 char **builtin_argv) NORETURN;
7352static void re_execute_shell(char ***to_free, const char *s,
7353 char *g_argv0, char **g_argv,
7354 char **builtin_argv)
7355{
7356# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7357 /* delims + 2 * (number of bytes in printed hex numbers) */
7358 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7359 char *heredoc_argv[4];
7360 struct variable *cur;
7361# if ENABLE_HUSH_FUNCTIONS
7362 struct function *funcp;
7363# endif
7364 char **argv, **pp;
7365 unsigned cnt;
7366 unsigned long long empty_trap_mask;
7367
7368 if (!g_argv0) { /* heredoc */
7369 argv = heredoc_argv;
7370 argv[0] = (char *) G.argv0_for_re_execing;
7371 argv[1] = (char *) "-<";
7372 argv[2] = (char *) s;
7373 argv[3] = NULL;
7374 pp = &argv[3]; /* used as pointer to empty environment */
7375 goto do_exec;
7376 }
7377
7378 cnt = 0;
7379 pp = builtin_argv;
7380 if (pp) while (*pp++)
7381 cnt++;
7382
7383 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007384 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007385 int sig;
7386 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007387 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007388 empty_trap_mask |= 1LL << sig;
7389 }
7390 }
7391
7392 sprintf(param_buf, NOMMU_HACK_FMT
7393 , (unsigned) G.root_pid
7394 , (unsigned) G.root_ppid
7395 , (unsigned) G.last_bg_pid
7396 , (unsigned) G.last_exitcode
7397 , cnt
7398 , empty_trap_mask
7399 IF_HUSH_LOOPS(, G.depth_of_loop)
7400 );
7401# undef NOMMU_HACK_FMT
7402 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7403 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7404 */
7405 cnt += 6;
7406 for (cur = G.top_var; cur; cur = cur->next) {
7407 if (!cur->flg_export || cur->flg_read_only)
7408 cnt += 2;
7409 }
7410# if ENABLE_HUSH_FUNCTIONS
7411 for (funcp = G.top_func; funcp; funcp = funcp->next)
7412 cnt += 3;
7413# endif
7414 pp = g_argv;
7415 while (*pp++)
7416 cnt++;
7417 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7418 *pp++ = (char *) G.argv0_for_re_execing;
7419 *pp++ = param_buf;
7420 for (cur = G.top_var; cur; cur = cur->next) {
7421 if (strcmp(cur->varstr, hush_version_str) == 0)
7422 continue;
7423 if (cur->flg_read_only) {
7424 *pp++ = (char *) "-R";
7425 *pp++ = cur->varstr;
7426 } else if (!cur->flg_export) {
7427 *pp++ = (char *) "-V";
7428 *pp++ = cur->varstr;
7429 }
7430 }
7431# if ENABLE_HUSH_FUNCTIONS
7432 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7433 *pp++ = (char *) "-F";
7434 *pp++ = funcp->name;
7435 *pp++ = funcp->body_as_string;
7436 }
7437# endif
7438 /* We can pass activated traps here. Say, -Tnn:trap_string
7439 *
7440 * However, POSIX says that subshells reset signals with traps
7441 * to SIG_DFL.
7442 * I tested bash-3.2 and it not only does that with true subshells
7443 * of the form ( list ), but with any forked children shells.
7444 * I set trap "echo W" WINCH; and then tried:
7445 *
7446 * { echo 1; sleep 20; echo 2; } &
7447 * while true; do echo 1; sleep 20; echo 2; break; done &
7448 * true | { echo 1; sleep 20; echo 2; } | cat
7449 *
7450 * In all these cases sending SIGWINCH to the child shell
7451 * did not run the trap. If I add trap "echo V" WINCH;
7452 * _inside_ group (just before echo 1), it works.
7453 *
7454 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007455 */
7456 *pp++ = (char *) "-c";
7457 *pp++ = (char *) s;
7458 if (builtin_argv) {
7459 while (*++builtin_argv)
7460 *pp++ = *builtin_argv;
7461 *pp++ = (char *) "";
7462 }
7463 *pp++ = g_argv0;
7464 while (*g_argv)
7465 *pp++ = *g_argv++;
7466 /* *pp = NULL; - is already there */
7467 pp = environ;
7468
7469 do_exec:
7470 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007471 /* Don't propagate SIG_IGN to the child */
7472 if (SPECIAL_JOBSTOP_SIGS != 0)
7473 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007474 execve(bb_busybox_exec_path, argv, pp);
7475 /* Fallback. Useful for init=/bin/hush usage etc */
7476 if (argv[0][0] == '/')
7477 execve(argv[0], argv, pp);
7478 xfunc_error_retval = 127;
James Byrne69374872019-07-02 11:35:03 +02007479 bb_simple_error_msg_and_die("can't re-execute the shell");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007480}
7481#endif /* !BB_MMU */
7482
7483
7484static int run_and_free_list(struct pipe *pi);
7485
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007486/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007487 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7488 * end_trigger controls how often we stop parsing
7489 * NUL: parse all, execute, return
7490 * ';': parse till ';' or newline, execute, repeat till EOF
7491 */
7492static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007493{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007494 /* Why we need empty flag?
7495 * An obscure corner case "false; ``; echo $?":
7496 * empty command in `` should still set $? to 0.
7497 * But we can't just set $? to 0 at the start,
7498 * this breaks "false; echo `echo $?`" case.
7499 */
7500 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007501 while (1) {
7502 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007503
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007504#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007505 if (end_trigger == ';') {
7506 G.promptmode = 0; /* PS1 */
7507 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7508 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007509#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007510 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007511 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7512 /* If we are in "big" script
7513 * (not in `cmd` or something similar)...
7514 */
7515 if (pipe_list == ERR_PTR && end_trigger == ';') {
7516 /* Discard cached input (rest of line) */
7517 int ch = inp->last_char;
7518 while (ch != EOF && ch != '\n') {
7519 //bb_error_msg("Discarded:'%c'", ch);
7520 ch = i_getch(inp);
7521 }
7522 /* Force prompt */
7523 inp->p = NULL;
7524 /* This stream isn't empty */
7525 empty = 0;
7526 continue;
7527 }
7528 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007529 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007530 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007531 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007532 debug_print_tree(pipe_list, 0);
7533 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7534 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007535 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007536 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007537 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007538 }
Eric Andersen25f27032001-04-26 23:22:31 +00007539}
7540
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007541static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007542{
7543 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007544 //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007545
Eric Andersen25f27032001-04-26 23:22:31 +00007546 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007547 parse_and_run_stream(&input, '\0');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007548 //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007549}
7550
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007551static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007552{
Eric Andersen25f27032001-04-26 23:22:31 +00007553 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007554 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007555
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007556 IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007557 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007558 parse_and_run_stream(&input, ';');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007559 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007560}
7561
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007562#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007563static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007564{
7565 pid_t pid;
7566 int channel[2];
7567# if !BB_MMU
7568 char **to_free = NULL;
7569# endif
7570
7571 xpipe(channel);
7572 pid = BB_MMU ? xfork() : xvfork();
7573 if (pid == 0) { /* child */
7574 disable_restore_tty_pgrp_on_exit();
7575 /* Process substitution is not considered to be usual
7576 * 'command execution'.
7577 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7578 */
7579 bb_signals(0
7580 + (1 << SIGTSTP)
7581 + (1 << SIGTTIN)
7582 + (1 << SIGTTOU)
7583 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007584 close(channel[0]); /* NB: close _first_, then move fd! */
7585 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007586# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007587 /* Awful hack for `trap` or $(trap).
7588 *
7589 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7590 * contains an example where "trap" is executed in a subshell:
7591 *
7592 * save_traps=$(trap)
7593 * ...
7594 * eval "$save_traps"
7595 *
7596 * Standard does not say that "trap" in subshell shall print
7597 * parent shell's traps. It only says that its output
7598 * must have suitable form, but then, in the above example
7599 * (which is not supposed to be normative), it implies that.
7600 *
7601 * bash (and probably other shell) does implement it
7602 * (traps are reset to defaults, but "trap" still shows them),
7603 * but as a result, "trap" logic is hopelessly messed up:
7604 *
7605 * # trap
7606 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7607 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7608 * # true | trap <--- trap is in subshell - no output (ditto)
7609 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7610 * trap -- 'echo Ho' SIGWINCH
7611 * # echo `(trap)` <--- in subshell in subshell - output
7612 * trap -- 'echo Ho' SIGWINCH
7613 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7614 * trap -- 'echo Ho' SIGWINCH
7615 *
7616 * The rules when to forget and when to not forget traps
7617 * get really complex and nonsensical.
7618 *
7619 * Our solution: ONLY bare $(trap) or `trap` is special.
7620 */
7621 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007622 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007623 && skip_whitespace(s + 4)[0] == '\0'
7624 ) {
7625 static const char *const argv[] = { NULL, NULL };
7626 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007627 fflush_all(); /* important */
7628 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007629 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007630# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007631# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007632 /* Prevent it from trying to handle ctrl-z etc */
7633 IF_HUSH_JOB(G.run_list_level = 1;)
7634 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007635 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007636 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007637 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007638 parse_and_run_string(s);
7639 _exit(G.last_exitcode);
7640# else
7641 /* We re-execute after vfork on NOMMU. This makes this script safe:
7642 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7643 * huge=`cat BIG` # was blocking here forever
7644 * echo OK
7645 */
7646 re_execute_shell(&to_free,
7647 s,
7648 G.global_argv[0],
7649 G.global_argv + 1,
7650 NULL);
7651# endif
7652 }
7653
7654 /* parent */
7655 *pid_p = pid;
7656# if ENABLE_HUSH_FAST
7657 G.count_SIGCHLD++;
7658//bb_error_msg("[%d] fork in generate_stream_from_string:"
7659// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7660// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7661# endif
7662 enable_restore_tty_pgrp_on_exit();
7663# if !BB_MMU
7664 free(to_free);
7665# endif
7666 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007667 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007668}
7669
7670/* Return code is exit status of the process that is run. */
7671static int process_command_subs(o_string *dest, const char *s)
7672{
7673 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007674 pid_t pid;
7675 int status, ch, eol_cnt;
7676
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007677 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007678
7679 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007680 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007681 while ((ch = getc(fp)) != EOF) {
7682 if (ch == '\0')
7683 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007684 if (ch == '\n') {
7685 eol_cnt++;
7686 continue;
7687 }
7688 while (eol_cnt) {
7689 o_addchr(dest, '\n');
7690 eol_cnt--;
7691 }
7692 o_addQchr(dest, ch);
7693 }
7694
7695 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007696 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007697 /* We need to extract exitcode. Test case
7698 * "true; echo `sleep 1; false` $?"
7699 * should print 1 */
7700 safe_waitpid(pid, &status, 0);
7701 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7702 return WEXITSTATUS(status);
7703}
7704#endif /* ENABLE_HUSH_TICK */
7705
7706
7707static void setup_heredoc(struct redir_struct *redir)
7708{
7709 struct fd_pair pair;
7710 pid_t pid;
7711 int len, written;
7712 /* the _body_ of heredoc (misleading field name) */
7713 const char *heredoc = redir->rd_filename;
7714 char *expanded;
7715#if !BB_MMU
7716 char **to_free;
7717#endif
7718
7719 expanded = NULL;
7720 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007721 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007722 if (expanded)
7723 heredoc = expanded;
7724 }
7725 len = strlen(heredoc);
7726
7727 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7728 xpiped_pair(pair);
7729 xmove_fd(pair.rd, redir->rd_fd);
7730
7731 /* Try writing without forking. Newer kernels have
7732 * dynamically growing pipes. Must use non-blocking write! */
7733 ndelay_on(pair.wr);
7734 while (1) {
7735 written = write(pair.wr, heredoc, len);
7736 if (written <= 0)
7737 break;
7738 len -= written;
7739 if (len == 0) {
7740 close(pair.wr);
7741 free(expanded);
7742 return;
7743 }
7744 heredoc += written;
7745 }
7746 ndelay_off(pair.wr);
7747
7748 /* Okay, pipe buffer was not big enough */
7749 /* Note: we must not create a stray child (bastard? :)
7750 * for the unsuspecting parent process. Child creates a grandchild
7751 * and exits before parent execs the process which consumes heredoc
7752 * (that exec happens after we return from this function) */
7753#if !BB_MMU
7754 to_free = NULL;
7755#endif
7756 pid = xvfork();
7757 if (pid == 0) {
7758 /* child */
7759 disable_restore_tty_pgrp_on_exit();
7760 pid = BB_MMU ? xfork() : xvfork();
7761 if (pid != 0)
7762 _exit(0);
7763 /* grandchild */
7764 close(redir->rd_fd); /* read side of the pipe */
7765#if BB_MMU
7766 full_write(pair.wr, heredoc, len); /* may loop or block */
7767 _exit(0);
7768#else
7769 /* Delegate blocking writes to another process */
7770 xmove_fd(pair.wr, STDOUT_FILENO);
7771 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7772#endif
7773 }
7774 /* parent */
7775#if ENABLE_HUSH_FAST
7776 G.count_SIGCHLD++;
7777//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7778#endif
7779 enable_restore_tty_pgrp_on_exit();
7780#if !BB_MMU
7781 free(to_free);
7782#endif
7783 close(pair.wr);
7784 free(expanded);
7785 wait(NULL); /* wait till child has died */
7786}
7787
Denys Vlasenko2db74612017-07-07 22:07:28 +02007788struct squirrel {
7789 int orig_fd;
7790 int moved_to;
7791 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7792 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7793};
7794
Denys Vlasenko621fc502017-07-24 12:42:17 +02007795static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7796{
7797 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7798 sq[i].orig_fd = orig;
7799 sq[i].moved_to = moved;
7800 sq[i+1].orig_fd = -1; /* end marker */
7801 return sq;
7802}
7803
Denys Vlasenko2db74612017-07-07 22:07:28 +02007804static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7805{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007806 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007807 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007808
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007809 i = 0;
7810 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007811 /* If we collide with an already moved fd... */
7812 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007813 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007814 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7815 if (sq[i].moved_to < 0) /* what? */
7816 xfunc_die();
7817 return sq;
7818 }
7819 if (fd == sq[i].orig_fd) {
7820 /* Example: echo Hello >/dev/null 1>&2 */
7821 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7822 return sq;
7823 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007824 }
7825
Denys Vlasenko2db74612017-07-07 22:07:28 +02007826 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007827 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007828 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7829 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007830 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007831 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007832}
7833
Denys Vlasenko657e9002017-07-30 23:34:04 +02007834static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7835{
7836 int i;
7837
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007838 i = 0;
7839 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007840 /* If we collide with an already moved fd... */
7841 if (fd == sq[i].orig_fd) {
7842 /* Examples:
7843 * "echo 3>FILE 3>&- 3>FILE"
7844 * "echo 3>&- 3>FILE"
7845 * No need for last redirect to insert
7846 * another "need to close 3" indicator.
7847 */
7848 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7849 return sq;
7850 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007851 }
7852
7853 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7854 return append_squirrel(sq, i, fd, -1);
7855}
7856
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007857/* fd: redirect wants this fd to be used (e.g. 3>file).
7858 * Move all conflicting internally used fds,
7859 * and remember them so that we can restore them later.
7860 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007861static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007862{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007863 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7864 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007865
7866#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko21806562019-11-01 14:16:07 +01007867 if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
7868 && fd == G_interactive_fd
7869 ) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007870 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007871 G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
7872 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 +02007873 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007874 }
7875#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007876 /* Are we called from setup_redirects(squirrel==NULL)
7877 * in redirect in a [v]forked child?
7878 */
7879 if (sqp == NULL) {
7880 /* No need to move script fds.
7881 * For NOMMU case, it's actively wrong: we'd change ->fd
7882 * fields in memory for the parent, but parent's fds
Denys Vlasenko21806562019-11-01 14:16:07 +01007883 * aren't moved, it would use wrong fd!
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007884 * Reproducer: "cmd 3>FILE" in script.
7885 * If we would call move_HFILEs_on_redirect(), child would:
7886 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7887 * close(3) = 0
7888 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7889 */
7890 //bb_error_msg("sqp == NULL: [v]forked child");
7891 return 0;
7892 }
7893
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007894 /* If this one of script's fds? */
7895 if (move_HFILEs_on_redirect(fd, avoid_fd))
7896 return 1; /* yes. "we closed fd" (actually moved it) */
7897
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007898 /* Are we called for "exec 3>FILE"? Came through
7899 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7900 * This case used to fail for this script:
7901 * exec 3>FILE
7902 * echo Ok
7903 * ...100000 more lines...
7904 * echo Ok
7905 * as follows:
7906 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7907 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7908 * dup2(4, 3) = 3
7909 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7910 * close(4) = 0
7911 * write(1, "Ok\n", 3) = 3
7912 * ... = 3
7913 * write(1, "Ok\n", 3) = 3
7914 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7915 * ^^^^^^^^ oops, wrong fd!!!
7916 * With this case separate from sqp == NULL and *after* move_HFILEs,
7917 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007918 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007919 if (sqp == ERR_PTR) {
7920 /* Don't preserve redirected fds: exec is _meant_ to change these */
7921 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007922 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007923 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007924
Denys Vlasenko2db74612017-07-07 22:07:28 +02007925 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7926 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7927 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007928}
7929
Denys Vlasenko2db74612017-07-07 22:07:28 +02007930static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007931{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007932 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007933 int i;
7934 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007935 if (sq[i].moved_to >= 0) {
7936 /* We simply die on error */
7937 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7938 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7939 } else {
7940 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7941 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7942 close(sq[i].orig_fd);
7943 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007944 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007945 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007946 }
Denys Vlasenko21806562019-11-01 14:16:07 +01007947 if (G.HFILE_stdin
Denys Vlasenko1237d622020-12-25 19:01:49 +01007948 && G.HFILE_stdin->fd > STDIN_FILENO
7949 /* we compare > STDIN, not == STDIN, since hfgetc()
7950 * closes fd and sets ->fd to -1 if EOF is reached.
7951 * Testcase: echo 'pwd' | hush
7952 */
Denys Vlasenko21806562019-11-01 14:16:07 +01007953 ) {
7954 /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
7955 * Redirect moves ->fd to e.g. 10,
7956 * and it is not restored above (we do not restore script fds
7957 * after redirects, we just use new, "moved" fds).
7958 * However for stdin, get_user_input() -> read_line_input(),
7959 * and read builtin, depend on fd == STDIN_FILENO.
7960 */
7961 debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
7962 xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
7963 G.HFILE_stdin->fd = STDIN_FILENO;
7964 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007965
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007966 /* If moved, G_interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007967}
7968
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007969#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007970static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007971{
7972 if (G_interactive_fd)
7973 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007974 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007975}
7976#endif
7977
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007978static int internally_opened_fd(int fd, struct squirrel *sq)
7979{
7980 int i;
7981
7982#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007983 if (fd == G_interactive_fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007984 return 1;
7985#endif
7986 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007987 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007988 return 1;
7989
7990 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7991 if (fd == sq[i].moved_to)
7992 return 1;
7993 }
7994 return 0;
7995}
7996
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007997/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7998 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007999static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008000{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008001 struct redir_struct *redir;
8002
8003 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02008004 int newfd;
8005 int closed;
8006
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008007 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02008008 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02008009 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008010 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
8011 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008012 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008013 redir->rd_filename);
8014 setup_heredoc(redir);
8015 continue;
8016 }
8017
8018 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02008019 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008020 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02008021 int mode;
8022
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008023 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02008024 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02008025 * "cmd >" (no filename)
8026 * "cmd > <file" (2nd redirect starts too early)
8027 */
Denys Vlasenko39701202017-08-02 19:44:05 +02008028 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008029 continue;
8030 }
8031 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02008032 p = expand_string_to_string(redir->rd_filename,
8033 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02008034 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008035 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02008036 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02008037 /* Error message from open_or_warn can be lost
8038 * if stderr has been redirected, but bash
8039 * and ash both lose it as well
8040 * (though zsh doesn't!)
8041 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008042 return 1;
8043 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02008044 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02008045 /* open() gave us precisely the fd we wanted.
8046 * This means that this fd was not busy
8047 * (not opened to anywhere).
8048 * Remember to close it on restore:
8049 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02008050 *sqp = add_squirrel_closed(*sqp, newfd);
8051 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02008052 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008053 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02008054 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
8055 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008056 }
8057
Denys Vlasenko657e9002017-07-30 23:34:04 +02008058 if (newfd == redir->rd_fd)
8059 continue;
8060
8061 /* if "N>FILE": move newfd to redir->rd_fd */
8062 /* if "N>&M": dup newfd to redir->rd_fd */
8063 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
8064
8065 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
8066 if (newfd == REDIRFD_CLOSE) {
8067 /* "N>&-" means "close me" */
8068 if (!closed) {
8069 /* ^^^ optimization: saving may already
8070 * have closed it. If not... */
8071 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008072 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02008073 /* Sometimes we do another close on restore, getting EBADF.
8074 * Consider "echo 3>FILE 3>&-"
8075 * first redirect remembers "need to close 3",
8076 * and second redirect closes 3! Restore code then closes 3 again.
8077 */
8078 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02008079 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02008080 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02008081 //errno = EBADF;
8082 //bb_perror_msg_and_die("can't duplicate file descriptor");
8083 newfd = -1; /* same effect as code above */
8084 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02008085 xdup2(newfd, redir->rd_fd);
8086 if (redir->rd_dup == REDIRFD_TO_FILE)
8087 /* "rd_fd > FILE" */
8088 close(newfd);
8089 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008090 }
8091 }
8092 return 0;
8093}
8094
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008095static char *find_in_path(const char *arg)
8096{
8097 char *ret = NULL;
8098 const char *PATH = get_local_var_value("PATH");
8099
8100 if (!PATH)
8101 return NULL;
8102
8103 while (1) {
8104 const char *end = strchrnul(PATH, ':');
8105 int sz = end - PATH; /* must be int! */
8106
8107 free(ret);
8108 if (sz != 0) {
8109 ret = xasprintf("%.*s/%s", sz, PATH, arg);
8110 } else {
8111 /* We have xxx::yyyy in $PATH,
8112 * it means "use current dir" */
8113 ret = xstrdup(arg);
8114 }
8115 if (access(ret, F_OK) == 0)
8116 break;
8117
8118 if (*end == '\0') {
8119 free(ret);
8120 return NULL;
8121 }
8122 PATH = end + 1;
8123 }
8124
8125 return ret;
8126}
8127
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008128static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008129 const struct built_in_command *x,
8130 const struct built_in_command *end)
8131{
8132 while (x != end) {
8133 if (strcmp(name, x->b_cmd) != 0) {
8134 x++;
8135 continue;
8136 }
8137 debug_printf_exec("found builtin '%s'\n", name);
8138 return x;
8139 }
8140 return NULL;
8141}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008142static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008143{
8144 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
8145}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008146static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008147{
8148 const struct built_in_command *x = find_builtin1(name);
8149 if (x)
8150 return x;
8151 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
8152}
8153
Denys Vlasenkod5314e72020-06-24 09:31:30 +02008154#if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
Ron Yorston9e2a5662020-01-21 16:01:58 +00008155static const char * FAST_FUNC get_builtin_name(int i)
8156{
8157 if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
8158 return bltins1[i].b_cmd;
8159 }
8160 i -= ARRAY_SIZE(bltins1);
8161 if (i < ARRAY_SIZE(bltins2)) {
8162 return bltins2[i].b_cmd;
8163 }
8164 return NULL;
8165}
8166#endif
8167
Denys Vlasenko99496dc2018-06-26 15:36:58 +02008168static void remove_nested_vars(void)
8169{
8170 struct variable *cur;
8171 struct variable **cur_pp;
8172
8173 cur_pp = &G.top_var;
8174 while ((cur = *cur_pp) != NULL) {
8175 if (cur->var_nest_level <= G.var_nest_level) {
8176 cur_pp = &cur->next;
8177 continue;
8178 }
8179 /* Unexport */
8180 if (cur->flg_export) {
8181 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
8182 bb_unsetenv(cur->varstr);
8183 }
8184 /* Remove from global list */
8185 *cur_pp = cur->next;
8186 /* Free */
8187 if (!cur->max_len) {
8188 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
8189 free(cur->varstr);
8190 }
8191 free(cur);
8192 }
8193}
8194
8195static void enter_var_nest_level(void)
8196{
8197 G.var_nest_level++;
8198 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
8199
8200 /* Try: f() { echo -n .; f; }; f
8201 * struct variable::var_nest_level is uint16_t,
8202 * thus limiting recursion to < 2^16.
8203 * In any case, with 8 Mbyte stack SEGV happens
8204 * not too long after 2^16 recursions anyway.
8205 */
8206 if (G.var_nest_level > 0xff00)
8207 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
8208}
8209
8210static void leave_var_nest_level(void)
8211{
8212 G.var_nest_level--;
8213 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
8214 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
James Byrne69374872019-07-02 11:35:03 +02008215 bb_simple_error_msg_and_die("BUG: nesting underflow");
Denys Vlasenko99496dc2018-06-26 15:36:58 +02008216
8217 remove_nested_vars();
8218}
8219
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008220#if ENABLE_HUSH_FUNCTIONS
8221static struct function **find_function_slot(const char *name)
8222{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008223 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008224 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008225
8226 while ((funcp = *funcpp) != NULL) {
8227 if (strcmp(name, funcp->name) == 0) {
8228 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008229 break;
8230 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008231 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008232 }
8233 return funcpp;
8234}
8235
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008236static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008237{
8238 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008239 return funcp;
8240}
8241
8242/* Note: takes ownership on name ptr */
8243static struct function *new_function(char *name)
8244{
8245 struct function **funcpp = find_function_slot(name);
8246 struct function *funcp = *funcpp;
8247
8248 if (funcp != NULL) {
8249 struct command *cmd = funcp->parent_cmd;
8250 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
8251 if (!cmd) {
8252 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
8253 free(funcp->name);
8254 /* Note: if !funcp->body, do not free body_as_string!
8255 * This is a special case of "-F name body" function:
8256 * body_as_string was not malloced! */
8257 if (funcp->body) {
8258 free_pipe_list(funcp->body);
8259# if !BB_MMU
8260 free(funcp->body_as_string);
8261# endif
8262 }
8263 } else {
8264 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
8265 cmd->argv[0] = funcp->name;
8266 cmd->group = funcp->body;
8267# if !BB_MMU
8268 cmd->group_as_string = funcp->body_as_string;
8269# endif
8270 }
8271 } else {
8272 debug_printf_exec("remembering new function '%s'\n", name);
8273 funcp = *funcpp = xzalloc(sizeof(*funcp));
8274 /*funcp->next = NULL;*/
8275 }
8276
8277 funcp->name = name;
8278 return funcp;
8279}
8280
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008281# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008282static void unset_func(const char *name)
8283{
8284 struct function **funcpp = find_function_slot(name);
8285 struct function *funcp = *funcpp;
8286
8287 if (funcp != NULL) {
8288 debug_printf_exec("freeing function '%s'\n", funcp->name);
8289 *funcpp = funcp->next;
8290 /* funcp is unlinked now, deleting it.
8291 * Note: if !funcp->body, the function was created by
8292 * "-F name body", do not free ->body_as_string
8293 * and ->name as they were not malloced. */
8294 if (funcp->body) {
8295 free_pipe_list(funcp->body);
8296 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008297# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008298 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008299# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008300 }
8301 free(funcp);
8302 }
8303}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008304# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008305
8306# if BB_MMU
8307#define exec_function(to_free, funcp, argv) \
8308 exec_function(funcp, argv)
8309# endif
8310static void exec_function(char ***to_free,
8311 const struct function *funcp,
8312 char **argv) NORETURN;
8313static void exec_function(char ***to_free,
8314 const struct function *funcp,
8315 char **argv)
8316{
8317# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008318 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008319
8320 argv[0] = G.global_argv[0];
8321 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008322 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008323
8324// Example when we are here: "cmd | func"
8325// func will run with saved-redirect fds open.
8326// $ f() { echo /proc/self/fd/*; }
8327// $ true | f
8328// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8329// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8330// Same in script:
8331// $ . ./SCRIPT
8332// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8333// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8334// They are CLOEXEC so external programs won't see them, but
8335// for "more correctness" we might want to close those extra fds here:
8336//? close_saved_fds_and_FILE_fds();
8337
Denys Vlasenko332e4112018-04-04 22:32:59 +02008338 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008339 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008340 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008341 IF_HUSH_LOCAL(G.func_nest_level++;)
8342
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008343 /* On MMU, funcp->body is always non-NULL */
8344 n = run_list(funcp->body);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008345 _exit(n);
8346# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008347//? close_saved_fds_and_FILE_fds();
8348
8349//TODO: check whether "true | func_with_return" works
8350
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008351 re_execute_shell(to_free,
8352 funcp->body_as_string,
8353 G.global_argv[0],
8354 argv + 1,
8355 NULL);
8356# endif
8357}
8358
8359static int run_function(const struct function *funcp, char **argv)
8360{
8361 int rc;
8362 save_arg_t sv;
8363 smallint sv_flg;
8364
8365 save_and_replace_G_args(&sv, argv);
8366
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008367 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008368 sv_flg = G_flag_return_in_progress;
8369 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008370
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008371 /* Make "local" variables properly shadow previous ones */
8372 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008373 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008374
8375 /* On MMU, funcp->body is always non-NULL */
8376# if !BB_MMU
8377 if (!funcp->body) {
8378 /* Function defined by -F */
8379 parse_and_run_string(funcp->body_as_string);
8380 rc = G.last_exitcode;
8381 } else
8382# endif
8383 {
8384 rc = run_list(funcp->body);
8385 }
8386
Denys Vlasenko332e4112018-04-04 22:32:59 +02008387 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008388 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008389
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008390 G_flag_return_in_progress = sv_flg;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01008391# if ENABLE_HUSH_TRAP
8392 debug_printf_exec("G.return_exitcode=-1\n");
8393 G.return_exitcode = -1; /* invalidate stashed return value */
8394# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008395
8396 restore_G_args(&sv, argv);
8397
8398 return rc;
8399}
8400#endif /* ENABLE_HUSH_FUNCTIONS */
8401
8402
8403#if BB_MMU
8404#define exec_builtin(to_free, x, argv) \
8405 exec_builtin(x, argv)
8406#else
8407#define exec_builtin(to_free, x, argv) \
8408 exec_builtin(to_free, argv)
8409#endif
8410static void exec_builtin(char ***to_free,
8411 const struct built_in_command *x,
8412 char **argv) NORETURN;
8413static void exec_builtin(char ***to_free,
8414 const struct built_in_command *x,
8415 char **argv)
8416{
8417#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008418 int rcode;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008419//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008420 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008421 fflush_all();
8422 _exit(rcode);
8423#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008424 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008425 /* On NOMMU, we must never block!
8426 * Example: { sleep 99 | read line; } & echo Ok
8427 */
8428 re_execute_shell(to_free,
8429 argv[0],
8430 G.global_argv[0],
8431 G.global_argv + 1,
8432 argv);
8433#endif
8434}
8435
8436
8437static void execvp_or_die(char **argv) NORETURN;
8438static void execvp_or_die(char **argv)
8439{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008440 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008441 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008442 /* Don't propagate SIG_IGN to the child */
8443 if (SPECIAL_JOBSTOP_SIGS != 0)
8444 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008445 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008446 e = 2;
8447 if (errno == EACCES) e = 126;
8448 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008449 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008450 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008451}
8452
8453#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008454static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008455{
8456 unsigned len;
8457 const char *cp;
8458
8459 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008460
8461 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8462 /* test a char with: bash -c 'set -x; echo "CH"' */
8463 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8464 " " "\001\002\003\004\005\006\007"
8465 "\010\011\012\013\014\015\016\017"
8466 "\020\021\022\023\024\025\026\027"
8467 "\030\031\032\033\034\035\036\037"
8468 )
8469 ] == '\0'
8470 ) {
8471 /* string has no special chars */
8472 x_mode_addstr(str);
8473 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008474 }
8475
8476 cp = str;
8477 for (;;) {
8478 /* print '....' up to EOL or first squote */
8479 len = (int)(strchrnul(cp, '\'') - cp);
8480 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008481 x_mode_addchr('\'');
8482 x_mode_addblock(cp, len);
8483 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008484 cp += len;
8485 }
8486 if (*cp == '\0')
8487 break;
8488 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008489 x_mode_addchr('\\');
8490 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008491 cp++;
8492 }
8493}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008494static void dump_cmd_in_x_mode(char **argv)
8495{
8496 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008497 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008498
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008499 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008500 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008501 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008502 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008503 x_mode_addchr(' ');
8504 if (argv[n][0] == '\0') {
8505 x_mode_addchr('\'');
8506 x_mode_addchr('\'');
8507 } else {
8508 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008509 }
8510 n++;
8511 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008512 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008513 }
8514}
8515#else
8516# define dump_cmd_in_x_mode(argv) ((void)0)
8517#endif
8518
Denys Vlasenko57000292018-01-12 14:41:45 +01008519#if ENABLE_HUSH_COMMAND
8520static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8521{
8522 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008523
Denys Vlasenko57000292018-01-12 14:41:45 +01008524 if (!opt_vV)
8525 return;
8526
8527 to_free = NULL;
8528 if (!explanation) {
8529 char *path = getenv("PATH");
8530 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008531 if (!explanation)
8532 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008533 if (opt_vV != 'V')
8534 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8535 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008536 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008537 free(to_free);
8538 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008539 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008540}
8541#else
8542# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8543#endif
8544
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008545#if BB_MMU
8546#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8547 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8548#define pseudo_exec(nommu_save, command, argv_expanded) \
8549 pseudo_exec(command, argv_expanded)
8550#endif
8551
8552/* Called after [v]fork() in run_pipe, or from builtin_exec.
8553 * Never returns.
8554 * Don't exit() here. If you don't exec, use _exit instead.
8555 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008556 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008557 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008558static void pseudo_exec_argv(nommu_save_t *nommu_save,
8559 char **argv, int assignment_cnt,
8560 char **argv_expanded) NORETURN;
8561static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8562 char **argv, int assignment_cnt,
8563 char **argv_expanded)
8564{
Denys Vlasenko57000292018-01-12 14:41:45 +01008565 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008566 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008567 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008568 IF_HUSH_COMMAND(char opt_vV = 0;)
8569 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008570
8571 new_env = expand_assignments(argv, assignment_cnt);
8572 dump_cmd_in_x_mode(new_env);
8573
8574 if (!argv[assignment_cnt]) {
8575 /* Case when we are here: ... | var=val | ...
8576 * (note that we do not exit early, i.e., do not optimize out
8577 * expand_assignments(): think about ... | var=`sleep 1` | ...
8578 */
8579 free_strings(new_env);
8580 _exit(EXIT_SUCCESS);
8581 }
8582
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008583 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008584#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008585 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008586#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008587 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008588 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008589#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008590 set_vars_and_save_old(new_env);
8591 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008592
8593 if (argv_expanded) {
8594 argv = argv_expanded;
8595 } else {
8596 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8597#if !BB_MMU
8598 nommu_save->argv = argv;
8599#endif
8600 }
8601 dump_cmd_in_x_mode(argv);
8602
8603#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8604 if (strchr(argv[0], '/') != NULL)
8605 goto skip;
8606#endif
8607
Denys Vlasenko75481d32017-07-31 05:27:09 +02008608#if ENABLE_HUSH_FUNCTIONS
8609 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008610 funcp = find_function(argv[0]);
8611 if (funcp)
8612 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008613#endif
8614
Denys Vlasenko57000292018-01-12 14:41:45 +01008615#if ENABLE_HUSH_COMMAND
8616 /* "command BAR": run BAR without looking it up among functions
8617 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8618 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8619 */
8620 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8621 char *p;
8622
8623 argv++;
8624 p = *argv;
8625 if (p[0] != '-' || !p[1])
8626 continue; /* bash allows "command command command [-OPT] BAR" */
8627
8628 for (;;) {
8629 p++;
8630 switch (*p) {
8631 case '\0':
8632 argv++;
8633 p = *argv;
8634 if (p[0] != '-' || !p[1])
8635 goto after_opts;
8636 continue; /* next arg is also -opts, process it too */
8637 case 'v':
8638 case 'V':
8639 opt_vV = *p;
8640 continue;
8641 default:
8642 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8643 }
8644 }
8645 }
8646 after_opts:
8647# if ENABLE_HUSH_FUNCTIONS
8648 if (opt_vV && find_function(argv[0]))
8649 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8650# endif
8651#endif
8652
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008653 /* Check if the command matches any of the builtins.
8654 * Depending on context, this might be redundant. But it's
8655 * easier to waste a few CPU cycles than it is to figure out
8656 * if this is one of those cases.
8657 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008658 /* Why "BB_MMU ? :" difference in logic? -
8659 * On NOMMU, it is more expensive to re-execute shell
8660 * just in order to run echo or test builtin.
8661 * It's better to skip it here and run corresponding
8662 * non-builtin later. */
8663 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8664 if (x) {
8665 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8666 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008667 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008668
8669#if ENABLE_FEATURE_SH_STANDALONE
8670 /* Check if the command matches any busybox applets */
8671 {
8672 int a = find_applet_by_name(argv[0]);
8673 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008674 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008675# if BB_MMU /* see above why on NOMMU it is not allowed */
8676 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008677 /* Do not leak open fds from opened script files etc.
8678 * Testcase: interactive "ls -l /proc/self/fd"
8679 * should not show tty fd open.
8680 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008681 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008682//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008683//This casuses test failures in
8684//redir_children_should_not_see_saved_fd_2.tests
8685//redir_children_should_not_see_saved_fd_3.tests
8686//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008687 /* Without this, "rm -i FILE" can't be ^C'ed: */
8688 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008689 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008690 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008691 }
8692# endif
8693 /* Re-exec ourselves */
8694 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008695 /* Don't propagate SIG_IGN to the child */
8696 if (SPECIAL_JOBSTOP_SIGS != 0)
8697 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008698 execv(bb_busybox_exec_path, argv);
8699 /* If they called chroot or otherwise made the binary no longer
8700 * executable, fall through */
8701 }
8702 }
8703#endif
8704
8705#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8706 skip:
8707#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008708 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008709 execvp_or_die(argv);
8710}
8711
8712/* Called after [v]fork() in run_pipe
8713 */
8714static void pseudo_exec(nommu_save_t *nommu_save,
8715 struct command *command,
8716 char **argv_expanded) NORETURN;
8717static void pseudo_exec(nommu_save_t *nommu_save,
8718 struct command *command,
8719 char **argv_expanded)
8720{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008721#if ENABLE_HUSH_FUNCTIONS
8722 if (command->cmd_type == CMD_FUNCDEF) {
8723 /* Ignore funcdefs in pipes:
8724 * true | f() { cmd }
8725 */
8726 _exit(0);
8727 }
8728#endif
8729
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008730 if (command->argv) {
8731 pseudo_exec_argv(nommu_save, command->argv,
8732 command->assignment_cnt, argv_expanded);
8733 }
8734
8735 if (command->group) {
8736 /* Cases when we are here:
8737 * ( list )
8738 * { list } &
8739 * ... | ( list ) | ...
8740 * ... | { list } | ...
8741 */
8742#if BB_MMU
8743 int rcode;
8744 debug_printf_exec("pseudo_exec: run_list\n");
8745 reset_traps_to_defaults();
8746 rcode = run_list(command->group);
8747 /* OK to leak memory by not calling free_pipe_list,
8748 * since this process is about to exit */
8749 _exit(rcode);
8750#else
8751 re_execute_shell(&nommu_save->argv_from_re_execing,
8752 command->group_as_string,
8753 G.global_argv[0],
8754 G.global_argv + 1,
8755 NULL);
8756#endif
8757 }
8758
8759 /* Case when we are here: ... | >file */
8760 debug_printf_exec("pseudo_exec'ed null command\n");
8761 _exit(EXIT_SUCCESS);
8762}
8763
8764#if ENABLE_HUSH_JOB
8765static const char *get_cmdtext(struct pipe *pi)
8766{
8767 char **argv;
8768 char *p;
8769 int len;
8770
8771 /* This is subtle. ->cmdtext is created only on first backgrounding.
8772 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8773 * On subsequent bg argv is trashed, but we won't use it */
8774 if (pi->cmdtext)
8775 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008776
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008777 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008778 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008779 pi->cmdtext = xzalloc(1);
8780 return pi->cmdtext;
8781 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008782 len = 0;
8783 do {
8784 len += strlen(*argv) + 1;
8785 } while (*++argv);
8786 p = xmalloc(len);
8787 pi->cmdtext = p;
8788 argv = pi->cmds[0].argv;
8789 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008790 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008791 *p++ = ' ';
8792 } while (*++argv);
8793 p[-1] = '\0';
8794 return pi->cmdtext;
8795}
8796
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008797static void remove_job_from_table(struct pipe *pi)
8798{
8799 struct pipe *prev_pipe;
8800
8801 if (pi == G.job_list) {
8802 G.job_list = pi->next;
8803 } else {
8804 prev_pipe = G.job_list;
8805 while (prev_pipe->next != pi)
8806 prev_pipe = prev_pipe->next;
8807 prev_pipe->next = pi->next;
8808 }
8809 G.last_jobid = 0;
8810 if (G.job_list)
8811 G.last_jobid = G.job_list->jobid;
8812}
8813
8814static void delete_finished_job(struct pipe *pi)
8815{
8816 remove_job_from_table(pi);
8817 free_pipe(pi);
8818}
8819
8820static void clean_up_last_dead_job(void)
8821{
8822 if (G.job_list && !G.job_list->alive_cmds)
8823 delete_finished_job(G.job_list);
8824}
8825
Denys Vlasenko16096292017-07-10 10:00:28 +02008826static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008827{
8828 struct pipe *job, **jobp;
8829 int i;
8830
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008831 clean_up_last_dead_job();
8832
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008833 /* Find the end of the list, and find next job ID to use */
8834 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008835 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008836 while ((job = *jobp) != NULL) {
8837 if (job->jobid > i)
8838 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008839 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008840 }
8841 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008842
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008843 /* Create a new job struct at the end */
8844 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008845 job->next = NULL;
8846 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8847 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8848 for (i = 0; i < pi->num_cmds; i++) {
8849 job->cmds[i].pid = pi->cmds[i].pid;
8850 /* all other fields are not used and stay zero */
8851 }
8852 job->cmdtext = xstrdup(get_cmdtext(pi));
8853
8854 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008855 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008856 G.last_jobid = job->jobid;
8857}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008858#endif /* JOB */
8859
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008860static int job_exited_or_stopped(struct pipe *pi)
8861{
8862 int rcode, i;
8863
8864 if (pi->alive_cmds != pi->stopped_cmds)
8865 return -1;
8866
8867 /* All processes in fg pipe have exited or stopped */
8868 rcode = 0;
8869 i = pi->num_cmds;
8870 while (--i >= 0) {
8871 rcode = pi->cmds[i].cmd_exitcode;
8872 /* usually last process gives overall exitstatus,
8873 * but with "set -o pipefail", last *failed* process does */
8874 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8875 break;
8876 }
8877 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8878 return rcode;
8879}
8880
Denys Vlasenko7e675362016-10-28 21:57:31 +02008881static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008882{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008883#if ENABLE_HUSH_JOB
8884 struct pipe *pi;
8885#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008886 int i, dead;
8887
8888 dead = WIFEXITED(status) || WIFSIGNALED(status);
8889
8890#if DEBUG_JOBS
8891 if (WIFSTOPPED(status))
8892 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8893 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8894 if (WIFSIGNALED(status))
8895 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8896 childpid, WTERMSIG(status), WEXITSTATUS(status));
8897 if (WIFEXITED(status))
8898 debug_printf_jobs("pid %d exited, exitcode %d\n",
8899 childpid, WEXITSTATUS(status));
8900#endif
8901 /* Were we asked to wait for a fg pipe? */
8902 if (fg_pipe) {
8903 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008904
Denys Vlasenko7e675362016-10-28 21:57:31 +02008905 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008906 int rcode;
8907
Denys Vlasenko7e675362016-10-28 21:57:31 +02008908 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8909 if (fg_pipe->cmds[i].pid != childpid)
8910 continue;
8911 if (dead) {
8912 int ex;
8913 fg_pipe->cmds[i].pid = 0;
8914 fg_pipe->alive_cmds--;
8915 ex = WEXITSTATUS(status);
8916 /* bash prints killer signal's name for *last*
8917 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8918 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8919 */
8920 if (WIFSIGNALED(status)) {
8921 int sig = WTERMSIG(status);
Denys Vlasenko77a51a22020-12-29 16:53:11 +01008922#if ENABLE_HUSH_JOB
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008923 if (G.run_list_level == 1
8924 /* ^^^^^ Do not print in nested contexts, example:
8925 * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
8926 */
8927 && i == fg_pipe->num_cmds-1
8928 ) {
Denys Vlasenkoe16f7eb2020-10-24 04:26:43 +02008929 /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
8930 puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008931 }
Denys Vlasenko77a51a22020-12-29 16:53:11 +01008932#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008933 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko93e2a222020-12-23 12:23:21 +01008934 /* MIPS has 128 sigs (1..128), if sig==128,
8935 * 128 + sig would result in exitcode 256 -> 0!
8936 */
8937 ex = 128 | sig;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008938 }
8939 fg_pipe->cmds[i].cmd_exitcode = ex;
8940 } else {
8941 fg_pipe->stopped_cmds++;
8942 }
8943 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8944 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008945 rcode = job_exited_or_stopped(fg_pipe);
8946 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008947/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8948 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8949 * and "killall -STOP cat" */
8950 if (G_interactive_fd) {
8951#if ENABLE_HUSH_JOB
8952 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008953 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008954#endif
8955 return rcode;
8956 }
8957 if (fg_pipe->alive_cmds == 0)
8958 return rcode;
8959 }
8960 /* There are still running processes in the fg_pipe */
8961 return -1;
8962 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008963 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008964 }
8965
8966#if ENABLE_HUSH_JOB
8967 /* We were asked to wait for bg or orphaned children */
8968 /* No need to remember exitcode in this case */
8969 for (pi = G.job_list; pi; pi = pi->next) {
8970 for (i = 0; i < pi->num_cmds; i++) {
8971 if (pi->cmds[i].pid == childpid)
8972 goto found_pi_and_prognum;
8973 }
8974 }
8975 /* Happens when shell is used as init process (init=/bin/sh) */
8976 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8977 return -1; /* this wasn't a process from fg_pipe */
8978
8979 found_pi_and_prognum:
8980 if (dead) {
8981 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008982 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008983 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01008984 /* NB: not 128 + sig, MIPS has sig 128 */
8985 rcode = 128 | WTERMSIG(status);
Denys Vlasenko840a4352017-07-07 22:56:02 +02008986 pi->cmds[i].cmd_exitcode = rcode;
8987 if (G.last_bg_pid == pi->cmds[i].pid)
8988 G.last_bg_pid_exitcode = rcode;
8989 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008990 pi->alive_cmds--;
8991 if (!pi->alive_cmds) {
Denys Vlasenko259747c2019-11-28 10:28:14 +01008992# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008993 G.dead_job_exitcode = job_exited_or_stopped(pi);
Denys Vlasenko259747c2019-11-28 10:28:14 +01008994# endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008995 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008996 printf(JOB_STATUS_FORMAT, pi->jobid,
8997 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008998 delete_finished_job(pi);
8999 } else {
9000/*
9001 * bash deletes finished jobs from job table only in interactive mode,
9002 * after "jobs" cmd, or if pid of a new process matches one of the old ones
9003 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
9004 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
9005 * We only retain one "dead" job, if it's the single job on the list.
9006 * This covers most of real-world scenarios where this is useful.
9007 */
9008 if (pi != G.job_list)
9009 delete_finished_job(pi);
9010 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009011 }
9012 } else {
9013 /* child stopped */
9014 pi->stopped_cmds++;
9015 }
9016#endif
9017 return -1; /* this wasn't a process from fg_pipe */
9018}
9019
9020/* Check to see if any processes have exited -- if they have,
9021 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009022 *
9023 * If non-NULL fg_pipe: wait for its completion or stop.
9024 * Return its exitcode or zero if stopped.
9025 *
9026 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
9027 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
9028 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
9029 * or 0 if no children changed status.
9030 *
9031 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
9032 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
9033 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02009034 */
9035static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
9036{
9037 int attributes;
9038 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009039 int rcode = 0;
9040
9041 debug_printf_jobs("checkjobs %p\n", fg_pipe);
9042
9043 attributes = WUNTRACED;
9044 if (fg_pipe == NULL)
9045 attributes |= WNOHANG;
9046
9047 errno = 0;
9048#if ENABLE_HUSH_FAST
9049 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
9050//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
9051//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
9052 /* There was neither fork nor SIGCHLD since last waitpid */
9053 /* Avoid doing waitpid syscall if possible */
9054 if (!G.we_have_children) {
9055 errno = ECHILD;
9056 return -1;
9057 }
9058 if (fg_pipe == NULL) { /* is WNOHANG set? */
9059 /* We have children, but they did not exit
9060 * or stop yet (we saw no SIGCHLD) */
9061 return 0;
9062 }
9063 /* else: !WNOHANG, waitpid will block, can't short-circuit */
9064 }
9065#endif
9066
9067/* Do we do this right?
9068 * bash-3.00# sleep 20 | false
9069 * <ctrl-Z pressed>
9070 * [3]+ Stopped sleep 20 | false
9071 * bash-3.00# echo $?
9072 * 1 <========== bg pipe is not fully done, but exitcode is already known!
9073 * [hush 1.14.0: yes we do it right]
9074 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009075 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009076 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009077#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02009078 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009079 i = G.count_SIGCHLD;
9080#endif
9081 childpid = waitpid(-1, &status, attributes);
9082 if (childpid <= 0) {
9083 if (childpid && errno != ECHILD)
James Byrne69374872019-07-02 11:35:03 +02009084 bb_simple_perror_msg("waitpid");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009085#if ENABLE_HUSH_FAST
9086 else { /* Until next SIGCHLD, waitpid's are useless */
9087 G.we_have_children = (childpid == 0);
9088 G.handled_SIGCHLD = i;
9089//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9090 }
9091#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009092 /* ECHILD (no children), or 0 (no change in children status) */
9093 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009094 break;
9095 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009096 rcode = process_wait_result(fg_pipe, childpid, status);
9097 if (rcode >= 0) {
9098 /* fg_pipe exited or stopped */
9099 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009100 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01009101 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009102 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009103 rcode = WEXITSTATUS(status);
9104 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009105 rcode = 128 | WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009106 if (WIFSTOPPED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009107 /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
9108 rcode = 128 | WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009109 rcode++;
9110 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009111 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01009112#if ENABLE_HUSH_BASH_COMPAT
9113 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
9114 && G.dead_job_exitcode >= 0 /* some job did finish */
9115 ) {
9116 debug_printf_exec("waitfor_pid:-1\n");
9117 rcode = G.dead_job_exitcode + 1;
9118 break;
9119 }
9120#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009121 /* This wasn't one of our processes, or */
9122 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009123 } /* while (waitpid succeeds)... */
9124
9125 return rcode;
9126}
9127
9128#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02009129static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009130{
9131 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02009132 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009133 if (G_saved_tty_pgrp) {
9134 /* Job finished, move the shell to the foreground */
9135 p = getpgrp(); /* our process group id */
9136 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
9137 tcsetpgrp(G_interactive_fd, p);
9138 }
9139 return rcode;
9140}
9141#endif
9142
9143/* Start all the jobs, but don't wait for anything to finish.
9144 * See checkjobs().
9145 *
9146 * Return code is normally -1, when the caller has to wait for children
9147 * to finish to determine the exit status of the pipe. If the pipe
9148 * is a simple builtin command, however, the action is done by the
9149 * time run_pipe returns, and the exit code is provided as the
9150 * return value.
9151 *
9152 * Returns -1 only if started some children. IOW: we have to
9153 * mask out retvals of builtins etc with 0xff!
9154 *
9155 * The only case when we do not need to [v]fork is when the pipe
9156 * is single, non-backgrounded, non-subshell command. Examples:
9157 * cmd ; ... { list } ; ...
9158 * cmd && ... { list } && ...
9159 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01009160 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009161 * or (if SH_STANDALONE) an applet, and we can run the { list }
9162 * with run_list. If it isn't one of these, we fork and exec cmd.
9163 *
9164 * Cases when we must fork:
9165 * non-single: cmd | cmd
9166 * backgrounded: cmd & { list } &
9167 * subshell: ( list ) [&]
9168 */
9169#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009170#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
9171 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009172#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009173static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009174 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02009175 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009176 char **argv_expanded)
9177{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009178 /* Assignments occur before redirects. Try:
9179 * a=`sleep 1` sleep 2 3>/qwe/rty
9180 */
9181
9182 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
9183 dump_cmd_in_x_mode(new_env);
9184 dump_cmd_in_x_mode(argv_expanded);
9185 /* this takes ownership of new_env[i] elements, and frees new_env: */
9186 set_vars_and_save_old(new_env);
9187
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009188 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009189}
9190static NOINLINE int run_pipe(struct pipe *pi)
9191{
9192 static const char *const null_ptr = NULL;
9193
9194 int cmd_no;
9195 int next_infd;
9196 struct command *command;
9197 char **argv_expanded;
9198 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02009199 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009200 int rcode;
9201
9202 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
9203 debug_enter();
9204
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009205 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
9206 * Result should be 3 lines: q w e, qwe, q w e
9207 */
Denys Vlasenko96786362018-04-11 16:02:58 +02009208 if (G.ifs_whitespace != G.ifs)
9209 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009210 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02009211 if (G.ifs) {
9212 char *p;
9213 G.ifs_whitespace = (char*)G.ifs;
9214 p = skip_whitespace(G.ifs);
9215 if (*p) {
9216 /* Not all $IFS is whitespace */
9217 char *d;
9218 int len = p - G.ifs;
9219 p = skip_non_whitespace(p);
9220 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
9221 d = mempcpy(G.ifs_whitespace, G.ifs, len);
9222 while (*p) {
9223 if (isspace(*p))
9224 *d++ = *p;
9225 p++;
9226 }
9227 *d = '\0';
9228 }
9229 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009230 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02009231 G.ifs_whitespace = (char*)G.ifs;
9232 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009233
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009234 IF_HUSH_JOB(pi->pgrp = -1;)
9235 pi->stopped_cmds = 0;
9236 command = &pi->cmds[0];
9237 argv_expanded = NULL;
9238
9239 if (pi->num_cmds != 1
9240 || pi->followup == PIPE_BG
9241 || command->cmd_type == CMD_SUBSHELL
9242 ) {
9243 goto must_fork;
9244 }
9245
9246 pi->alive_cmds = 1;
9247
9248 debug_printf_exec(": group:%p argv:'%s'\n",
9249 command->group, command->argv ? command->argv[0] : "NONE");
9250
9251 if (command->group) {
9252#if ENABLE_HUSH_FUNCTIONS
9253 if (command->cmd_type == CMD_FUNCDEF) {
9254 /* "executing" func () { list } */
9255 struct function *funcp;
9256
9257 funcp = new_function(command->argv[0]);
9258 /* funcp->name is already set to argv[0] */
9259 funcp->body = command->group;
9260# if !BB_MMU
9261 funcp->body_as_string = command->group_as_string;
9262 command->group_as_string = NULL;
9263# endif
9264 command->group = NULL;
9265 command->argv[0] = NULL;
9266 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
9267 funcp->parent_cmd = command;
9268 command->child_func = funcp;
9269
9270 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
9271 debug_leave();
9272 return EXIT_SUCCESS;
9273 }
9274#endif
9275 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009276 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009277 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009278 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009279 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02009280//FIXME: we need to pass squirrel down into run_list()
9281//for SH_STANDALONE case, or else this construct:
9282// { find /proc/self/fd; true; } >FILE; cmd2
9283//has no way of closing saved fd#1 for "find",
9284//and in SH_STANDALONE mode, "find" is not execed,
9285//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009286 rcode = run_list(command->group) & 0xff;
9287 }
9288 restore_redirects(squirrel);
9289 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9290 debug_leave();
9291 debug_printf_exec("run_pipe: return %d\n", rcode);
9292 return rcode;
9293 }
9294
9295 argv = command->argv ? command->argv : (char **) &null_ptr;
9296 {
9297 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009298 IF_HUSH_FUNCTIONS(const struct function *funcp;)
9299 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009300 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009301 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009302
Denys Vlasenko5807e182018-02-08 19:19:04 +01009303#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009304 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009305#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009306
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009307 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009308 /* Assignments, but no command.
9309 * Ensure redirects take effect (that is, create files).
9310 * Try "a=t >file"
9311 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009312 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009313 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009314 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009315 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009316 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009317
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009318 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009319 i = 0;
9320 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009321 char *p = expand_string_to_string(argv[i],
9322 EXP_FLAG_ESC_GLOB_CHARS,
9323 /*unbackslash:*/ 1
9324 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009325#if ENABLE_HUSH_MODE_X
9326 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009327 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009328 if (i == 0)
9329 x_mode_prefix();
9330 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009331 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009332 if (*eq) eq++;
9333 x_mode_addblock(p, (eq - p));
9334 x_mode_print_optionally_squoted(eq);
9335 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009336 }
9337#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009338 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009339 if (set_local_var(p, /*flag:*/ 0)) {
9340 /* assignment to readonly var / putenv error? */
9341 rcode = 1;
9342 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009343 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009344 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009345 /* Redirect error sets $? to 1. Otherwise,
9346 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009347 * Else, clear $?:
9348 * false; q=`exit 2`; echo $? - should print 2
9349 * false; x=1; echo $? - should print 0
9350 * Because of the 2nd case, we can't just use G.last_exitcode.
9351 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009352 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009353 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009354 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9355 debug_leave();
9356 debug_printf_exec("run_pipe: return %d\n", rcode);
9357 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009358 }
9359
9360 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkod2241f52020-10-31 03:34:07 +01009361#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
9362 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
9363 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
9364 else
9365#endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02009366#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009367 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009368 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009369 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009370#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009371 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009372
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009373 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009374 if (!argv_expanded[0]) {
9375 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009376 /* `false` still has to set exitcode 1 */
9377 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009378 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009379 }
9380
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009381 old_vars = NULL;
9382 sv_shadowed = G.shadowed_vars_pp;
9383
Denys Vlasenko75481d32017-07-31 05:27:09 +02009384 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009385 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9386 IF_HUSH_FUNCTIONS(x = NULL;)
9387 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009388 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009389 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009390 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9391 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009392 /*
9393 * Variable assignments are executed, but then "forgotten":
9394 * a=`sleep 1;echo A` exec 3>&-; echo $a
9395 * sleeps, but prints nothing.
9396 */
9397 enter_var_nest_level();
9398 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009399 rcode = redirect_and_varexp_helper(command,
9400 /*squirrel:*/ ERR_PTR,
9401 argv_expanded
9402 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009403 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009404 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009405
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009406 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009407 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009408
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009409 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009410 * a=b true; env | grep ^a=
9411 */
9412 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009413 /* Collect all variables "shadowed" by helper
9414 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9415 * into old_vars list:
9416 */
9417 G.shadowed_vars_pp = &old_vars;
9418 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009419 if (rcode == 0) {
9420 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009421 /* Do not collect *to old_vars list* vars shadowed
9422 * by e.g. "local VAR" builtin (collect them
9423 * in the previously nested list instead):
9424 * don't want them to be restored immediately
9425 * after "local" completes.
9426 */
9427 G.shadowed_vars_pp = sv_shadowed;
9428
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009429 debug_printf_exec(": builtin '%s' '%s'...\n",
9430 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009431 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009432 rcode = x->b_function(argv_expanded) & 0xff;
9433 fflush_all();
9434 }
9435#if ENABLE_HUSH_FUNCTIONS
9436 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009437 debug_printf_exec(": function '%s' '%s'...\n",
9438 funcp->name, argv_expanded[1]);
9439 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009440 /*
9441 * But do collect *to old_vars list* vars shadowed
9442 * within function execution. To that end, restore
9443 * this pointer _after_ function run:
9444 */
9445 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009446 }
9447#endif
9448 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009449 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009450 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009451 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009452 if (n < 0 || !APPLET_IS_NOFORK(n))
9453 goto must_fork;
9454
9455 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009456 /* Collect all variables "shadowed" by helper into old_vars list */
9457 G.shadowed_vars_pp = &old_vars;
9458 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9459 G.shadowed_vars_pp = sv_shadowed;
9460
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009461 if (rcode == 0) {
9462 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9463 argv_expanded[0], argv_expanded[1]);
9464 /*
9465 * Note: signals (^C) can't interrupt here.
9466 * We remember them and they will be acted upon
9467 * after applet returns.
9468 * This makes applets which can run for a long time
9469 * and/or wait for user input ineligible for NOFORK:
9470 * for example, "yes" or "rm" (rm -i waits for input).
9471 */
9472 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009473 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009474 } else
9475 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009476
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009477 restore_redirects(squirrel);
9478 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009479 leave_var_nest_level();
9480 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009481
9482 /*
9483 * Try "usleep 99999999" + ^C + "echo $?"
9484 * with FEATURE_SH_NOFORK=y.
9485 */
9486 if (!funcp) {
9487 /* It was builtin or nofork.
9488 * if this would be a real fork/execed program,
9489 * it should have died if a fatal sig was received.
9490 * But OTOH, there was no separate process,
9491 * the sig was sent to _shell_, not to non-existing
9492 * child.
9493 * Let's just handle ^C only, this one is obvious:
9494 * we aren't ok with exitcode 0 when ^C was pressed
9495 * during builtin/nofork.
9496 */
9497 if (sigismember(&G.pending_set, SIGINT))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009498 rcode = 128 | SIGINT;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009499 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009500 free(argv_expanded);
9501 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9502 debug_leave();
9503 debug_printf_exec("run_pipe return %d\n", rcode);
9504 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009505 }
9506
9507 must_fork:
9508 /* NB: argv_expanded may already be created, and that
9509 * might include `cmd` runs! Do not rerun it! We *must*
9510 * use argv_expanded if it's non-NULL */
9511
9512 /* Going to fork a child per each pipe member */
9513 pi->alive_cmds = 0;
9514 next_infd = 0;
9515
9516 cmd_no = 0;
9517 while (cmd_no < pi->num_cmds) {
9518 struct fd_pair pipefds;
9519#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009520 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009521 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009522 nommu_save.old_vars = NULL;
9523 nommu_save.argv = NULL;
9524 nommu_save.argv_from_re_execing = NULL;
9525#endif
9526 command = &pi->cmds[cmd_no];
9527 cmd_no++;
9528 if (command->argv) {
9529 debug_printf_exec(": pipe member '%s' '%s'...\n",
9530 command->argv[0], command->argv[1]);
9531 } else {
9532 debug_printf_exec(": pipe member with no argv\n");
9533 }
9534
9535 /* pipes are inserted between pairs of commands */
9536 pipefds.rd = 0;
9537 pipefds.wr = 1;
9538 if (cmd_no < pi->num_cmds)
9539 xpiped_pair(pipefds);
9540
Denys Vlasenko5807e182018-02-08 19:19:04 +01009541#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009542 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009543#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009544
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009545 command->pid = BB_MMU ? fork() : vfork();
9546 if (!command->pid) { /* child */
9547#if ENABLE_HUSH_JOB
9548 disable_restore_tty_pgrp_on_exit();
9549 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9550
9551 /* Every child adds itself to new process group
9552 * with pgid == pid_of_first_child_in_pipe */
9553 if (G.run_list_level == 1 && G_interactive_fd) {
9554 pid_t pgrp;
9555 pgrp = pi->pgrp;
9556 if (pgrp < 0) /* true for 1st process only */
9557 pgrp = getpid();
9558 if (setpgid(0, pgrp) == 0
9559 && pi->followup != PIPE_BG
9560 && G_saved_tty_pgrp /* we have ctty */
9561 ) {
9562 /* We do it in *every* child, not just first,
9563 * to avoid races */
9564 tcsetpgrp(G_interactive_fd, pgrp);
9565 }
9566 }
9567#endif
9568 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9569 /* 1st cmd in backgrounded pipe
9570 * should have its stdin /dev/null'ed */
9571 close(0);
9572 if (open(bb_dev_null, O_RDONLY))
9573 xopen("/", O_RDONLY);
9574 } else {
9575 xmove_fd(next_infd, 0);
9576 }
9577 xmove_fd(pipefds.wr, 1);
9578 if (pipefds.rd > 1)
9579 close(pipefds.rd);
9580 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009581 * and the pipe fd (fd#1) is available for dup'ing:
9582 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9583 * of cmd1 goes into pipe.
9584 */
9585 if (setup_redirects(command, NULL)) {
9586 /* Happens when redir file can't be opened:
9587 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9588 * FOO
9589 * hush: can't open '/qwe/rty': No such file or directory
9590 * BAZ
9591 * (echo BAR is not executed, it hits _exit(1) below)
9592 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009593 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009594 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009595
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009596 /* Stores to nommu_save list of env vars putenv'ed
9597 * (NOMMU, on MMU we don't need that) */
9598 /* cast away volatility... */
9599 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9600 /* pseudo_exec() does not return */
9601 }
9602
9603 /* parent or error */
9604#if ENABLE_HUSH_FAST
9605 G.count_SIGCHLD++;
9606//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9607#endif
9608 enable_restore_tty_pgrp_on_exit();
9609#if !BB_MMU
9610 /* Clean up after vforked child */
9611 free(nommu_save.argv);
9612 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009613 G.var_nest_level = sv_var_nest_level;
9614 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009615 add_vars(nommu_save.old_vars);
9616#endif
9617 free(argv_expanded);
9618 argv_expanded = NULL;
9619 if (command->pid < 0) { /* [v]fork failed */
9620 /* Clearly indicate, was it fork or vfork */
James Byrne69374872019-07-02 11:35:03 +02009621 bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009622 } else {
9623 pi->alive_cmds++;
9624#if ENABLE_HUSH_JOB
9625 /* Second and next children need to know pid of first one */
9626 if (pi->pgrp < 0)
9627 pi->pgrp = command->pid;
9628#endif
9629 }
9630
9631 if (cmd_no > 1)
9632 close(next_infd);
9633 if (cmd_no < pi->num_cmds)
9634 close(pipefds.wr);
9635 /* Pass read (output) pipe end to next iteration */
9636 next_infd = pipefds.rd;
9637 }
9638
9639 if (!pi->alive_cmds) {
9640 debug_leave();
9641 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9642 return 1;
9643 }
9644
9645 debug_leave();
9646 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9647 return -1;
9648}
9649
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009650/* NB: called by pseudo_exec, and therefore must not modify any
9651 * global data until exec/_exit (we can be a child after vfork!) */
9652static int run_list(struct pipe *pi)
9653{
9654#if ENABLE_HUSH_CASE
9655 char *case_word = NULL;
9656#endif
9657#if ENABLE_HUSH_LOOPS
9658 struct pipe *loop_top = NULL;
9659 char **for_lcur = NULL;
9660 char **for_list = NULL;
9661#endif
9662 smallint last_followup;
9663 smalluint rcode;
9664#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9665 smalluint cond_code = 0;
9666#else
9667 enum { cond_code = 0 };
9668#endif
9669#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009670 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009671 smallint last_rword; /* ditto */
9672#endif
9673
9674 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9675 debug_enter();
9676
9677#if ENABLE_HUSH_LOOPS
9678 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009679 {
9680 struct pipe *cpipe;
9681 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9682 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9683 continue;
9684 /* current word is FOR or IN (BOLD in comments below) */
9685 if (cpipe->next == NULL) {
9686 syntax_error("malformed for");
9687 debug_leave();
9688 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9689 return 1;
9690 }
9691 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9692 if (cpipe->next->res_word == RES_DO)
9693 continue;
9694 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9695 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9696 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9697 ) {
9698 syntax_error("malformed for");
9699 debug_leave();
9700 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9701 return 1;
9702 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009703 }
9704 }
9705#endif
9706
9707 /* Past this point, all code paths should jump to ret: label
9708 * in order to return, no direct "return" statements please.
9709 * This helps to ensure that no memory is leaked. */
9710
9711#if ENABLE_HUSH_JOB
9712 G.run_list_level++;
9713#endif
9714
9715#if HAS_KEYWORDS
9716 rword = RES_NONE;
9717 last_rword = RES_XXXX;
9718#endif
9719 last_followup = PIPE_SEQ;
9720 rcode = G.last_exitcode;
9721
9722 /* Go through list of pipes, (maybe) executing them. */
9723 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009724 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009725 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009726
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009727 if (G.flag_SIGINT)
9728 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009729 if (G_flag_return_in_progress == 1)
9730 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009731
9732 IF_HAS_KEYWORDS(rword = pi->res_word;)
9733 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9734 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009735
9736 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009737 if (
9738#if ENABLE_HUSH_IF
9739 rword == RES_IF || rword == RES_ELIF ||
9740#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009741 pi->followup != PIPE_SEQ
9742 ) {
9743 G.errexit_depth++;
9744 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009745#if ENABLE_HUSH_LOOPS
9746 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9747 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9748 ) {
9749 /* start of a loop: remember where loop starts */
9750 loop_top = pi;
9751 G.depth_of_loop++;
9752 }
9753#endif
9754 /* Still in the same "if...", "then..." or "do..." branch? */
9755 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9756 if ((rcode == 0 && last_followup == PIPE_OR)
9757 || (rcode != 0 && last_followup == PIPE_AND)
9758 ) {
9759 /* It is "<true> || CMD" or "<false> && CMD"
9760 * and we should not execute CMD */
9761 debug_printf_exec("skipped cmd because of || or &&\n");
9762 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009763 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009764 }
9765 }
9766 last_followup = pi->followup;
9767 IF_HAS_KEYWORDS(last_rword = rword;)
9768#if ENABLE_HUSH_IF
9769 if (cond_code) {
9770 if (rword == RES_THEN) {
9771 /* if false; then ... fi has exitcode 0! */
9772 G.last_exitcode = rcode = EXIT_SUCCESS;
9773 /* "if <false> THEN cmd": skip cmd */
9774 continue;
9775 }
9776 } else {
9777 if (rword == RES_ELSE || rword == RES_ELIF) {
9778 /* "if <true> then ... ELSE/ELIF cmd":
9779 * skip cmd and all following ones */
9780 break;
9781 }
9782 }
9783#endif
9784#if ENABLE_HUSH_LOOPS
9785 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9786 if (!for_lcur) {
9787 /* first loop through for */
9788
9789 static const char encoded_dollar_at[] ALIGN1 = {
9790 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9791 }; /* encoded representation of "$@" */
9792 static const char *const encoded_dollar_at_argv[] = {
9793 encoded_dollar_at, NULL
9794 }; /* argv list with one element: "$@" */
9795 char **vals;
9796
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009797 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009798 vals = (char**)encoded_dollar_at_argv;
9799 if (pi->next->res_word == RES_IN) {
9800 /* if no variable values after "in" we skip "for" */
9801 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009802 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9803 break;
9804 }
9805 vals = pi->next->cmds[0].argv;
9806 } /* else: "for var; do..." -> assume "$@" list */
9807 /* create list of variable values */
9808 debug_print_strings("for_list made from", vals);
9809 for_list = expand_strvec_to_strvec(vals);
9810 for_lcur = for_list;
9811 debug_print_strings("for_list", for_list);
9812 }
9813 if (!*for_lcur) {
9814 /* "for" loop is over, clean up */
9815 free(for_list);
9816 for_list = NULL;
9817 for_lcur = NULL;
9818 break;
9819 }
9820 /* Insert next value from for_lcur */
9821 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009822 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009823 continue;
9824 }
9825 if (rword == RES_IN) {
9826 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9827 }
9828 if (rword == RES_DONE) {
9829 continue; /* "done" has no cmds too */
9830 }
9831#endif
9832#if ENABLE_HUSH_CASE
9833 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009834 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009835 case_word = expand_string_to_string(pi->cmds->argv[0],
9836 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009837 debug_printf_exec("CASE word1:'%s'\n", case_word);
9838 //unbackslash(case_word);
9839 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009840 continue;
9841 }
9842 if (rword == RES_MATCH) {
9843 char **argv;
9844
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009845 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009846 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9847 break;
9848 /* all prev words didn't match, does this one match? */
9849 argv = pi->cmds->argv;
9850 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009851 char *pattern;
9852 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9853 pattern = expand_string_to_string(*argv,
9854 EXP_FLAG_ESC_GLOB_CHARS,
9855 /*unbackslash:*/ 0
9856 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009857 /* TODO: which FNM_xxx flags to use? */
9858 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009859 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9860 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009861 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009862 if (cond_code == 0) {
9863 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009864 free(case_word);
9865 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009866 break;
9867 }
9868 argv++;
9869 }
9870 continue;
9871 }
9872 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009873 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009874 if (cond_code != 0)
9875 continue; /* not matched yet, skip this pipe */
9876 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009877 if (rword == RES_ESAC) {
9878 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9879 if (case_word) {
9880 /* "case" did not match anything: still set $? (to 0) */
9881 G.last_exitcode = rcode = EXIT_SUCCESS;
9882 }
9883 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009884#endif
9885 /* Just pressing <enter> in shell should check for jobs.
9886 * OTOH, in non-interactive shell this is useless
9887 * and only leads to extra job checks */
9888 if (pi->num_cmds == 0) {
9889 if (G_interactive_fd)
9890 goto check_jobs_and_continue;
9891 continue;
9892 }
9893
9894 /* After analyzing all keywords and conditions, we decided
9895 * to execute this pipe. NB: have to do checkjobs(NULL)
9896 * after run_pipe to collect any background children,
9897 * even if list execution is to be stopped. */
9898 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009899#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009900 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009901#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009902 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9903 if (r != -1) {
9904 /* We ran a builtin, function, or group.
9905 * rcode is already known
9906 * and we don't need to wait for anything. */
9907 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9908 G.last_exitcode = rcode;
9909 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009910#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9911 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9912#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009913#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009914 /* Was it "break" or "continue"? */
9915 if (G.flag_break_continue) {
9916 smallint fbc = G.flag_break_continue;
9917 /* We might fall into outer *loop*,
9918 * don't want to break it too */
9919 if (loop_top) {
9920 G.depth_break_continue--;
9921 if (G.depth_break_continue == 0)
9922 G.flag_break_continue = 0;
9923 /* else: e.g. "continue 2" should *break* once, *then* continue */
9924 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9925 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009926 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009927 break;
9928 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009929 /* "continue": simulate end of loop */
9930 rword = RES_DONE;
9931 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009932 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009933#endif
9934 if (G_flag_return_in_progress == 1) {
9935 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9936 break;
9937 }
9938 } else if (pi->followup == PIPE_BG) {
9939 /* What does bash do with attempts to background builtins? */
9940 /* even bash 3.2 doesn't do that well with nested bg:
9941 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9942 * I'm NOT treating inner &'s as jobs */
9943#if ENABLE_HUSH_JOB
9944 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009945 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009946#endif
9947 /* Last command's pid goes to $! */
9948 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009949 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009950 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009951/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009952 rcode = EXIT_SUCCESS;
9953 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009954 } else {
9955#if ENABLE_HUSH_JOB
9956 if (G.run_list_level == 1 && G_interactive_fd) {
9957 /* Waits for completion, then fg's main shell */
9958 rcode = checkjobs_and_fg_shell(pi);
9959 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009960 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009961 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009962#endif
9963 /* This one just waits for completion */
9964 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9965 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9966 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009967 G.last_exitcode = rcode;
9968 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009969#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9970 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9971#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009972 }
9973
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009974 /* Handle "set -e" */
9975 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9976 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9977 if (G.errexit_depth == 0)
9978 hush_exit(rcode);
9979 }
9980 G.errexit_depth = sv_errexit_depth;
9981
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009982 /* Analyze how result affects subsequent commands */
9983#if ENABLE_HUSH_IF
9984 if (rword == RES_IF || rword == RES_ELIF)
9985 cond_code = rcode;
9986#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009987 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009988 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009989 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009990#if ENABLE_HUSH_LOOPS
9991 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009992 if (pi->next
9993 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009994 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009995 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009996 if (rword == RES_WHILE) {
9997 if (rcode) {
9998 /* "while false; do...done" - exitcode 0 */
9999 G.last_exitcode = rcode = EXIT_SUCCESS;
10000 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +020010001 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010002 }
10003 }
10004 if (rword == RES_UNTIL) {
10005 if (!rcode) {
10006 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010007 break;
10008 }
10009 }
10010 }
10011#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010012 } /* for (pi) */
10013
10014#if ENABLE_HUSH_JOB
10015 G.run_list_level--;
10016#endif
10017#if ENABLE_HUSH_LOOPS
10018 if (loop_top)
10019 G.depth_of_loop--;
10020 free(for_list);
10021#endif
10022#if ENABLE_HUSH_CASE
10023 free(case_word);
10024#endif
10025 debug_leave();
10026 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
10027 return rcode;
10028}
10029
10030/* Select which version we will use */
10031static int run_and_free_list(struct pipe *pi)
10032{
10033 int rcode = 0;
10034 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -080010035 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +020010036 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
10037 rcode = run_list(pi);
10038 }
10039 /* free_pipe_list has the side effect of clearing memory.
10040 * In the long run that function can be merged with run_list,
10041 * but doing that now would hobble the debugging effort. */
10042 free_pipe_list(pi);
10043 debug_printf_exec("run_and_free_list return %d\n", rcode);
10044 return rcode;
10045}
10046
10047
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010048static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +000010049{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010050 sighandler_t old_handler;
10051 unsigned sig = 0;
10052 while ((mask >>= 1) != 0) {
10053 sig++;
10054 if (!(mask & 1))
10055 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +020010056 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010057 /* POSIX allows shell to re-enable SIGCHLD
10058 * even if it was SIG_IGN on entry.
10059 * Therefore we skip IGN check for it:
10060 */
10061 if (sig == SIGCHLD)
10062 continue;
Denys Vlasenko23bc5622020-02-18 16:46:01 +010010063 /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
10064 * Try:
10065 * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
10066 * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
Denys Vlasenko49e6bf22017-08-04 14:28:16 +020010067 */
Denys Vlasenko23bc5622020-02-18 16:46:01 +010010068 if (sig == SIGHUP && G_interactive_fd)
10069 continue;
10070 /* Unless one of the above signals, is it SIG_IGN? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010071 if (old_handler == SIG_IGN) {
10072 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010073 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010074#if ENABLE_HUSH_TRAP
10075 if (!G_traps)
10076 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10077 free(G_traps[sig]);
10078 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
10079#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010080 }
10081 }
10082}
10083
10084/* Called a few times only (or even once if "sh -c") */
10085static void install_special_sighandlers(void)
10086{
Denis Vlasenkof9375282009-04-05 19:13:39 +000010087 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010088
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010089 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010090 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010091 if (G_interactive_fd) {
10092 mask |= SPECIAL_INTERACTIVE_SIGS;
10093 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010094 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010095 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010096 /* Careful, do not re-install handlers we already installed */
10097 if (G.special_sig_mask != mask) {
10098 unsigned diff = mask & ~G.special_sig_mask;
10099 G.special_sig_mask = mask;
10100 install_sighandlers(diff);
10101 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010102}
10103
10104#if ENABLE_HUSH_JOB
10105/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010106/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010107static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +000010108{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010109 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010110
10111 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010112 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +010010113 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
10114 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010115 + (1 << SIGBUS ) * HUSH_DEBUG
10116 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +010010117 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010118 + (1 << SIGABRT)
10119 /* bash 3.2 seems to handle these just like 'fatal' ones */
10120 + (1 << SIGPIPE)
10121 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010122 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010123 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010124 * we never want to restore pgrp on exit, and this fn is not called
10125 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010126 /*+ (1 << SIGHUP )*/
10127 /*+ (1 << SIGTERM)*/
10128 /*+ (1 << SIGINT )*/
10129 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010130 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +020010131
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010132 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010133}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000010134#endif
Eric Andersenada18ff2001-05-21 16:18:22 +000010135
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010136static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +000010137{
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010138 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +000010139 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010140 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -080010141 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010142 break;
10143 case 'x':
10144 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +020010145 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 +010010146 break;
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010147 case 'e':
10148 G.o_opt[OPT_O_ERREXIT] = state;
10149 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010150 case 'o':
10151 if (!o_opt) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010152 /* "set -o" or "set +o" without parameter.
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010153 * in bash, set -o produces this output:
10154 * pipefail off
10155 * and set +o:
10156 * set +o pipefail
10157 * We always use the second form.
10158 */
10159 const char *p = o_opt_strings;
10160 idx = 0;
10161 while (*p) {
10162 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
10163 idx++;
10164 p += strlen(p) + 1;
10165 }
10166 break;
10167 }
10168 idx = index_in_strings(o_opt_strings, o_opt);
10169 if (idx >= 0) {
10170 G.o_opt[idx] = state;
10171 break;
10172 }
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010173 /* fall through to error */
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010174 default:
10175 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +000010176 }
10177 return EXIT_SUCCESS;
10178}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010179
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000010180int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +000010181int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +000010182{
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010183 pid_t cached_getpid;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010184 enum {
10185 OPT_login = (1 << 0),
10186 };
10187 unsigned flags;
Denys Vlasenko63139b52020-12-13 22:00:56 +010010188#if !BB_MMU
10189 unsigned builtin_argc = 0;
10190#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010191 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010192 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010193 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +000010194
Denis Vlasenko574f2f42008-02-27 18:41:59 +000010195 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +020010196 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010197 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010198#if ENABLE_HUSH_TRAP
10199# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010200 G.return_exitcode = -1;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010201# endif
10202 G.pre_trap_exitcode = -1;
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010203#endif
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010204
Denys Vlasenko10c01312011-05-11 11:49:21 +020010205#if ENABLE_HUSH_FAST
10206 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
10207#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010208#if !BB_MMU
10209 G.argv0_for_re_execing = argv[0];
10210#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010211
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010212 cached_getpid = getpid(); /* for tcsetpgrp() during init */
Denys Vlasenko46a71dc2020-12-25 18:49:29 +010010213 G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
10214 G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010215
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010216 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010217 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
10218 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010219 shell_ver = xzalloc(sizeof(*shell_ver));
10220 shell_ver->flg_export = 1;
10221 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +020010222 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +020010223 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010224 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010225
Denys Vlasenko605067b2010-09-06 12:10:51 +020010226 /* Create shell local variables from the values
10227 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010228 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010229 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010230 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010231 if (e) while (*e) {
10232 char *value = strchr(*e, '=');
10233 if (value) { /* paranoia */
10234 cur_var->next = xzalloc(sizeof(*cur_var));
10235 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +000010236 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010237 cur_var->max_len = strlen(*e);
10238 cur_var->flg_export = 1;
10239 }
10240 e++;
10241 }
Denys Vlasenko605067b2010-09-06 12:10:51 +020010242 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010243 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
10244 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +020010245
10246 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010247 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010248
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010249#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010250 /* Set (but not export) HOSTNAME unless already set */
10251 if (!get_local_var_value("HOSTNAME")) {
10252 struct utsname uts;
10253 uname(&uts);
10254 set_local_var_from_halves("HOSTNAME", uts.nodename);
10255 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +020010256#endif
10257 /* IFS is not inherited from the parent environment */
10258 set_local_var_from_halves("IFS", defifs);
10259
Denys Vlasenkoef8985c2019-05-19 16:29:09 +020010260 if (!get_local_var_value("PATH"))
10261 set_local_var_from_halves("PATH", bb_default_root_path);
10262
Denys Vlasenko0c360192019-05-19 15:37:50 +020010263 /* PS1/PS2 are set later, if we determine that we are interactive */
10264
Denys Vlasenko6db47842009-09-05 20:15:17 +020010265 /* bash also exports SHLVL and _,
10266 * and sets (but doesn't export) the following variables:
10267 * BASH=/bin/bash
10268 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
10269 * BASH_VERSION='3.2.0(1)-release'
10270 * HOSTTYPE=i386
10271 * MACHTYPE=i386-pc-linux-gnu
10272 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +020010273 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +020010274 * EUID=<NNNNN>
10275 * UID=<NNNNN>
10276 * GROUPS=()
10277 * LINES=<NNN>
10278 * COLUMNS=<NNN>
10279 * BASH_ARGC=()
10280 * BASH_ARGV=()
10281 * BASH_LINENO=()
10282 * BASH_SOURCE=()
10283 * DIRSTACK=()
10284 * PIPESTATUS=([0]="0")
10285 * HISTFILE=/<xxx>/.bash_history
10286 * HISTFILESIZE=500
10287 * HISTSIZE=500
10288 * MAILCHECK=60
10289 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
10290 * SHELL=/bin/bash
10291 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
10292 * TERM=dumb
10293 * OPTERR=1
10294 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +020010295 * PS4='+ '
10296 */
10297
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010298#if NUM_SCRIPTS > 0
10299 if (argc < 0) {
10300 char *script = get_script_content(-argc - 1);
10301 G.global_argv = argv;
10302 G.global_argc = string_array_len(argv);
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010303 //install_special_sighandlers(); - needed?
10304 parse_and_run_string(script);
10305 goto final_return;
10306 }
10307#endif
10308
Eric Andersen94ac2442001-05-22 19:05:18 +000010309 /* Initialize some more globals to non-zero values */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010310 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +000010311
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010312 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010313 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010314 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010315 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010316 * in order to intercept (more) signals.
10317 */
10318
10319 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010320 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010321 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010322 while (1) {
Denys Vlasenko3b053052021-01-04 03:05:34 +010010323 int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
10324 "cexinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010325#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +000010326 "<:$:R:V:"
10327# if ENABLE_HUSH_FUNCTIONS
10328 "F:"
10329# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010330#endif
10331 );
10332 if (opt <= 0)
10333 break;
Eric Andersen25f27032001-04-26 23:22:31 +000010334 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010335 case 'c':
Denys Vlasenko0ab2dd42020-12-23 02:22:08 +010010336 /* Note: -c is not an option with param!
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010337 * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010338 */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010339 G.opt_c = 1;
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010340 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010341 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010342 /* Well, we cannot just declare interactiveness,
10343 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010344 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010345 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010346 case 's':
Denys Vlasenkof3634582019-06-03 12:21:04 +020010347 G.opt_s = 1;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010348 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010349 case 'l':
10350 flags |= OPT_login;
10351 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010352#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010353 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010354 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010355 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010356 case '$': {
10357 unsigned long long empty_trap_mask;
10358
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010359 G.root_pid = bb_strtou(optarg, &optarg, 16);
10360 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010361 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10362 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010363 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10364 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010365 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010366 optarg++;
10367 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010368 optarg++;
10369 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10370 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010371 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010372 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010373# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010374 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010375 for (sig = 1; sig < NSIG; sig++) {
10376 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010377 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010378 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010379 }
10380 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010381# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010382 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010383# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010384 optarg++;
10385 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010386# endif
Denys Vlasenko49142d42020-12-13 18:44:07 +010010387 /* Suppress "killed by signal" message, -$ hack is used
10388 * for subshells: echo `sh -c 'kill -9 $$'`
10389 * should be silent.
10390 */
10391 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010392# if ENABLE_HUSH_FUNCTIONS
10393 /* nommu uses re-exec trick for "... | func | ...",
10394 * should allow "return".
10395 * This accidentally allows returns in subshells.
10396 */
10397 G_flag_return_in_progress = -1;
10398# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010399 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010400 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010401 case 'R':
10402 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010403 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010404 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010405# if ENABLE_HUSH_FUNCTIONS
10406 case 'F': {
10407 struct function *funcp = new_function(optarg);
10408 /* funcp->name is already set to optarg */
10409 /* funcp->body is set to NULL. It's a special case. */
10410 funcp->body_as_string = argv[optind];
10411 optind++;
10412 break;
10413 }
10414# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010415#endif
Denys Vlasenko3b053052021-01-04 03:05:34 +010010416 /*case '?': invalid option encountered (set_mode('?') will fail) */
10417 /*case 'n':*/
10418 /*case 'x':*/
10419 /*case 'e':*/
10420 default:
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010421 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010422 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010423 bb_show_usage();
Eric Andersen25f27032001-04-26 23:22:31 +000010424 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010425 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010426
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010427 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10428 G.global_argc = argc - (optind - 1);
10429 G.global_argv = argv + (optind - 1);
10430 G.global_argv[0] = argv[0];
10431
Denis Vlasenkof9375282009-04-05 19:13:39 +000010432 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010433 if (flags & OPT_login) {
Denys Vlasenko63139b52020-12-13 22:00:56 +010010434 const char *hp = NULL;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010435 HFILE *input;
Denys Vlasenko63139b52020-12-13 22:00:56 +010010436
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010437 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010438 input = hfopen("/etc/profile");
Denys Vlasenko63139b52020-12-13 22:00:56 +010010439 run_profile:
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010440 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010441 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010442 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010443 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010444 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010445 /* bash: after sourcing /etc/profile,
10446 * tries to source (in the given order):
10447 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010448 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010449 * bash also sources ~/.bash_logout on exit.
10450 * If called as sh, skips .bash_XXX files.
10451 */
Denys Vlasenko63139b52020-12-13 22:00:56 +010010452 if (!hp) { /* unless we looped on the "goto" already */
10453 hp = get_local_var_value("HOME");
10454 if (hp && hp[0]) {
10455 debug_printf("sourcing ~/.profile\n");
10456 hp = concat_path_file(hp, ".profile");
10457 input = hfopen(hp);
10458 free((char*)hp);
10459 goto run_profile;
10460 }
10461 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010462 }
10463
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010464 /* -c takes effect *after* -l */
10465 if (G.opt_c) {
10466 /* Possibilities:
10467 * sh ... -c 'script'
10468 * sh ... -c 'script' ARG0 [ARG1...]
10469 * On NOMMU, if builtin_argc != 0,
10470 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
10471 * "" needs to be replaced with NULL
10472 * and BARGV vector fed to builtin function.
10473 * Note: the form without ARG0 never happens:
10474 * sh ... -c 'builtin' BARGV... ""
10475 */
10476 char *script;
10477
10478 install_special_sighandlers();
10479
10480 G.global_argc--;
10481 G.global_argv++;
Denys Vlasenko49142d42020-12-13 18:44:07 +010010482#if !BB_MMU
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010483 if (builtin_argc) {
10484 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10485 const struct built_in_command *x;
10486 x = find_builtin(G.global_argv[0]);
10487 if (x) { /* paranoia */
10488 argv = G.global_argv;
10489 G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
10490 G.global_argv += builtin_argc + 1;
10491 G.global_argv[-1] = NULL; /* replace "" */
10492 G.last_exitcode = x->b_function(argv);
10493 }
10494 goto final_return;
10495 }
Denys Vlasenko49142d42020-12-13 18:44:07 +010010496#endif
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010497
10498 script = G.global_argv[0];
10499 if (!script)
10500 bb_error_msg_and_die(bb_msg_requires_arg, "-c");
10501 if (!G.global_argv[1]) {
10502 /* -c 'script' (no params): prevent empty $0 */
10503 G.global_argv[0] = argv[0];
10504 } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
10505 G.global_argc--;
10506 G.global_argv++;
10507 }
10508 parse_and_run_string(script);
10509 goto final_return;
10510 }
10511
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010512 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010513 if (!G.opt_s && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010514 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010515 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010516 * "bash <script>" (which is never interactive (unless -i?))
10517 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010518 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010519 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010520 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010521 G.global_argc--;
10522 G.global_argv++;
10523 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010524 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010525 input = hfopen(G.global_argv[0]);
10526 if (!input) {
10527 bb_simple_perror_msg_and_die(G.global_argv[0]);
10528 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010529 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010530 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010531 parse_and_run_file(input);
10532#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010533 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010534#endif
10535 goto final_return;
10536 }
Denys Vlasenkof3634582019-06-03 12:21:04 +020010537 /* "implicit" -s: bare interactive hush shows 's' in $- */
Denys Vlasenkod8740b22019-05-19 19:11:21 +020010538 G.opt_s = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010539
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010540 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010541 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010542 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010543
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010544 /* A shell is interactive if the '-i' flag was given,
10545 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010546 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010547 * no arguments remaining or the -s flag given
10548 * standard input is a terminal
10549 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010550 * Refer to Posix.2, the description of the 'sh' utility.
10551 */
10552#if ENABLE_HUSH_JOB
10553 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010554 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10555 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10556 if (G_saved_tty_pgrp < 0)
10557 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010558
10559 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010560 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010561 if (G_interactive_fd < 0) {
10562 /* try to dup to any fd */
10563 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010564 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010565 /* give up */
10566 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010567 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010568 }
10569 }
Eric Andersen25f27032001-04-26 23:22:31 +000010570 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010571 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010572 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010573 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010574
Mike Frysinger38478a62009-05-20 04:48:06 -040010575 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010576 /* If we were run as 'hush &', sleep until we are
10577 * in the foreground (tty pgrp == our pgrp).
10578 * If we get started under a job aware app (like bash),
10579 * make sure we are now in charge so we don't fight over
10580 * who gets the foreground */
10581 while (1) {
10582 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010583 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10584 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010585 break;
10586 /* send TTIN to ourself (should stop us) */
10587 kill(- shell_pgrp, SIGTTIN);
10588 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010589 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010590
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010591 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010592 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010593
Mike Frysinger38478a62009-05-20 04:48:06 -040010594 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010595 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010596 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010597 /* Put ourselves in our own process group
10598 * (bash, too, does this only if ctty is available) */
10599 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10600 /* Grab control of the terminal */
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010601 tcsetpgrp(G_interactive_fd, cached_getpid);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010602 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010603 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010604
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010605# if ENABLE_FEATURE_EDITING
10606 G.line_input_state = new_line_input_t(FOR_SHELL);
Ron Yorston9e2a5662020-01-21 16:01:58 +000010607# if EDITING_HAS_get_exe_name
10608 G.line_input_state->get_exe_name = get_builtin_name;
10609# endif
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010610# endif
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010611# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10612 {
10613 const char *hp = get_local_var_value("HISTFILE");
10614 if (!hp) {
10615 hp = get_local_var_value("HOME");
10616 if (hp)
10617 hp = concat_path_file(hp, ".hush_history");
10618 } else {
10619 hp = xstrdup(hp);
10620 }
10621 if (hp) {
10622 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010623 //set_local_var(xasprintf("HISTFILE=%s", ...));
10624 }
10625# if ENABLE_FEATURE_SH_HISTFILESIZE
10626 hp = get_local_var_value("HISTFILESIZE");
10627 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10628# endif
10629 }
10630# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010631 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010632 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010633 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010634#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010635 /* No job control compiled in, only prompt/line editing */
10636 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010637 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010638 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010639 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010640 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010641 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010642 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010643 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010644 }
10645 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010646 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010647 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010648 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010649 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010650#else
10651 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010652 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010653#endif
10654 /* bash:
10655 * if interactive but not a login shell, sources ~/.bashrc
10656 * (--norc turns this off, --rcfile <file> overrides)
10657 */
10658
Denys Vlasenko0c360192019-05-19 15:37:50 +020010659 if (G_interactive_fd) {
10660#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
10661 /* Set (but not export) PS1/2 unless already set */
10662 if (!get_local_var_value("PS1"))
10663 set_local_var_from_halves("PS1", "\\w \\$ ");
10664 if (!get_local_var_value("PS2"))
10665 set_local_var_from_halves("PS2", "> ");
10666#endif
10667 if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
10668 /* note: ash and hush share this string */
10669 printf("\n\n%s %s\n"
10670 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10671 "\n",
10672 bb_banner,
10673 "hush - the humble shell"
10674 );
10675 }
Mike Frysingerb2705e12009-03-23 08:44:02 +000010676 }
10677
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010678 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010679
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010680 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010681 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010682}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010683
10684
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010685/*
10686 * Built-ins
10687 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010688static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010689{
10690 return 0;
10691}
10692
Denys Vlasenko265062d2017-01-10 15:13:30 +010010693#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenkoa8e19602020-12-14 03:52:54 +010010694static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010695{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010696 int argc = string_array_len(argv);
10697 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010698}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010699#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010700#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010701static int FAST_FUNC builtin_test(char **argv)
10702{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010703 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010704}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010705#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010706#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010707static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010708{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010709 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010710}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010711#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010712#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010713static int FAST_FUNC builtin_printf(char **argv)
10714{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010715 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010716}
10717#endif
10718
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010719#if ENABLE_HUSH_HELP
10720static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10721{
10722 const struct built_in_command *x;
10723
10724 printf(
10725 "Built-in commands:\n"
10726 "------------------\n");
10727 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10728 if (x->b_descr)
10729 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10730 }
10731 return EXIT_SUCCESS;
10732}
10733#endif
10734
10735#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10736static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10737{
Ron Yorston9f3b4102019-12-16 09:31:10 +000010738 show_history(G.line_input_state);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010739 return EXIT_SUCCESS;
10740}
10741#endif
10742
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010743static char **skip_dash_dash(char **argv)
10744{
10745 argv++;
10746 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10747 argv++;
10748 return argv;
10749}
10750
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010751static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010752{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010753 const char *newdir;
10754
10755 argv = skip_dash_dash(argv);
10756 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010757 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010758 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010759 * bash says "bash: cd: HOME not set" and does nothing
10760 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010761 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010762 const char *home = get_local_var_value("HOME");
10763 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010764 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010765 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010766 /* Mimic bash message exactly */
10767 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010768 return EXIT_FAILURE;
10769 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010770 /* Read current dir (get_cwd(1) is inside) and set PWD.
10771 * Note: do not enforce exporting. If PWD was unset or unexported,
10772 * set it again, but do not export. bash does the same.
10773 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010774 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010775 return EXIT_SUCCESS;
10776}
10777
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010778static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10779{
10780 puts(get_cwd(0));
10781 return EXIT_SUCCESS;
10782}
10783
10784static int FAST_FUNC builtin_eval(char **argv)
10785{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010786 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010787
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010788 if (!argv[0])
10789 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010790
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010791 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010792 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010793 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010794 /* bash:
10795 * eval "echo Hi; done" ("done" is syntax error):
10796 * "echo Hi" will not execute too.
10797 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010798 parse_and_run_string(argv[0]);
10799 } else {
10800 /* "The eval utility shall construct a command by
10801 * concatenating arguments together, separating
10802 * each with a <space> character."
10803 */
10804 char *str, *p;
10805 unsigned len = 0;
10806 char **pp = argv;
10807 do
10808 len += strlen(*pp) + 1;
10809 while (*++pp);
10810 str = p = xmalloc(len);
10811 pp = argv;
10812 for (;;) {
10813 p = stpcpy(p, *pp);
10814 pp++;
10815 if (!*pp)
10816 break;
10817 *p++ = ' ';
10818 }
10819 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010820 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010821 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010822 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010823 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010824 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010825}
10826
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010827static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010828{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010829 argv = skip_dash_dash(argv);
10830 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010831 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010832
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010833 /* Careful: we can end up here after [v]fork. Do not restore
10834 * tty pgrp then, only top-level shell process does that */
10835 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10836 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10837
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010838 /* Saved-redirect fds, script fds and G_interactive_fd are still
10839 * open here. However, they are all CLOEXEC, and execv below
10840 * closes them. Try interactive "exec ls -l /proc/self/fd",
10841 * it should show no extra open fds in the "ls" process.
10842 * If we'd try to run builtins/NOEXECs, this would need improving.
10843 */
10844 //close_saved_fds_and_FILE_fds();
10845
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010846 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010847 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010848 * and tcsetpgrp, and this is inherently racy.
10849 */
10850 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010851}
10852
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010853static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010854{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010855 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010856
10857 /* interactive bash:
10858 * # trap "echo EEE" EXIT
10859 * # exit
10860 * exit
10861 * There are stopped jobs.
10862 * (if there are _stopped_ jobs, running ones don't count)
10863 * # exit
10864 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010865 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010866 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010867 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010868 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010869
10870 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010871 argv = skip_dash_dash(argv);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010872 if (argv[0] == NULL) {
10873#if ENABLE_HUSH_TRAP
10874 if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
10875 hush_exit(G.pre_trap_exitcode);
10876#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010877 hush_exit(G.last_exitcode);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010878 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010879 /* mimic bash: exit 123abc == exit 255 + error msg */
10880 xfunc_error_retval = 255;
10881 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010882 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010883}
10884
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010885#if ENABLE_HUSH_TYPE
10886/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10887static int FAST_FUNC builtin_type(char **argv)
10888{
10889 int ret = EXIT_SUCCESS;
10890
10891 while (*++argv) {
10892 const char *type;
10893 char *path = NULL;
10894
10895 if (0) {} /* make conditional compile easier below */
10896 /*else if (find_alias(*argv))
10897 type = "an alias";*/
Denys Vlasenko259747c2019-11-28 10:28:14 +010010898# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010899 else if (find_function(*argv))
10900 type = "a function";
Denys Vlasenko259747c2019-11-28 10:28:14 +010010901# endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010902 else if (find_builtin(*argv))
10903 type = "a shell builtin";
10904 else if ((path = find_in_path(*argv)) != NULL)
10905 type = path;
10906 else {
10907 bb_error_msg("type: %s: not found", *argv);
10908 ret = EXIT_FAILURE;
10909 continue;
10910 }
10911
10912 printf("%s is %s\n", *argv, type);
10913 free(path);
10914 }
10915
10916 return ret;
10917}
10918#endif
10919
10920#if ENABLE_HUSH_READ
10921/* Interruptibility of read builtin in bash
10922 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10923 *
10924 * Empty trap makes read ignore corresponding signal, for any signal.
10925 *
10926 * SIGINT:
10927 * - terminates non-interactive shell;
10928 * - interrupts read in interactive shell;
10929 * if it has non-empty trap:
10930 * - executes trap and returns to command prompt in interactive shell;
10931 * - executes trap and returns to read in non-interactive shell;
10932 * SIGTERM:
10933 * - is ignored (does not interrupt) read in interactive shell;
10934 * - terminates non-interactive shell;
10935 * if it has non-empty trap:
10936 * - executes trap and returns to read;
10937 * SIGHUP:
10938 * - terminates shell (regardless of interactivity);
10939 * if it has non-empty trap:
10940 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010941 * SIGCHLD from children:
10942 * - does not interrupt read regardless of interactivity:
10943 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010944 */
10945static int FAST_FUNC builtin_read(char **argv)
10946{
10947 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010948 struct builtin_read_params params;
10949
10950 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010951
10952 /* "!": do not abort on errors.
10953 * Option string must start with "sr" to match BUILTIN_READ_xxx
10954 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010955 params.read_flags = getopt32(argv,
Denys Vlasenko259747c2019-11-28 10:28:14 +010010956# if BASH_READ_D
Denys Vlasenko457825f2021-06-06 12:07:11 +020010957 IF_NOT_HUSH_BASH_COMPAT("^")
10958 "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
10959 &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko259747c2019-11-28 10:28:14 +010010960# else
Denys Vlasenko457825f2021-06-06 12:07:11 +020010961 IF_NOT_HUSH_BASH_COMPAT("^")
10962 "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
10963 &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko259747c2019-11-28 10:28:14 +010010964# endif
Denys Vlasenko457825f2021-06-06 12:07:11 +020010965//TODO: print "read: need variable name"
10966//for the case of !BASH "read" with no args (now it fails silently)
10967//(or maybe extend getopt32() to emit a message if "-1" fails)
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010968 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010969 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010970 return EXIT_FAILURE;
10971 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010972 params.argv = argv;
10973 params.setvar = set_local_var_from_halves;
10974 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010975
10976 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010977 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010978
10979 if ((uintptr_t)r == 1 && errno == EINTR) {
10980 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010981 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010982 goto again;
10983 }
10984
10985 if ((uintptr_t)r > 1) {
James Byrne69374872019-07-02 11:35:03 +020010986 bb_simple_error_msg(r);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010987 r = (char*)(uintptr_t)1;
10988 }
10989
10990 return (uintptr_t)r;
10991}
10992#endif
10993
10994#if ENABLE_HUSH_UMASK
10995static int FAST_FUNC builtin_umask(char **argv)
10996{
10997 int rc;
10998 mode_t mask;
10999
11000 rc = 1;
11001 mask = umask(0);
11002 argv = skip_dash_dash(argv);
11003 if (argv[0]) {
11004 mode_t old_mask = mask;
11005
11006 /* numeric umasks are taken as-is */
11007 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
11008 if (!isdigit(argv[0][0]))
11009 mask ^= 0777;
11010 mask = bb_parse_mode(argv[0], mask);
11011 if (!isdigit(argv[0][0]))
11012 mask ^= 0777;
11013 if ((unsigned)mask > 0777) {
11014 mask = old_mask;
11015 /* bash messages:
11016 * bash: umask: 'q': invalid symbolic mode operator
11017 * bash: umask: 999: octal number out of range
11018 */
11019 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
11020 rc = 0;
11021 }
11022 } else {
11023 /* Mimic bash */
11024 printf("%04o\n", (unsigned) mask);
11025 /* fall through and restore mask which we set to 0 */
11026 }
11027 umask(mask);
11028
11029 return !rc; /* rc != 0 - success */
11030}
11031#endif
11032
Denys Vlasenko41ade052017-01-08 18:56:24 +010011033#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011034static void print_escaped(const char *s)
11035{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020011036 if (*s == '\'')
11037 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011038 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020011039 const char *p = strchrnul(s, '\'');
11040 /* print 'xxxx', possibly just '' */
11041 printf("'%.*s'", (int)(p - s), s);
11042 if (*p == '\0')
11043 break;
11044 s = p;
11045 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011046 /* s points to '; print "'''...'''" */
11047 putchar('"');
11048 do putchar('\''); while (*++s == '\'');
11049 putchar('"');
11050 } while (*s);
11051}
Denys Vlasenko41ade052017-01-08 18:56:24 +010011052#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011053
Denys Vlasenko1e660422017-07-17 21:10:50 +020011054#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011055static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020011056{
11057 do {
11058 char *name = *argv;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020011059 const char *name_end = endofname(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011060
Denys Vlasenko27c56f12010-09-07 09:56:34 +020011061 if (*name_end == '\0') {
11062 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020011063
Denys Vlasenko27c56f12010-09-07 09:56:34 +020011064 vpp = get_ptr_to_local_var(name, name_end - name);
11065 var = vpp ? *vpp : NULL;
11066
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011067 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020011068 /* export -n NAME (without =VALUE) */
11069 if (var) {
11070 var->flg_export = 0;
11071 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
11072 unsetenv(name);
11073 } /* else: export -n NOT_EXISTING_VAR: no-op */
11074 continue;
11075 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011076 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020011077 /* export NAME (without =VALUE) */
11078 if (var) {
11079 var->flg_export = 1;
11080 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
11081 putenv(var->varstr);
11082 continue;
11083 }
11084 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020011085 if (flags & SETFLAG_MAKE_RO) {
11086 /* readonly NAME (without =VALUE) */
11087 if (var) {
11088 var->flg_read_only = 1;
11089 continue;
11090 }
11091 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011092# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020011093 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011094 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020011095 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
11096 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020011097 /* "local x=abc; ...; local x" - ignore second local decl */
11098 continue;
11099 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011100 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011101# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020011102 /* Exporting non-existing variable.
11103 * bash does not put it in environment,
11104 * but remembers that it is exported,
11105 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020011106 * We just set it to "" and export.
11107 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020011108 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020011109 * bash sets the value to "".
11110 */
11111 /* Or, it's "readonly NAME" (without =VALUE).
11112 * bash remembers NAME and disallows its creation
11113 * in the future.
11114 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020011115 name = xasprintf("%s=", name);
11116 } else {
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020011117 if (*name_end != '=') {
11118 bb_error_msg("'%s': bad variable name", name);
11119 /* do not parse following argv[]s: */
11120 return 1;
11121 }
Denys Vlasenko295fef82009-06-03 12:47:26 +020011122 /* (Un)exporting/making local NAME=VALUE */
11123 name = xstrdup(name);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020011124 /* Testcase: export PS1='\w \$ ' */
11125 unbackslash(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011126 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020011127 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020011128 if (set_local_var(name, flags))
11129 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020011130 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020011131 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020011132}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011133#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020011134
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011135#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011136static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011137{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000011138 unsigned opt_unexport;
11139
Denys Vlasenko259747c2019-11-28 10:28:14 +010011140# if ENABLE_HUSH_EXPORT_N
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020011141 /* "!": do not abort on errors */
11142 opt_unexport = getopt32(argv, "!n");
11143 if (opt_unexport == (uint32_t)-1)
11144 return EXIT_FAILURE;
11145 argv += optind;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011146# else
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020011147 opt_unexport = 0;
11148 argv++;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011149# endif
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020011150
11151 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011152 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011153 if (e) {
11154 while (*e) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010011155# if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011156 puts(*e++);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011157# else
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011158 /* ash emits: export VAR='VAL'
11159 * bash: declare -x VAR="VAL"
11160 * we follow ash example */
11161 const char *s = *e++;
11162 const char *p = strchr(s, '=');
11163
11164 if (!p) /* wtf? take next variable */
11165 continue;
11166 /* export var= */
11167 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011168 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011169 putchar('\n');
Denys Vlasenko259747c2019-11-28 10:28:14 +010011170# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011171 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011172 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011173 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011174 return EXIT_SUCCESS;
11175 }
11176
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011177 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011178}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011179#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011180
Denys Vlasenko295fef82009-06-03 12:47:26 +020011181#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011182static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020011183{
11184 if (G.func_nest_level == 0) {
11185 bb_error_msg("%s: not in a function", argv[0]);
11186 return EXIT_FAILURE; /* bash compat */
11187 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020011188 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020011189 /* Since all builtins run in a nested variable level,
11190 * need to use level - 1 here. Or else the variable will be removed at once
11191 * after builtin returns.
11192 */
11193 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011194}
11195#endif
11196
Denys Vlasenko1e660422017-07-17 21:10:50 +020011197#if ENABLE_HUSH_READONLY
11198static int FAST_FUNC builtin_readonly(char **argv)
11199{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011200 argv++;
11201 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020011202 /* bash: readonly [-p]: list all readonly VARs
11203 * (-p has no effect in bash)
11204 */
11205 struct variable *e;
11206 for (e = G.top_var; e; e = e->next) {
11207 if (e->flg_read_only) {
11208//TODO: quote value: readonly VAR='VAL'
11209 printf("readonly %s\n", e->varstr);
11210 }
11211 }
11212 return EXIT_SUCCESS;
11213 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011214 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020011215}
11216#endif
11217
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011218#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011219/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
11220static int FAST_FUNC builtin_unset(char **argv)
11221{
11222 int ret;
11223 unsigned opts;
11224
11225 /* "!": do not abort on errors */
11226 /* "+": stop at 1st non-option */
11227 opts = getopt32(argv, "!+vf");
11228 if (opts == (unsigned)-1)
11229 return EXIT_FAILURE;
11230 if (opts == 3) {
James Byrne69374872019-07-02 11:35:03 +020011231 bb_simple_error_msg("unset: -v and -f are exclusive");
Denys Vlasenko61508d92016-10-02 21:12:02 +020011232 return EXIT_FAILURE;
11233 }
11234 argv += optind;
11235
11236 ret = EXIT_SUCCESS;
11237 while (*argv) {
11238 if (!(opts & 2)) { /* not -f */
11239 if (unset_local_var(*argv)) {
11240 /* unset <nonexistent_var> doesn't fail.
11241 * Error is when one tries to unset RO var.
11242 * Message was printed by unset_local_var. */
11243 ret = EXIT_FAILURE;
11244 }
11245 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011246# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020011247 else {
11248 unset_func(*argv);
11249 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011250# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011251 argv++;
11252 }
11253 return ret;
11254}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011255#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011256
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011257#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011258/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
11259 * built-in 'set' handler
11260 * SUSv3 says:
11261 * set [-abCefhmnuvx] [-o option] [argument...]
11262 * set [+abCefhmnuvx] [+o option] [argument...]
11263 * set -- [argument...]
11264 * set -o
11265 * set +o
11266 * Implementations shall support the options in both their hyphen and
11267 * plus-sign forms. These options can also be specified as options to sh.
11268 * Examples:
11269 * Write out all variables and their values: set
11270 * Set $1, $2, and $3 and set "$#" to 3: set c a b
11271 * Turn on the -x and -v options: set -xv
11272 * Unset all positional parameters: set --
11273 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
11274 * Set the positional parameters to the expansion of x, even if x expands
11275 * with a leading '-' or '+': set -- $x
11276 *
11277 * So far, we only support "set -- [argument...]" and some of the short names.
11278 */
11279static int FAST_FUNC builtin_set(char **argv)
11280{
11281 int n;
11282 char **pp, **g_argv;
11283 char *arg = *++argv;
11284
11285 if (arg == NULL) {
11286 struct variable *e;
11287 for (e = G.top_var; e; e = e->next)
11288 puts(e->varstr);
11289 return EXIT_SUCCESS;
11290 }
11291
11292 do {
11293 if (strcmp(arg, "--") == 0) {
11294 ++argv;
11295 goto set_argv;
11296 }
11297 if (arg[0] != '+' && arg[0] != '-')
11298 break;
11299 for (n = 1; arg[n]; ++n) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020011300 if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
11301 bb_error_msg("%s: %s: invalid option", "set", arg);
11302 return EXIT_FAILURE;
11303 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011304 if (arg[n] == 'o' && argv[1])
11305 argv++;
11306 }
11307 } while ((arg = *++argv) != NULL);
11308 /* Now argv[0] is 1st argument */
11309
11310 if (arg == NULL)
11311 return EXIT_SUCCESS;
11312 set_argv:
11313
11314 /* NB: G.global_argv[0] ($0) is never freed/changed */
11315 g_argv = G.global_argv;
11316 if (G.global_args_malloced) {
11317 pp = g_argv;
11318 while (*++pp)
11319 free(*pp);
11320 g_argv[1] = NULL;
11321 } else {
11322 G.global_args_malloced = 1;
11323 pp = xzalloc(sizeof(pp[0]) * 2);
11324 pp[0] = g_argv[0]; /* retain $0 */
11325 g_argv = pp;
11326 }
11327 /* This realloc's G.global_argv */
11328 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
11329
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020011330 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020011331
11332 return EXIT_SUCCESS;
Denys Vlasenko61508d92016-10-02 21:12:02 +020011333}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011334#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011335
11336static int FAST_FUNC builtin_shift(char **argv)
11337{
11338 int n = 1;
11339 argv = skip_dash_dash(argv);
11340 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020011341 n = bb_strtou(argv[0], NULL, 10);
11342 if (errno || n < 0) {
11343 /* shared string with ash.c */
11344 bb_error_msg("Illegal number: %s", argv[0]);
11345 /*
11346 * ash aborts in this case.
11347 * bash prints error message and set $? to 1.
11348 * Interestingly, for "shift 99999" bash does not
11349 * print error message, but does set $? to 1
11350 * (and does no shifting at all).
11351 */
11352 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011353 }
11354 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010011355 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020011356 int m = 1;
11357 while (m <= n)
11358 free(G.global_argv[m++]);
11359 }
11360 G.global_argc -= n;
11361 memmove(&G.global_argv[1], &G.global_argv[n+1],
11362 G.global_argc * sizeof(G.global_argv[0]));
11363 return EXIT_SUCCESS;
11364 }
11365 return EXIT_FAILURE;
11366}
11367
Denys Vlasenko74d40582017-08-11 01:32:46 +020011368#if ENABLE_HUSH_GETOPTS
11369static int FAST_FUNC builtin_getopts(char **argv)
11370{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011371/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11372
Denys Vlasenko74d40582017-08-11 01:32:46 +020011373TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011374If a required argument is not found, and getopts is not silent,
11375a question mark (?) is placed in VAR, OPTARG is unset, and a
11376diagnostic message is printed. If getopts is silent, then a
11377colon (:) is placed in VAR and OPTARG is set to the option
11378character found.
11379
11380Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011381
11382"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011383*/
11384 char cbuf[2];
11385 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011386 int c, n, exitcode, my_opterr;
11387 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011388
11389 optstring = *++argv;
11390 if (!optstring || !(var = *++argv)) {
James Byrne69374872019-07-02 11:35:03 +020011391 bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
Denys Vlasenko74d40582017-08-11 01:32:46 +020011392 return EXIT_FAILURE;
11393 }
11394
Denys Vlasenko238ff982017-08-29 13:38:30 +020011395 if (argv[1])
11396 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11397 else
11398 argv = G.global_argv;
11399 cbuf[1] = '\0';
11400
11401 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011402 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011403 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011404 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011405 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011406 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011407
11408 /* getopts stops on first non-option. Add "+" to force that */
11409 /*if (optstring[0] != '+')*/ {
11410 char *s = alloca(strlen(optstring) + 2);
11411 sprintf(s, "+%s", optstring);
11412 optstring = s;
11413 }
11414
Denys Vlasenko238ff982017-08-29 13:38:30 +020011415 /* Naively, now we should just
11416 * cp = get_local_var_value("OPTIND");
11417 * optind = cp ? atoi(cp) : 0;
11418 * optarg = NULL;
11419 * opterr = my_opterr;
11420 * c = getopt(string_array_len(argv), argv, optstring);
11421 * and be done? Not so fast...
11422 * Unlike normal getopt() usage in C programs, here
11423 * each successive call will (usually) have the same argv[] CONTENTS,
11424 * but not the ADDRESSES. Worse yet, it's possible that between
11425 * invocations of "getopts", there will be calls to shell builtins
11426 * which use getopt() internally. Example:
11427 * while getopts "abc" RES -a -bc -abc de; do
11428 * unset -ff func
11429 * done
11430 * This would not work correctly: getopt() call inside "unset"
11431 * modifies internal libc state which is tracking position in
11432 * multi-option strings ("-abc"). At best, it can skip options
11433 * or return the same option infinitely. With glibc implementation
11434 * of getopt(), it would use outright invalid pointers and return
11435 * garbage even _without_ "unset" mangling internal state.
11436 *
11437 * We resort to resetting getopt() state and calling it N times,
11438 * until we get Nth result (or failure).
11439 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11440 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011441 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011442 count = 0;
11443 n = string_array_len(argv);
11444 do {
11445 optarg = NULL;
11446 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11447 c = getopt(n, argv, optstring);
11448 if (c < 0)
11449 break;
11450 count++;
11451 } while (count <= G.getopt_count);
11452
11453 /* Set OPTIND. Prevent resetting of the magic counter! */
11454 set_local_var_from_halves("OPTIND", utoa(optind));
11455 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011456 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011457
11458 /* Set OPTARG */
11459 /* Always set or unset, never left as-is, even on exit/error:
11460 * "If no option was found, or if the option that was found
11461 * does not have an option-argument, OPTARG shall be unset."
11462 */
11463 cp = optarg;
11464 if (c == '?') {
11465 /* If ":optstring" and unknown option is seen,
11466 * it is stored to OPTARG.
11467 */
11468 if (optstring[1] == ':') {
11469 cbuf[0] = optopt;
11470 cp = cbuf;
11471 }
11472 }
11473 if (cp)
11474 set_local_var_from_halves("OPTARG", cp);
11475 else
11476 unset_local_var("OPTARG");
11477
11478 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011479 exitcode = EXIT_SUCCESS;
11480 if (c < 0) { /* -1: end of options */
11481 exitcode = EXIT_FAILURE;
11482 c = '?';
11483 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011484
Denys Vlasenko238ff982017-08-29 13:38:30 +020011485 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011486 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011487 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011488
Denys Vlasenko74d40582017-08-11 01:32:46 +020011489 return exitcode;
11490}
11491#endif
11492
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011493static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011494{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011495 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011496 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011497 save_arg_t sv;
11498 char *args_need_save;
11499#if ENABLE_HUSH_FUNCTIONS
11500 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011501#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011502
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011503 argv = skip_dash_dash(argv);
11504 filename = argv[0];
11505 if (!filename) {
11506 /* bash says: "bash: .: filename argument required" */
11507 return 2; /* bash compat */
11508 }
11509 arg_path = NULL;
11510 if (!strchr(filename, '/')) {
11511 arg_path = find_in_path(filename);
11512 if (arg_path)
11513 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011514 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011515 errno = ENOENT;
11516 bb_simple_perror_msg(filename);
11517 return EXIT_FAILURE;
11518 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011519 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011520 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011521 free(arg_path);
11522 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011523 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011524 /* POSIX: non-interactive shell should abort here,
11525 * not merely fail. So far no one complained :)
11526 */
11527 return EXIT_FAILURE;
11528 }
11529
11530#if ENABLE_HUSH_FUNCTIONS
11531 sv_flg = G_flag_return_in_progress;
11532 /* "we are inside sourced file, ok to use return" */
11533 G_flag_return_in_progress = -1;
11534#endif
11535 args_need_save = argv[1]; /* used as a boolean variable */
11536 if (args_need_save)
11537 save_and_replace_G_args(&sv, argv);
11538
11539 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11540 G.last_exitcode = 0;
11541 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011542 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011543
11544 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11545 restore_G_args(&sv, argv);
11546#if ENABLE_HUSH_FUNCTIONS
11547 G_flag_return_in_progress = sv_flg;
11548#endif
11549
11550 return G.last_exitcode;
11551}
11552
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011553#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011554static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011555{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011556 int sig;
11557 char *new_cmd;
11558
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011559 if (!G_traps)
11560 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011561
11562 argv++;
11563 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011564 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011565 /* No args: print all trapped */
11566 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011567 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011568 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011569 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011570 /* note: bash adds "SIG", but only if invoked
11571 * as "bash". If called as "sh", or if set -o posix,
11572 * then it prints short signal names.
11573 * We are printing short names: */
11574 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011575 }
11576 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011577 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011578 return EXIT_SUCCESS;
11579 }
11580
11581 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011582 /* If first arg is a number: reset all specified signals */
11583 sig = bb_strtou(*argv, NULL, 10);
11584 if (errno == 0) {
11585 int ret;
11586 process_sig_list:
11587 ret = EXIT_SUCCESS;
11588 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011589 sighandler_t handler;
11590
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011591 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011592 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011593 ret = EXIT_FAILURE;
11594 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011595 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011596 continue;
11597 }
11598
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011599 free(G_traps[sig]);
11600 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011601
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011602 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011603 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011604
11605 /* There is no signal for 0 (EXIT) */
11606 if (sig == 0)
11607 continue;
11608
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011609 if (new_cmd)
11610 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11611 else
11612 /* We are removing trap handler */
11613 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011614 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011615 }
11616 return ret;
11617 }
11618
11619 if (!argv[1]) { /* no second arg */
James Byrne69374872019-07-02 11:35:03 +020011620 bb_simple_error_msg("trap: invalid arguments");
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011621 return EXIT_FAILURE;
11622 }
11623
11624 /* First arg is "-": reset all specified to default */
11625 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11626 /* Everything else: set arg as signal handler
11627 * (includes "" case, which ignores signal) */
11628 if (argv[0][0] == '-') {
11629 if (argv[0][1] == '\0') { /* "-" */
11630 /* new_cmd remains NULL: "reset these sigs" */
11631 goto reset_traps;
11632 }
11633 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11634 argv++;
11635 }
11636 /* else: "-something", no special meaning */
11637 }
11638 new_cmd = *argv;
11639 reset_traps:
11640 argv++;
11641 goto process_sig_list;
11642}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011643#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011644
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011645#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011646static struct pipe *parse_jobspec(const char *str)
11647{
11648 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011649 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011650
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011651 if (sscanf(str, "%%%u", &jobnum) != 1) {
11652 if (str[0] != '%'
11653 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11654 ) {
11655 bb_error_msg("bad argument '%s'", str);
11656 return NULL;
11657 }
11658 /* It is "%%", "%+" or "%" - current job */
11659 jobnum = G.last_jobid;
11660 if (jobnum == 0) {
James Byrne69374872019-07-02 11:35:03 +020011661 bb_simple_error_msg("no current job");
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011662 return NULL;
11663 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011664 }
11665 for (pi = G.job_list; pi; pi = pi->next) {
11666 if (pi->jobid == jobnum) {
11667 return pi;
11668 }
11669 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011670 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011671 return NULL;
11672}
11673
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011674static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11675{
11676 struct pipe *job;
11677 const char *status_string;
11678
11679 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11680 for (job = G.job_list; job; job = job->next) {
11681 if (job->alive_cmds == job->stopped_cmds)
11682 status_string = "Stopped";
11683 else
11684 status_string = "Running";
11685
11686 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11687 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011688
11689 clean_up_last_dead_job();
11690
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011691 return EXIT_SUCCESS;
11692}
11693
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011694/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011695static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011696{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011697 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011698 struct pipe *pi;
11699
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011700 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011701 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011702
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011703 /* If they gave us no args, assume they want the last backgrounded task */
11704 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011705 for (pi = G.job_list; pi; pi = pi->next) {
11706 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011707 goto found;
11708 }
11709 }
11710 bb_error_msg("%s: no current job", argv[0]);
11711 return EXIT_FAILURE;
11712 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011713
11714 pi = parse_jobspec(argv[1]);
11715 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011716 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011717 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011718 /* TODO: bash prints a string representation
11719 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011720 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011721 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011722 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011723 }
11724
11725 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011726 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11727 for (i = 0; i < pi->num_cmds; i++) {
11728 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011729 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011730 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011731
11732 i = kill(- pi->pgrp, SIGCONT);
11733 if (i < 0) {
11734 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011735 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011736 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011737 }
James Byrne69374872019-07-02 11:35:03 +020011738 bb_simple_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011739 }
11740
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011741 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011742 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011743 return checkjobs_and_fg_shell(pi);
11744 }
11745 return EXIT_SUCCESS;
11746}
11747#endif
11748
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011749#if ENABLE_HUSH_KILL
11750static int FAST_FUNC builtin_kill(char **argv)
11751{
11752 int ret = 0;
11753
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011754# if ENABLE_HUSH_JOB
11755 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11756 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011757
11758 do {
11759 struct pipe *pi;
11760 char *dst;
11761 int j, n;
11762
11763 if (argv[i][0] != '%')
11764 continue;
11765 /*
11766 * "kill %N" - job kill
11767 * Converting to pgrp / pid kill
11768 */
11769 pi = parse_jobspec(argv[i]);
11770 if (!pi) {
11771 /* Eat bad jobspec */
11772 j = i;
11773 do {
11774 j++;
11775 argv[j - 1] = argv[j];
11776 } while (argv[j]);
11777 ret = 1;
11778 i--;
11779 continue;
11780 }
11781 /*
11782 * In jobs started under job control, we signal
11783 * entire process group by kill -PGRP_ID.
11784 * This happens, f.e., in interactive shell.
11785 *
11786 * Otherwise, we signal each child via
11787 * kill PID1 PID2 PID3.
11788 * Testcases:
11789 * sh -c 'sleep 1|sleep 1 & kill %1'
11790 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11791 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11792 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011793 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011794 dst = alloca(n * sizeof(int)*4);
11795 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011796 if (G_interactive_fd)
11797 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011798 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011799 struct command *cmd = &pi->cmds[j];
11800 /* Skip exited members of the job */
11801 if (cmd->pid == 0)
11802 continue;
11803 /*
11804 * kill_main has matching code to expect
11805 * leading space. Needed to not confuse
11806 * negative pids with "kill -SIGNAL_NO" syntax
11807 */
11808 dst += sprintf(dst, " %u", (int)cmd->pid);
11809 }
11810 *dst = '\0';
11811 } while (argv[++i]);
11812 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011813# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011814
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011815 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011816 ret = run_applet_main(argv, kill_main);
11817 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011818 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011819 return ret;
11820}
11821#endif
11822
11823#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011824/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011825# if !ENABLE_HUSH_JOB
11826# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11827# endif
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011828static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011829{
11830 int ret = 0;
11831 for (;;) {
11832 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011833 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011834
Denys Vlasenko830ea352016-11-08 04:59:11 +010011835 if (!sigisemptyset(&G.pending_set))
11836 goto check_sig;
11837
Denys Vlasenko7e675362016-10-28 21:57:31 +020011838 /* waitpid is not interruptible by SA_RESTARTed
11839 * signals which we use. Thus, this ugly dance:
11840 */
11841
11842 /* Make sure possible SIGCHLD is stored in kernel's
11843 * pending signal mask before we call waitpid.
11844 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011845 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011846 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011847 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011848 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011849
11850 if (!sigisemptyset(&G.pending_set)) {
11851 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011852 goto restore;
11853 }
11854
11855 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011856/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011857 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011858 debug_printf_exec("checkjobs:%d\n", ret);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011859# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011860 if (waitfor_pipe) {
11861 int rcode = job_exited_or_stopped(waitfor_pipe);
11862 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11863 if (rcode >= 0) {
11864 ret = rcode;
11865 sigprocmask(SIG_SETMASK, &oldset, NULL);
11866 break;
11867 }
11868 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011869# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011870 /* if ECHILD, there are no children (ret is -1 or 0) */
11871 /* if ret == 0, no children changed state */
11872 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011873 if (errno == ECHILD || ret) {
11874 ret--;
11875 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011876 ret = 0;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011877# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011878 if (waitfor_pid == -1 && errno == ECHILD) {
11879 /* exitcode of "wait -n" with no children is 127, not 0 */
11880 ret = 127;
11881 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011882# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011883 sigprocmask(SIG_SETMASK, &oldset, NULL);
11884 break;
11885 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011886 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011887 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11888 /* Note: sigsuspend invokes signal handler */
11889 sigsuspend(&oldset);
Denys Vlasenko23bc5622020-02-18 16:46:01 +010011890 /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
11891 * to make sure SIGCHLD is not masked off?
11892 * It was reported that this:
11893 * fn() { : | return; }
11894 * shopt -s lastpipe
11895 * fn
11896 * exec hush SCRIPT
11897 * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
11898 * making "wait" commands in SCRIPT block forever.
11899 */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011900 restore:
11901 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011902 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011903 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011904 sig = check_and_run_traps();
11905 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011906 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko93e2a222020-12-23 12:23:21 +010011907 ret = 128 | sig;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011908 break;
11909 }
11910 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11911 }
11912 return ret;
11913}
11914
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011915static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011916{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011917 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011918 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011919
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011920 argv = skip_dash_dash(argv);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011921# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011922 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011923 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011924 /* (bash accepts "wait -n PID" too and ignores PID) */
11925 G.dead_job_exitcode = -1;
11926 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011927 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011928# endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011929 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011930 /* Don't care about wait results */
11931 /* Note 1: must wait until there are no more children */
11932 /* Note 2: must be interruptible */
11933 /* Examples:
11934 * $ sleep 3 & sleep 6 & wait
11935 * [1] 30934 sleep 3
11936 * [2] 30935 sleep 6
11937 * [1] Done sleep 3
11938 * [2] Done sleep 6
11939 * $ sleep 3 & sleep 6 & wait
11940 * [1] 30936 sleep 3
11941 * [2] 30937 sleep 6
11942 * [1] Done sleep 3
11943 * ^C <-- after ~4 sec from keyboard
11944 * $
11945 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011946 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011947 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011948
Denys Vlasenko7e675362016-10-28 21:57:31 +020011949 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011950 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011951 if (errno || pid <= 0) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010011952# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011953 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011954 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011955 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011956 wait_pipe = parse_jobspec(*argv);
11957 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011958 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011959 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011960 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011961 } else {
11962 /* waiting on "last dead job" removes it */
11963 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011964 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011965 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011966 /* else: parse_jobspec() already emitted error msg */
11967 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011968 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011969# endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011970 /* mimic bash message */
11971 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011972 ret = EXIT_FAILURE;
11973 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011974 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011975
Denys Vlasenko7e675362016-10-28 21:57:31 +020011976 /* Do we have such child? */
11977 ret = waitpid(pid, &status, WNOHANG);
11978 if (ret < 0) {
11979 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011980 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011981 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011982 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011983 /* "wait $!" but last bg task has already exited. Try:
11984 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11985 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011986 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011987 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011988 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011989 } else {
11990 /* Example: "wait 1". mimic bash message */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011991 bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011992 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011993 } else {
11994 /* ??? */
11995 bb_perror_msg("wait %s", *argv);
11996 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011997 continue; /* bash checks all argv[] */
11998 }
11999 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020012000 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010012001 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020012002 } else {
12003 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010012004 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020012005 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000012006 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +010012007 ret = 128 | WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000012008 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020012009 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000012010
12011 return ret;
12012}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010012013#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000012014
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012015#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
12016static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
12017{
12018 if (argv[1]) {
12019 def = bb_strtou(argv[1], NULL, 10);
12020 if (errno || def < def_min || argv[2]) {
12021 bb_error_msg("%s: bad arguments", argv[0]);
12022 def = UINT_MAX;
12023 }
12024 }
12025 return def;
12026}
12027#endif
12028
Denis Vlasenkodadfb492008-07-29 10:16:05 +000012029#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012030static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012031{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012032 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000012033 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000012034 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020012035 /* if we came from builtin_continue(), need to undo "= 1" */
12036 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000012037 return EXIT_SUCCESS; /* bash compat */
12038 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020012039 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012040
12041 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
12042 if (depth == UINT_MAX)
12043 G.flag_break_continue = BC_BREAK;
12044 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000012045 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012046
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012047 return EXIT_SUCCESS;
12048}
12049
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012050static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012051{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000012052 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
12053 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000012054}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000012055#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012056
12057#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012058static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012059{
12060 int rc;
12061
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020012062 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012063 bb_error_msg("%s: not in a function or sourced script", argv[0]);
12064 return EXIT_FAILURE; /* bash compat */
12065 }
12066
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020012067 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012068
12069 /* bash:
12070 * out of range: wraps around at 256, does not error out
12071 * non-numeric param:
12072 * f() { false; return qwe; }; f; echo $?
12073 * bash: return: qwe: numeric argument required <== we do this
12074 * 255 <== we also do this
12075 */
12076 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
Denys Vlasenkobb095f42020-02-20 16:37:59 +010012077# if ENABLE_HUSH_TRAP
12078 if (argv[1]) { /* "return ARG" inside a running trap sets $? */
12079 debug_printf_exec("G.return_exitcode=%d\n", rc);
12080 G.return_exitcode = rc;
12081 }
12082# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000012083 return rc;
12084}
12085#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010012086
Denys Vlasenko11f2e992017-08-10 16:34:03 +020012087#if ENABLE_HUSH_TIMES
12088static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
12089{
12090 static const uint8_t times_tbl[] ALIGN1 = {
12091 ' ', offsetof(struct tms, tms_utime),
12092 '\n', offsetof(struct tms, tms_stime),
12093 ' ', offsetof(struct tms, tms_cutime),
12094 '\n', offsetof(struct tms, tms_cstime),
12095 0
12096 };
12097 const uint8_t *p;
12098 unsigned clk_tck;
12099 struct tms buf;
12100
12101 clk_tck = bb_clk_tck();
12102
12103 times(&buf);
12104 p = times_tbl;
12105 do {
12106 unsigned sec, frac;
12107 unsigned long t;
12108 t = *(clock_t *)(((char *) &buf) + p[1]);
12109 sec = t / clk_tck;
12110 frac = t % clk_tck;
12111 printf("%um%u.%03us%c",
12112 sec / 60, sec % 60,
12113 (frac * 1000) / clk_tck,
12114 p[0]);
12115 p += 2;
12116 } while (*p);
12117
12118 return EXIT_SUCCESS;
12119}
12120#endif
12121
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010012122#if ENABLE_HUSH_MEMLEAK
12123static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
12124{
12125 void *p;
12126 unsigned long l;
12127
12128# ifdef M_TRIM_THRESHOLD
12129 /* Optional. Reduces probability of false positives */
12130 malloc_trim(0);
12131# endif
12132 /* Crude attempt to find where "free memory" starts,
12133 * sans fragmentation. */
12134 p = malloc(240);
12135 l = (unsigned long)p;
12136 free(p);
12137 p = malloc(3400);
12138 if (l < (unsigned long)p) l = (unsigned long)p;
12139 free(p);
12140
12141
12142# if 0 /* debug */
12143 {
12144 struct mallinfo mi = mallinfo();
12145 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
12146 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
12147 }
12148# endif
12149
12150 if (!G.memleak_value)
12151 G.memleak_value = l;
12152
12153 l -= G.memleak_value;
12154 if ((long)l < 0)
12155 l = 0;
12156 l /= 1024;
12157 if (l > 127)
12158 l = 127;
12159
12160 /* Exitcode is "how many kilobytes we leaked since 1st call" */
12161 return l;
12162}
12163#endif