blob: 77f90f82f806bc369e53eb36ca84ce8208273ebd [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020066 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020067 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
68 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
69 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020070 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020071 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
72 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020073 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020074 * indirect expansion: ${!VAR}
75 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020076 *
77 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020078 * Some builtins mandated by standards:
79 * newgrp [GRP]: not a builtin in bash but a suid binary
80 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020081 *
82 * Status of [[ support:
83 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
84 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020085 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenkod2241f52020-10-31 03:34:07 +010086 * = is glob match operator, not equality operator: STR = GLOB
Denys Vlasenkod2241f52020-10-31 03:34:07 +010087 * == same as =
88 * =~ is regex match operator: STR =~ REGEX
Denys Vlasenko3632cb12018-04-10 15:25:41 +020089 * TODO:
Denys Vlasenko3632cb12018-04-10 15:25:41 +020090 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
Denys Vlasenkoa7c06532020-10-31 04:32:34 +010091 * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
Eric Andersen25f27032001-04-26 23:22:31 +000092 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020093//config:config HUSH
Denys Vlasenkob097a842018-12-28 03:20:17 +010094//config: bool "hush (68 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +020096//config: select SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020098//config: hush is a small shell. It handles the normal flow control
99//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
100//config: case/esac. Redirections, here documents, $((arithmetic))
101//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200102//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200103//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200104//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200105//config: It does not handle select, aliases, tilde expansion,
106//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200107//config:
Denys Vlasenko67e15292020-06-24 13:39:13 +0200108// This option is visible (has a description) to make it possible to select
109// a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
110//config:config SHELL_HUSH
111//config: bool "Internal shell for embedded script support"
112//config: default n
113//config:
114//config:# hush options
115//config:# It's only needed to get "nice" menuconfig indenting.
116//config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
117//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200118//config:config HUSH_BASH_COMPAT
119//config: bool "bash-compatible extensions"
120//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200121//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200122//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200123//config:config HUSH_BRACE_EXPANSION
124//config: bool "Brace expansion"
125//config: default y
126//config: depends on HUSH_BASH_COMPAT
127//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200128//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200129//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100130//config:config HUSH_LINENO_VAR
131//config: bool "$LINENO variable"
132//config: default y
133//config: depends on HUSH_BASH_COMPAT
134//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100135//config:config HUSH_BASH_SOURCE_CURDIR
136//config: bool "'source' and '.' builtins search current directory after $PATH"
137//config: default n # do not encourage non-standard behavior
138//config: depends on HUSH_BASH_COMPAT
139//config: help
140//config: This is not compliant with standards. Avoid if possible.
141//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:config HUSH_INTERACTIVE
143//config: bool "Interactive mode"
144//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200145//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200146//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200147//config: Enable interactive mode (prompt and command editing).
148//config: Without this, hush simply reads and executes commands
149//config: from stdin just like a shell script from a file.
150//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200151//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200152//config:config HUSH_SAVEHISTORY
153//config: bool "Save command history to .hush_history"
154//config: default y
155//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200156//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200157//config:config HUSH_JOB
158//config: bool "Job control"
159//config: default y
160//config: depends on HUSH_INTERACTIVE
161//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200162//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
163//config: command (not entire shell), fg/bg builtins work. Without this option,
164//config: "cmd &" still works by simply spawning a process and immediately
165//config: prompting for next command (or executing next command in a script),
166//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200167//config:
168//config:config HUSH_TICK
Ron Yorston060f0a02018-11-09 12:00:39 +0000169//config: bool "Support command substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200171//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200172//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200173//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200174//config:
175//config:config HUSH_IF
176//config: bool "Support if/then/elif/else/fi"
177//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200178//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200179//config:
180//config:config HUSH_LOOPS
181//config: bool "Support for, while and until loops"
182//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200183//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200184//config:
185//config:config HUSH_CASE
186//config: bool "Support case ... esac statement"
187//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200188//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200190//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200191//config:
192//config:config HUSH_FUNCTIONS
193//config: bool "Support funcname() { commands; } syntax"
194//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200195//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200197//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200198//config:
199//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100200//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: default y
202//config: depends on HUSH_FUNCTIONS
203//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200204//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:
206//config:config HUSH_RANDOM_SUPPORT
207//config: bool "Pseudorandom generator and $RANDOM variable"
208//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200209//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200210//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200211//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
212//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200213//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200214//config:config HUSH_MODE_X
215//config: bool "Support 'hush -x' option and 'set -x' command"
216//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200217//config: depends on SHELL_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200218//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200219//config: This instructs hush to print commands before execution.
220//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200221//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100222//config:config HUSH_ECHO
223//config: bool "echo builtin"
224//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200225//config: depends on SHELL_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100226//config:
227//config:config HUSH_PRINTF
228//config: bool "printf builtin"
229//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200230//config: depends on SHELL_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100231//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100232//config:config HUSH_TEST
233//config: bool "test builtin"
234//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200235//config: depends on SHELL_HUSH
Denys Vlasenko265062d2017-01-10 15:13:30 +0100236//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100237//config:config HUSH_HELP
238//config: bool "help builtin"
239//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200240//config: depends on SHELL_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100241//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100242//config:config HUSH_EXPORT
243//config: bool "export builtin"
244//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200245//config: depends on SHELL_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100246//config:
247//config:config HUSH_EXPORT_N
248//config: bool "Support 'export -n' option"
249//config: default y
250//config: depends on HUSH_EXPORT
251//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200252//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100253//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200254//config:config HUSH_READONLY
255//config: bool "readonly builtin"
256//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200257//config: depends on SHELL_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200258//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200259//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200260//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100262//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100263//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200264//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100265//config:
266//config:config HUSH_WAIT
267//config: bool "wait builtin"
268//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200269//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100270//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100271//config:config HUSH_COMMAND
272//config: bool "command builtin"
273//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200274//config: depends on SHELL_HUSH
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100275//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:config HUSH_TRAP
277//config: bool "trap builtin"
278//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200279//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100280//config:
281//config:config HUSH_TYPE
282//config: bool "type builtin"
283//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200284//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100285//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200286//config:config HUSH_TIMES
287//config: bool "times builtin"
288//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200289//config: depends on SHELL_HUSH
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200290//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100291//config:config HUSH_READ
292//config: bool "read builtin"
293//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200294//config: depends on SHELL_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100295//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100296//config:config HUSH_SET
297//config: bool "set builtin"
298//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200299//config: depends on SHELL_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100300//config:
301//config:config HUSH_UNSET
302//config: bool "unset builtin"
303//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200304//config: depends on SHELL_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100305//config:
306//config:config HUSH_ULIMIT
307//config: bool "ulimit builtin"
308//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200309//config: depends on SHELL_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100310//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100311//config:config HUSH_UMASK
312//config: bool "umask builtin"
313//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200314//config: depends on SHELL_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100315//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200316//config:config HUSH_GETOPTS
317//config: bool "getopts builtin"
318//config: default y
Denys Vlasenko67e15292020-06-24 13:39:13 +0200319//config: depends on SHELL_HUSH
Denys Vlasenko74d40582017-08-11 01:32:46 +0200320//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100321//config:config HUSH_MEMLEAK
322//config: bool "memleak builtin (debugging)"
323//config: default n
Denys Vlasenko67e15292020-06-24 13:39:13 +0200324//config: depends on SHELL_HUSH
325//config:
326//config:endif # hush options
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200327
Denys Vlasenko20704f02011-03-23 17:59:27 +0100328//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100329// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100330//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100331//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100332
Denys Vlasenko67e15292020-06-24 13:39:13 +0200333//kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100334//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
335
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200336/* -i (interactive) is also accepted,
337 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100338 * NOMMU-specific options are not meant to be used by users,
339 * therefore we don't show them either.
340 */
341//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200342//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100343//usage:#define hush_full_usage "\n\n"
344//usage: "Unix shell interpreter"
345
Denys Vlasenko67047462016-12-22 15:21:58 +0100346#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
347 || defined(__APPLE__) \
348 )
349# include <malloc.h> /* for malloc_trim */
350#endif
351#include <glob.h>
352/* #include <dmalloc.h> */
353#if ENABLE_HUSH_CASE
354# include <fnmatch.h>
355#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200356#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100357#include <sys/utsname.h> /* for setting $HOSTNAME */
358
359#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
360#include "unicode.h"
361#include "shell_common.h"
362#include "math.h"
363#include "match.h"
364#if ENABLE_HUSH_RANDOM_SUPPORT
365# include "random.h"
366#else
367# define CLEAR_RANDOM_T(rnd) ((void)0)
368#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200369#ifndef O_CLOEXEC
370# define O_CLOEXEC 0
371#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100372#ifndef F_DUPFD_CLOEXEC
373# define F_DUPFD_CLOEXEC F_DUPFD
374#endif
Denys Vlasenko67047462016-12-22 15:21:58 +0100375
Ron Yorston71df2d32018-11-27 14:34:25 +0000376#if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
377# include "embedded_scripts.h"
378#else
379# define NUM_SCRIPTS 0
380#endif
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000381
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100382/* So far, all bash compat is controlled by one config option */
383/* Separate defines document which part of code implements what */
384#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
385#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100386#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
387#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Ron Yorstona81700b2019-04-15 10:48:29 +0100388#define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200389#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200390#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100391
392
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200393/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000394#define LEAK_HUNTING 0
395#define BUILD_AS_NOMMU 0
396/* Enable/disable sanity checks. Ok to enable in production,
397 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
398 * Keeping 1 for now even in released versions.
399 */
400#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200401/* Slightly bigger (+200 bytes), but faster hush.
402 * So far it only enables a trick with counting SIGCHLDs and forks,
403 * which allows us to do fewer waitpid's.
404 * (we can detect a case where neither forks were done nor SIGCHLDs happened
405 * and therefore waitpid will return the same result as last time)
406 */
407#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200408/* TODO: implement simplified code for users which do not need ${var%...} ops
409 * So far ${var%...} ops are always enabled:
410 */
411#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000412
413
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000414#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000415# undef BB_MMU
416# undef USE_FOR_NOMMU
417# undef USE_FOR_MMU
418# define BB_MMU 0
419# define USE_FOR_NOMMU(...) __VA_ARGS__
420# define USE_FOR_MMU(...)
421#endif
422
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200423#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100424#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000425/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000426# undef CONFIG_FEATURE_SH_STANDALONE
427# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000428# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100429# undef IF_NOT_FEATURE_SH_STANDALONE
430# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000431# define IF_FEATURE_SH_STANDALONE(...)
432# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000433#endif
434
Denis Vlasenko05743d72008-02-10 12:10:08 +0000435#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000436# undef ENABLE_FEATURE_EDITING
437# define ENABLE_FEATURE_EDITING 0
438# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
439# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200440# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
441# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000442#endif
443
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000444/* Do we support ANY keywords? */
445#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000446# define HAS_KEYWORDS 1
447# define IF_HAS_KEYWORDS(...) __VA_ARGS__
448# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000449#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000450# define HAS_KEYWORDS 0
451# define IF_HAS_KEYWORDS(...)
452# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000453#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000454
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000455/* If you comment out one of these below, it will be #defined later
456 * to perform debug printfs to stderr: */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200457#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000458/* Finer-grained debug switches */
Denys Vlasenko3675c372018-07-23 16:31:21 +0200459#define debug_printf_parse(...) do {} while (0)
460#define debug_printf_heredoc(...) do {} while (0)
461#define debug_print_tree(a, b) do {} while (0)
462#define debug_printf_exec(...) do {} while (0)
463#define debug_printf_env(...) do {} while (0)
464#define debug_printf_jobs(...) do {} while (0)
465#define debug_printf_expand(...) do {} while (0)
466#define debug_printf_varexp(...) do {} while (0)
467#define debug_printf_glob(...) do {} while (0)
468#define debug_printf_redir(...) do {} while (0)
469#define debug_printf_list(...) do {} while (0)
470#define debug_printf_subst(...) do {} while (0)
471#define debug_printf_prompt(...) do {} while (0)
472#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000473
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000474#define ERR_PTR ((void*)(long)1)
475
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100476#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000477
Denys Vlasenkoef8985c2019-05-19 16:29:09 +0200478#define _SPECIAL_VARS_STR "_*@$!?#-"
479#define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
480#define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100481#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200482/* Support / and // replace ops */
483/* Note that // is stored as \ in "encoded" string representation */
484# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
485# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
486# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
487#else
488# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
489# define VAR_SUBST_OPS "%#:-=+?"
490# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
491#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200492
Denys Vlasenko932b9972018-01-11 12:39:48 +0100493#define SPECIAL_VAR_SYMBOL_STR "\3"
494#define SPECIAL_VAR_SYMBOL 3
495/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
496#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000497
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200498struct variable;
499
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000500static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
501
502/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000503 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000504 */
505#if !BB_MMU
506typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200507 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000508 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000509 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000510} nommu_save_t;
511#endif
512
Denys Vlasenko9b782552010-09-08 13:33:26 +0200513enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000514 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000515#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000516 RES_IF ,
517 RES_THEN ,
518 RES_ELIF ,
519 RES_ELSE ,
520 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000521#endif
522#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000523 RES_FOR ,
524 RES_WHILE ,
525 RES_UNTIL ,
526 RES_DO ,
527 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000528#endif
529#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000530 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000531#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000532#if ENABLE_HUSH_CASE
533 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200534 /* three pseudo-keywords support contrived "case" syntax: */
535 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
536 RES_MATCH , /* "word)" */
537 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000538 RES_ESAC ,
539#endif
540 RES_XXXX ,
541 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200542};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000543
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000544typedef struct o_string {
545 char *data;
546 int length; /* position where data is appended */
547 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200548 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000549 /* At least some part of the string was inside '' or "",
550 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200551 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000552 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200553 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000554} o_string;
555enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200556 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
557 EXP_FLAG_GLOB = 0x2,
558 /* Protect newly added chars against globbing
559 * by prepending \ to *, ?, [, \ */
560 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
561};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000562/* Used for initialization: o_string foo = NULL_O_STRING; */
563#define NULL_O_STRING { NULL }
564
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200565#ifndef debug_printf_parse
566static const char *const assignment_flag[] = {
567 "MAYBE_ASSIGNMENT",
568 "DEFINITELY_ASSIGNMENT",
569 "NOT_ASSIGNMENT",
570 "WORD_IS_KEYWORD",
571};
572#endif
573
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200574/* We almost can use standard FILE api, but we need an ability to move
575 * its fd when redirects coincide with it. No api exists for that
576 * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
577 * HFILE is our internal alternative. Only supports reading.
578 * Since we now can, we incorporate linked list of all opened HFILEs
579 * into the struct (used to be a separate mini-list).
580 */
581typedef struct HFILE {
582 char *cur;
583 char *end;
584 struct HFILE *next_hfile;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200585 int fd;
586 char buf[1024];
587} HFILE;
588
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000589typedef struct in_str {
590 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200591 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200592 int last_char;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200593 HFILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000594} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000595
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200596/* The descrip member of this structure is only used to make
597 * debugging output pretty */
598static const struct {
Denys Vlasenko965b7952020-11-30 13:03:03 +0100599 int32_t mode;
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200600 signed char default_fd;
601 char descrip[3];
Denys Vlasenko965b7952020-11-30 13:03:03 +0100602} redir_table[] ALIGN4 = {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200603 { O_RDONLY, 0, "<" },
604 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
605 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
606 { O_CREAT|O_RDWR, 1, "<>" },
607 { O_RDONLY, 0, "<<" },
608/* Should not be needed. Bogus default_fd helps in debugging */
609/* { O_RDONLY, 77, "<<" }, */
610};
611
Eric Andersen25f27032001-04-26 23:22:31 +0000612struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000613 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000614 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000615 int rd_fd; /* fd to redirect */
616 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
617 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000618 smallint rd_type; /* (enum redir_type) */
619 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000620 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200621 * bit 0: do we need to trim leading tabs?
622 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000623 */
Eric Andersen25f27032001-04-26 23:22:31 +0000624};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000625typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200626 REDIRECT_INPUT = 0,
627 REDIRECT_OVERWRITE = 1,
628 REDIRECT_APPEND = 2,
629 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000630 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200631 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000632
633 REDIRFD_CLOSE = -3,
634 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000635 REDIRFD_TO_FILE = -1,
636 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000637
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000638 HEREDOC_SKIPTABS = 1,
639 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000640} redir_type;
641
Eric Andersen25f27032001-04-26 23:22:31 +0000642
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000643struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000644 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200645 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100646#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100647 unsigned lineno;
648#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200649 smallint cmd_type; /* CMD_xxx */
650#define CMD_NORMAL 0
651#define CMD_SUBSHELL 1
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100652#if BASH_TEST2
653/* used for "[[ EXPR ]]" */
654# define CMD_TEST2_SINGLEWORD_NOGLOB 2
655#endif
Denys Vlasenko77a51a22020-12-29 16:53:11 +0100656#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100657/* used to prevent word splitting and globbing in "export v=t*" */
658# define CMD_SINGLEWORD_NOGLOB 3
Denis Vlasenkoed055212009-04-11 10:37:10 +0000659#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200660#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod2241f52020-10-31 03:34:07 +0100661# define CMD_FUNCDEF 4
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200662#endif
663
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100664 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200665 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
666 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000667#if !BB_MMU
668 char *group_as_string;
669#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000670#if ENABLE_HUSH_FUNCTIONS
671 struct function *child_func;
672/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200673 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000674 * When we execute "f1() {a;}" cmd, we create new function and clear
675 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200676 * When we execute "f1() {b;}", we notice that f1 exists,
677 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000678 * we put those fields back into cmd->xxx
679 * (struct function has ->parent_cmd ptr to facilitate that).
680 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
681 * Without this trick, loop would execute a;b;b;b;...
682 * instead of correct sequence a;b;a;b;...
683 * When command is freed, it severs the link
684 * (sets ->child_func->parent_cmd to NULL).
685 */
686#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000687 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000688/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
689 * and on execution these are substituted with their values.
690 * Substitution can make _several_ words out of one argv[n]!
691 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000692 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000693 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000694 struct redir_struct *redirects; /* I/O redirections */
695};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000696/* Is there anything in this command at all? */
697#define IS_NULL_CMD(cmd) \
698 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
699
Eric Andersen25f27032001-04-26 23:22:31 +0000700struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000701 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000702 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000703 int alive_cmds; /* number of commands running (not exited) */
704 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000705#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100706 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000707 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000708 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000709#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000710 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000711 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000712 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
713 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000714};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000715typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100716 PIPE_SEQ = 0,
717 PIPE_AND = 1,
718 PIPE_OR = 2,
719 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000720} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000721/* Is there anything in this pipe at all? */
722#define IS_NULL_PIPE(pi) \
723 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000724
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000725/* This holds pointers to the various results of parsing */
726struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000727 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000728 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000729 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000730 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000731 /* last command in pipe (being constructed right now) */
732 struct command *command;
733 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000734 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200735 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000736#if !BB_MMU
737 o_string as_string;
738#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200739 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000740#if HAS_KEYWORDS
741 smallint ctx_res_w;
742 smallint ctx_inverted; /* "! cmd | cmd" */
743#if ENABLE_HUSH_CASE
744 smallint ctx_dsemicolon; /* ";;" seen */
745#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000746 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
747 int old_flag;
748 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000749 * example: "if pipe1; pipe2; then pipe3; fi"
750 * when we see "if" or "then", we malloc and copy current context,
751 * and make ->stack point to it. then we parse pipeN.
752 * when closing "then" / fi" / whatever is found,
753 * we move list_head into ->stack->command->group,
754 * copy ->stack into current context, and delete ->stack.
755 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000756 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000757 struct parse_context *stack;
758#endif
759};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200760enum {
761 MAYBE_ASSIGNMENT = 0,
762 DEFINITELY_ASSIGNMENT = 1,
763 NOT_ASSIGNMENT = 2,
764 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
765 WORD_IS_KEYWORD = 3,
766};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000767
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000768/* On program start, environ points to initial environment.
769 * putenv adds new pointers into it, unsetenv removes them.
770 * Neither of these (de)allocates the strings.
771 * setenv allocates new strings in malloc space and does putenv,
772 * and thus setenv is unusable (leaky) for shell's purposes */
773#define setenv(...) setenv_is_leaky_dont_use()
774struct variable {
775 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000776 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000777 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200778 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000779 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000780 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000781};
782
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000783enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000784 BC_BREAK = 1,
785 BC_CONTINUE = 2,
786};
787
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000788#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000789struct function {
790 struct function *next;
791 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000792 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000793 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200794# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000795 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200796# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000797};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000798#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000799
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000800
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100801/* set -/+o OPT support. (TODO: make it optional)
802 * bash supports the following opts:
803 * allexport off
804 * braceexpand on
805 * emacs on
806 * errexit off
807 * errtrace off
808 * functrace off
809 * hashall on
810 * histexpand off
811 * history on
812 * ignoreeof off
813 * interactive-comments on
814 * keyword off
815 * monitor on
816 * noclobber off
817 * noexec off
818 * noglob off
819 * nolog off
820 * notify off
821 * nounset off
822 * onecmd off
823 * physical off
824 * pipefail off
825 * posix off
826 * privileged off
827 * verbose off
828 * vi off
829 * xtrace off
830 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800831static const char o_opt_strings[] ALIGN1 =
832 "pipefail\0"
833 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200834 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800835#if ENABLE_HUSH_MODE_X
836 "xtrace\0"
837#endif
838 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100839enum {
840 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800841 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200842 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800843#if ENABLE_HUSH_MODE_X
844 OPT_O_XTRACE,
845#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100846 NUM_OPT_O
847};
848
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000849/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850/* Sorted roughly by size (smaller offsets == smaller code) */
851struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000852 /* interactive_fd != 0 means we are an interactive shell.
853 * If we are, then saved_tty_pgrp can also be != 0, meaning
854 * that controlling tty is available. With saved_tty_pgrp == 0,
855 * job control still works, but terminal signals
856 * (^C, ^Z, ^Y, ^\) won't work at all, and background
857 * process groups can only be created with "cmd &".
858 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
859 * to give tty to the foreground process group,
860 * and will take it back when the group is stopped (^Z)
861 * or killed (^C).
862 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000863#if ENABLE_HUSH_INTERACTIVE
864 /* 'interactive_fd' is a fd# open to ctty, if we have one
865 * _AND_ if we decided to act interactively */
866 int interactive_fd;
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +0200867 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000868# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000869#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000870# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000871#endif
872#if ENABLE_FEATURE_EDITING
873 line_input_t *line_input_state;
874#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000875 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200876 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000877 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200878#if ENABLE_HUSH_RANDOM_SUPPORT
879 random_t random_gen;
880#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000881#if ENABLE_HUSH_JOB
882 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100883 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000884 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000885 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400886# define G_saved_tty_pgrp (G.saved_tty_pgrp)
887#else
888# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000889#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200890 /* How deeply are we in context where "set -e" is ignored */
891 int errexit_depth;
892 /* "set -e" rules (do we follow them correctly?):
893 * Exit if pipe, list, or compound command exits with a non-zero status.
894 * Shell does not exit if failed command is part of condition in
895 * if/while, part of && or || list except the last command, any command
896 * in a pipe but the last, or if the command's return value is being
897 * inverted with !. If a compound command other than a subshell returns a
898 * non-zero status because a command failed while -e was being ignored, the
899 * shell does not exit. A trap on ERR, if set, is executed before the shell
900 * exits [ERR is a bashism].
901 *
902 * If a compound command or function executes in a context where -e is
903 * ignored, none of the commands executed within are affected by the -e
904 * setting. If a compound command or function sets -e while executing in a
905 * context where -e is ignored, that setting does not have any effect until
906 * the compound command or the command containing the function call completes.
907 */
908
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100909 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100910#if ENABLE_HUSH_MODE_X
911# define G_x_mode (G.o_opt[OPT_O_XTRACE])
912#else
913# define G_x_mode 0
914#endif
Denys Vlasenkod8740b22019-05-19 19:11:21 +0200915 char opt_s;
Denys Vlasenkof3634582019-06-03 12:21:04 +0200916 char opt_c;
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200917#if ENABLE_HUSH_INTERACTIVE
918 smallint promptmode; /* 0: PS1, 1: PS2 */
919#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000920 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000921#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000922 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000923#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000924#if ENABLE_HUSH_FUNCTIONS
925 /* 0: outside of a function (or sourced file)
926 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000927 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000928 */
929 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200930# define G_flag_return_in_progress (G.flag_return_in_progress)
931#else
932# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000933#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000934 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100935 /* These support $? */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000936 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200937 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200938 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100939#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000940 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000941 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100942# define G_global_args_malloced (G.global_args_malloced)
943#else
944# define G_global_args_malloced 0
945#endif
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +0100946#if ENABLE_HUSH_BASH_COMPAT
947 int dead_job_exitcode; /* for "wait -n" */
948#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000949 /* how many non-NULL argv's we have. NB: $# + 1 */
950 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000951 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000952#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000953 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000954#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000955#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000956 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000957 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000958#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200959#if ENABLE_HUSH_GETOPTS
960 unsigned getopt_count;
961#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000962 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200963 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000964 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200965 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200966 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200967 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200968 unsigned var_nest_level;
969#if ENABLE_HUSH_FUNCTIONS
970# if ENABLE_HUSH_LOCAL
971 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200972# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200973 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000974#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000975 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200976#if ENABLE_HUSH_FAST
977 unsigned count_SIGCHLD;
978 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200979 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200980#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100981#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +0200982 unsigned parse_lineno;
983 unsigned execute_lineno;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100984#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +0200985 HFILE *HFILE_list;
Denys Vlasenko21806562019-11-01 14:16:07 +0100986 HFILE *HFILE_stdin;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200987 /* Which signals have non-DFL handler (even with no traps set)?
988 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200989 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200990 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200991 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200992 * Other than these two times, never modified.
993 */
994 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200995#if ENABLE_HUSH_JOB
996 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100997# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200998#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200999# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001000#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001001#if ENABLE_HUSH_TRAP
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01001002 int pre_trap_exitcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01001003# if ENABLE_HUSH_FUNCTIONS
1004 int return_exitcode;
1005# endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001006 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001007# define G_traps G.traps
1008#else
1009# define G_traps ((char**)NULL)
1010#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001011 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +01001012#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001013 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +01001014#endif
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001015#if ENABLE_HUSH_MODE_X
1016 unsigned x_mode_depth;
1017 /* "set -x" output should not be redirectable with subsequent 2>FILE.
1018 * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
1019 * for all subsequent output.
1020 */
1021 int x_mode_fd;
1022 o_string x_mode_buf;
1023#endif
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001024#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001025 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001026#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +02001027 struct sigaction sa;
Denys Vlasenkof3634582019-06-03 12:21:04 +02001028 char optstring_buf[sizeof("eixcs")];
Ron Yorstona81700b2019-04-15 10:48:29 +01001029#if BASH_EPOCH_VARS
Denys Vlasenko3c13da32020-12-30 23:48:01 +01001030 char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
Ron Yorstona81700b2019-04-15 10:48:29 +01001031#endif
Denys Vlasenko0448c552016-09-29 20:25:44 +02001032#if ENABLE_FEATURE_EDITING
1033 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
1034#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001035};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001036#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +00001037/* Not #defining name to G.name - this quickly gets unwieldy
1038 * (too many defines). Also, I actually prefer to see when a variable
1039 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001040#define INIT_G() do { \
1041 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +02001042 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
1043 sigfillset(&G.sa.sa_mask); \
1044 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001045} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001046
1047
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001048/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001049static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001050#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001051static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001052#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001053static int builtin_eval(char **argv) FAST_FUNC;
1054static int builtin_exec(char **argv) FAST_FUNC;
1055static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001056#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001057static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001058#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001059#if ENABLE_HUSH_READONLY
1060static int builtin_readonly(char **argv) FAST_FUNC;
1061#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001062#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001063static int builtin_fg_bg(char **argv) FAST_FUNC;
1064static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001065#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001066#if ENABLE_HUSH_GETOPTS
1067static int builtin_getopts(char **argv) FAST_FUNC;
1068#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001069#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001070static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001071#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001072#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001073static int builtin_history(char **argv) FAST_FUNC;
1074#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001075#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001076static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001077#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001078#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001079static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001080#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001081#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001082static int builtin_printf(char **argv) FAST_FUNC;
1083#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001084static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001085#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001086static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001087#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001088#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001089static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001090#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001091static int builtin_shift(char **argv) FAST_FUNC;
1092static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001093#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001094static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001095#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001096#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001097static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001098#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001099#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001100static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001101#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001102#if ENABLE_HUSH_TIMES
1103static int builtin_times(char **argv) FAST_FUNC;
1104#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001105static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001106#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001107static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001108#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001109#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001110static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001111#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001112#if ENABLE_HUSH_KILL
1113static int builtin_kill(char **argv) FAST_FUNC;
1114#endif
1115#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001116static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001117#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001118#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001119static int builtin_break(char **argv) FAST_FUNC;
1120static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001122#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001123static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001124#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001125
1126/* Table of built-in functions. They can be forked or not, depending on
1127 * context: within pipes, they fork. As simple commands, they do not.
1128 * When used in non-forking context, they can change global variables
1129 * in the parent shell process. If forked, of course they cannot.
1130 * For example, 'unset foo | whatever' will parse and run, but foo will
1131 * still be set at the end. */
1132struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001133 const char *b_cmd;
1134 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001135#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001136 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001137# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001138#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001139# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001140#endif
1141};
1142
Denys Vlasenko965b7952020-11-30 13:03:03 +01001143static const struct built_in_command bltins1[] ALIGN_PTR = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001144 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001145 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001146#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001147 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001148#endif
1149#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001150 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001151#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001152 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001153#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001154 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001155#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001156 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1157 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001158 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001159#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001160 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001161#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001162#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001163 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001164#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001165#if ENABLE_HUSH_GETOPTS
1166 BLTIN("getopts" , builtin_getopts , NULL),
1167#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001168#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001169 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001170#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001171#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001172 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001173#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001174#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001175 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001176#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001177#if ENABLE_HUSH_KILL
1178 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1179#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001180#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001181 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001182#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001183#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001184 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001185#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001186#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001187 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001188#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001189#if ENABLE_HUSH_READONLY
1190 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1191#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001192#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001193 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001194#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001195#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001196 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001197#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001198 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001199#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001200 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001201#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001202#if ENABLE_HUSH_TIMES
1203 BLTIN("times" , builtin_times , NULL),
1204#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001205#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001206 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001207#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001208 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001209#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001210 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001211#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001212#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001213 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001214#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001215#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001216 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001217#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001218#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001219 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001220#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001221#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001222 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001223#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001224};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001225/* These builtins won't be used if we are on NOMMU and need to re-exec
1226 * (it's cheaper to run an external program in this case):
1227 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01001228static const struct built_in_command bltins2[] ALIGN_PTR = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001229#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001230 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001231#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001232#if BASH_TEST2
1233 BLTIN("[[" , builtin_test , NULL),
1234#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001235#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001236 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001237#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001238#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001239 BLTIN("printf" , builtin_printf , NULL),
1240#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001241 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001242#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001243 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001244#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001245};
1246
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001247
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001248/* Debug printouts.
1249 */
Denys Vlasenkoa8e74412018-07-28 12:16:30 +02001250#if HUSH_DEBUG >= 2
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001251/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001252# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001253# define debug_enter() (G.debug_indent++)
1254# define debug_leave() (G.debug_indent--)
1255#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001256# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001257# define debug_enter() ((void)0)
1258# define debug_leave() ((void)0)
1259#endif
1260
1261#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001262# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001263#endif
1264
1265#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001266# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001267#endif
1268
Denys Vlasenko3675c372018-07-23 16:31:21 +02001269#ifndef debug_printf_heredoc
1270# define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
1271#endif
1272
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001273#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001274#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001275#endif
1276
1277#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001278# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001279#endif
1280
1281#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001282# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001283# define DEBUG_JOBS 1
1284#else
1285# define DEBUG_JOBS 0
1286#endif
1287
1288#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001289# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001290# define DEBUG_EXPAND 1
1291#else
1292# define DEBUG_EXPAND 0
1293#endif
1294
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001295#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001296# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001297#endif
1298
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001299#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001300# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001301# define DEBUG_GLOB 1
1302#else
1303# define DEBUG_GLOB 0
1304#endif
1305
Denys Vlasenko2db74612017-07-07 22:07:28 +02001306#ifndef debug_printf_redir
1307# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1308#endif
1309
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001310#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001311# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001312#endif
1313
1314#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001315# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001316#endif
1317
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001318#ifndef debug_printf_prompt
1319# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1320#endif
1321
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001322#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001323# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001324# define DEBUG_CLEAN 1
1325#else
1326# define DEBUG_CLEAN 0
1327#endif
1328
1329#if DEBUG_EXPAND
1330static void debug_print_strings(const char *prefix, char **vv)
1331{
1332 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001333 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001334 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001335 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001336}
1337#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001338# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001339#endif
1340
1341
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001342/* Leak hunting. Use hush_leaktool.sh for post-processing.
1343 */
1344#if LEAK_HUNTING
1345static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001346{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001347 void *ptr = xmalloc((size + 0xff) & ~0xff);
1348 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1349 return ptr;
1350}
1351static void *xxrealloc(int lineno, void *ptr, size_t size)
1352{
1353 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1354 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1355 return ptr;
1356}
1357static char *xxstrdup(int lineno, const char *str)
1358{
1359 char *ptr = xstrdup(str);
1360 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1361 return ptr;
1362}
1363static void xxfree(void *ptr)
1364{
1365 fdprintf(2, "free %p\n", ptr);
1366 free(ptr);
1367}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001368# define xmalloc(s) xxmalloc(__LINE__, s)
1369# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1370# define xstrdup(s) xxstrdup(__LINE__, s)
1371# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001372#endif
1373
1374
1375/* Syntax and runtime errors. They always abort scripts.
1376 * In interactive use they usually discard unparsed and/or unexecuted commands
1377 * and return to the prompt.
1378 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1379 */
1380#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001381# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001382# define syntax_error(lineno, msg) syntax_error(msg)
1383# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1384# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1385# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1386# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001387#endif
1388
Denys Vlasenko39701202017-08-02 19:44:05 +02001389static void die_if_script(void)
1390{
1391 if (!G_interactive_fd) {
1392 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1393 xfunc_error_retval = G.last_exitcode;
1394 xfunc_die();
1395 }
1396}
1397
1398static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001399{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001400 va_list p;
1401
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001402#if HUSH_DEBUG >= 2
1403 bb_error_msg("hush.c:%u", lineno);
1404#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001405 va_start(p, fmt);
1406 bb_verror_msg(fmt, p, NULL);
1407 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001408 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001409}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001410
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001411static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001412{
1413 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001414 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001415 else
James Byrne69374872019-07-02 11:35:03 +02001416 bb_simple_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001417 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001418}
1419
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001420static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001421{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001422 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001423 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001424}
1425
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001426static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001427{
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01001428 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001429//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1430// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001431}
1432
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001433static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001434{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001435 char msg[2] = { ch, '\0' };
1436 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001437}
1438
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001439static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001440{
1441 char msg[2];
1442 msg[0] = ch;
1443 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001444#if HUSH_DEBUG >= 2
1445 bb_error_msg("hush.c:%u", lineno);
1446#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001447 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001448 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001449}
1450
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001451#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001452# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001453# undef syntax_error
1454# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001455# undef syntax_error_unterm_ch
1456# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001457# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001458#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001459# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001460# define syntax_error(msg) syntax_error(__LINE__, msg)
1461# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1462# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1463# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1464# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001465#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001466
Denis Vlasenko552433b2009-04-04 19:29:21 +00001467
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001468/* Utility functions
1469 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001470/* Replace each \x with x in place, return ptr past NUL. */
1471static char *unbackslash(char *src)
1472{
Denys Vlasenko71885402009-09-24 01:44:13 +02001473 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001474 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001475 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001476 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001477 if (*src != '\0') {
1478 /* \x -> x */
1479 *dst++ = *src++;
1480 continue;
1481 }
1482 /* else: "\<nul>". Do not delete this backslash.
1483 * Testcase: eval 'echo ok\'
1484 */
1485 *dst++ = '\\';
1486 /* fallthrough */
1487 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001488 if ((*dst++ = *src++) == '\0')
1489 break;
1490 }
1491 return dst;
1492}
1493
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001494static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001495{
1496 int i;
1497 unsigned count1;
1498 unsigned count2;
1499 char **v;
1500
1501 v = strings;
1502 count1 = 0;
1503 if (v) {
1504 while (*v) {
1505 count1++;
1506 v++;
1507 }
1508 }
1509 count2 = 0;
1510 v = add;
1511 while (*v) {
1512 count2++;
1513 v++;
1514 }
1515 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1516 v[count1 + count2] = NULL;
1517 i = count2;
1518 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001519 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001520 return v;
1521}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001522#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001523static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1524{
1525 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1526 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1527 return ptr;
1528}
1529#define add_strings_to_strings(strings, add, need_to_dup) \
1530 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1531#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001532
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001533/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001534static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001535{
1536 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001537 v[0] = add;
1538 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001539 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001540}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001541#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001542static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1543{
1544 char **ptr = add_string_to_strings(strings, add);
1545 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1546 return ptr;
1547}
1548#define add_string_to_strings(strings, add) \
1549 xx_add_string_to_strings(__LINE__, strings, add)
1550#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001551
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001552static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001553{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001554 char **v;
1555
1556 if (!strings)
1557 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001558 v = strings;
1559 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001560 free(*v);
1561 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001562 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001563 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001564}
1565
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001566static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001567{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001568 int newfd;
1569 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001570 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1571 if (newfd >= 0) {
1572 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1573 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1574 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001575 if (errno == EBUSY)
1576 goto repeat;
1577 if (errno == EINTR)
1578 goto repeat;
1579 }
1580 return newfd;
1581}
1582
Denys Vlasenko657e9002017-07-30 23:34:04 +02001583static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001584{
1585 int newfd;
1586 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001587 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001588 if (newfd < 0) {
1589 if (errno == EBUSY)
1590 goto repeat;
1591 if (errno == EINTR)
1592 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001593 /* fd was not open? */
1594 if (errno == EBADF)
1595 return fd;
1596 xfunc_die();
1597 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001598 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1599 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001600 close(fd);
1601 return newfd;
1602}
1603
1604
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001605/* Manipulating HFILEs */
1606static HFILE *hfopen(const char *name)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001607{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001608 HFILE *fp;
1609 int fd;
1610
1611 fd = STDIN_FILENO;
1612 if (name) {
1613 fd = open(name, O_RDONLY | O_CLOEXEC);
1614 if (fd < 0)
1615 return NULL;
1616 if (O_CLOEXEC == 0) /* ancient libc */
1617 close_on_exec_on(fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001618 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001619
1620 fp = xmalloc(sizeof(*fp));
Denys Vlasenko21806562019-11-01 14:16:07 +01001621 if (name == NULL)
1622 G.HFILE_stdin = fp;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001623 fp->fd = fd;
1624 fp->cur = fp->end = fp->buf;
1625 fp->next_hfile = G.HFILE_list;
1626 G.HFILE_list = fp;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001627 return fp;
1628}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001629static void hfclose(HFILE *fp)
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001630{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001631 HFILE **pp = &G.HFILE_list;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001632 while (*pp) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001633 HFILE *cur = *pp;
1634 if (cur == fp) {
1635 *pp = cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001636 break;
1637 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001638 pp = &cur->next_hfile;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001639 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001640 if (fp->fd >= 0)
1641 close(fp->fd);
1642 free(fp);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001643}
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001644static int refill_HFILE_and_getc(HFILE *fp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001645{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001646 int n;
1647
1648 if (fp->fd < 0) {
1649 /* Already saw EOF */
1650 return EOF;
1651 }
Denys Vlasenko521220e2020-12-23 23:44:55 +01001652#if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
1653 /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
1654 * IOW: ^C will not immediately stop line input.
1655 * But poll() is different: it does NOT restart after signals.
1656 */
1657 if (fp == G.HFILE_stdin) {
1658 struct pollfd pfd[1];
1659 pfd[0].fd = fp->fd;
1660 pfd[0].events = POLLIN;
1661 n = poll(pfd, 1, -1);
1662 if (n < 0
1663 /*&& errno == EINTR - assumed true */
1664 && sigismember(&G.pending_set, SIGINT)
1665 ) {
1666 return '\0';
1667 }
1668 }
1669#else
1670/* if FEATURE_EDITING=y, we do not use this routine for interactive input */
1671#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001672 /* Try to buffer more input */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001673 n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
1674 if (n < 0) {
James Byrne69374872019-07-02 11:35:03 +02001675 bb_simple_perror_msg("read error");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001676 n = 0;
1677 }
Denys Vlasenko93e2a222020-12-23 12:23:21 +01001678 fp->cur = fp->buf;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001679 fp->end = fp->buf + n;
1680 if (n == 0) {
1681 /* EOF/error */
1682 close(fp->fd);
1683 fp->fd = -1;
1684 return EOF;
1685 }
1686 return (unsigned char)(*fp->cur++);
1687}
1688/* Inlined for common case of non-empty buffer.
1689 */
1690static ALWAYS_INLINE int hfgetc(HFILE *fp)
1691{
1692 if (fp->cur < fp->end)
1693 return (unsigned char)(*fp->cur++);
1694 /* Buffer empty */
1695 return refill_HFILE_and_getc(fp);
1696}
1697static int move_HFILEs_on_redirect(int fd, int avoid_fd)
1698{
1699 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001700 while (fl) {
1701 if (fd == fl->fd) {
1702 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001703 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001704 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 +02001705 return 1; /* "found and moved" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001706 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001707 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001708 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02001709#if ENABLE_HUSH_MODE_X
1710 if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
1711 G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1712 return 1; /* "found and moved" */
1713 }
1714#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001715 return 0; /* "not in the list" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001716}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001717#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001718static void close_all_HFILE_list(void)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001719{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001720 HFILE *fl = G.HFILE_list;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001721 while (fl) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001722 /* hfclose would also free HFILE object.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001723 * It is disastrous if we share memory with a vforked parent.
1724 * I'm not sure we never come here after vfork.
1725 * Therefore just close fd, nothing more.
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001726 *
1727 * ">" instead of ">=": we don't close fd#0,
1728 * interactive shell uses hfopen(NULL) as stdin input
1729 * which has fl->fd == 0, but fd#0 gets redirected in pipes.
1730 * If we'd close it here, then e.g. interactive "set | sort"
1731 * with NOFORKed sort, would have sort's input fd closed.
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001732 */
Denys Vlasenkoe9dccab2018-08-05 14:55:01 +02001733 if (fl->fd > 0)
1734 /*hfclose(fl); - unsafe */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001735 close(fl->fd);
1736 fl = fl->next_hfile;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001737 }
1738}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001739#endif
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001740static int fd_in_HFILEs(int fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001741{
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001742 HFILE *fl = G.HFILE_list;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001743 while (fl) {
1744 if (fl->fd == fd)
1745 return 1;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02001746 fl = fl->next_hfile;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001747 }
1748 return 0;
1749}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001750
1751
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001752/* Helpers for setting new $n and restoring them back
1753 */
1754typedef struct save_arg_t {
1755 char *sv_argv0;
1756 char **sv_g_argv;
1757 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001758 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001759} save_arg_t;
1760
1761static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1762{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001763 sv->sv_argv0 = argv[0];
1764 sv->sv_g_argv = G.global_argv;
1765 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001766 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001767
1768 argv[0] = G.global_argv[0]; /* retain $0 */
1769 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001770 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001771
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001772 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001773}
1774
1775static void restore_G_args(save_arg_t *sv, char **argv)
1776{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001777#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001778 if (G.global_args_malloced) {
1779 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001780 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001781 while (*++pp) /* note: does not free $0 */
1782 free(*pp);
1783 free(G.global_argv);
1784 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001785#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001786 argv[0] = sv->sv_argv0;
1787 G.global_argv = sv->sv_g_argv;
1788 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001789 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001790}
1791
1792
Denis Vlasenkod5762932009-03-31 11:22:57 +00001793/* Basic theory of signal handling in shell
1794 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001795 * This does not describe what hush does, rather, it is current understanding
1796 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001797 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1798 *
1799 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1800 * is finished or backgrounded. It is the same in interactive and
1801 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001802 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001803 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001804 * backgrounds (i.e. stops) or kills all members of currently running
1805 * pipe.
1806 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001807 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001808 * or by SIGINT in interactive shell.
1809 *
1810 * Trap handlers will execute even within trap handlers. (right?)
1811 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001812 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1813 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001814 *
1815 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001816 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001817 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001818 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001819 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001820 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001821 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001822 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001823 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001824 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001825 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001826 *
1827 * SIGQUIT: ignore
1828 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001829 * SIGHUP (interactive):
1830 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001831 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001832 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1833 * that all pipe members are stopped. Try this in bash:
1834 * while :; do :; done - ^Z does not background it
1835 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001836 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001837 * of the command line, show prompt. NB: ^C does not send SIGINT
1838 * to interactive shell while shell is waiting for a pipe,
1839 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001840 * Example 1: this waits 5 sec, but does not execute ls:
1841 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1842 * Example 2: this does not wait and does not execute ls:
1843 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1844 * Example 3: this does not wait 5 sec, but executes ls:
1845 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001846 * Example 4: this does not wait and does not execute ls:
1847 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001848 *
1849 * (What happens to signals which are IGN on shell start?)
1850 * (What happens with signal mask on shell start?)
1851 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001852 * Old implementation
1853 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001854 * We use in-kernel pending signal mask to determine which signals were sent.
1855 * We block all signals which we don't want to take action immediately,
1856 * i.e. we block all signals which need to have special handling as described
1857 * above, and all signals which have traps set.
1858 * After each pipe execution, we extract any pending signals via sigtimedwait()
1859 * and act on them.
1860 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001861 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001862 * sigset_t blocked_set: current blocked signal set
1863 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001864 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001865 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001866 * "trap 'cmd' SIGxxx":
1867 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001868 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001869 * unblock signals with special interactive handling
1870 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001871 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001872 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001873 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001874 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001875 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001876 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001877 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001878 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001879 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001880 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001881 * Standard says "When a subshell is entered, traps that are not being ignored
1882 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001883 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001884 *
1885 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001886 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001887 * masked signals are not visible!
1888 *
1889 * New implementation
1890 * ==================
1891 * We record each signal we are interested in by installing signal handler
1892 * for them - a bit like emulating kernel pending signal mask in userspace.
1893 * We are interested in: signals which need to have special handling
1894 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001895 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001896 * After each pipe execution, we extract any pending signals
1897 * and act on them.
1898 *
1899 * unsigned special_sig_mask: a mask of shell-special signals.
1900 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1901 * char *traps[sig] if trap for sig is set (even if it's '').
1902 * sigset_t pending_set: set of sigs we received.
1903 *
1904 * "trap - SIGxxx":
1905 * if sig is in special_sig_mask, set handler back to:
1906 * record_pending_signo, or to IGN if it's a tty stop signal
1907 * if sig is in fatal_sig_mask, set handler back to sigexit.
1908 * else: set handler back to SIG_DFL
1909 * "trap 'cmd' SIGxxx":
1910 * set handler to record_pending_signo.
1911 * "trap '' SIGxxx":
1912 * set handler to SIG_IGN.
1913 * after [v]fork, if we plan to be a shell:
1914 * set signals with special interactive handling to SIG_DFL
1915 * (because child shell is not interactive),
1916 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1917 * after [v]fork, if we plan to exec:
1918 * POSIX says fork clears pending signal mask in child - no need to clear it.
1919 *
1920 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1921 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1922 *
1923 * Note (compat):
1924 * Standard says "When a subshell is entered, traps that are not being ignored
1925 * are set to the default actions". bash interprets it so that traps which
1926 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001927 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001928enum {
1929 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001930 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001931 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001932 | (1 << SIGHUP)
1933 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001934 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001935#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001936 | (1 << SIGTTIN)
1937 | (1 << SIGTTOU)
1938 | (1 << SIGTSTP)
1939#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001940 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001941};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001942
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001943static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001944{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001945 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001946#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001947 if (sig == SIGCHLD) {
1948 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001949//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 +02001950 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001951#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001952}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001953
Denys Vlasenko0806e402011-05-12 23:06:20 +02001954static sighandler_t install_sighandler(int sig, sighandler_t handler)
1955{
1956 struct sigaction old_sa;
1957
1958 /* We could use signal() to install handlers... almost:
1959 * except that we need to mask ALL signals while handlers run.
1960 * I saw signal nesting in strace, race window isn't small.
1961 * SA_RESTART is also needed, but in Linux, signal()
1962 * sets SA_RESTART too.
1963 */
1964 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1965 /* sigfillset(&G.sa.sa_mask); - already done */
1966 /* G.sa.sa_flags = SA_RESTART; - already done */
1967 G.sa.sa_handler = handler;
1968 sigaction(sig, &G.sa, &old_sa);
1969 return old_sa.sa_handler;
1970}
1971
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001972static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001973
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001974static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001975static void restore_ttypgrp_and__exit(void)
1976{
1977 /* xfunc has failed! die die die */
1978 /* no EXIT traps, this is an escape hatch! */
1979 G.exiting = 1;
1980 hush_exit(xfunc_error_retval);
1981}
1982
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001983#if ENABLE_HUSH_JOB
1984
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001985/* Needed only on some libc:
1986 * It was observed that on exit(), fgetc'ed buffered data
1987 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1988 * With the net effect that even after fork(), not vfork(),
1989 * exit() in NOEXECed applet in "sh SCRIPT":
1990 * noexec_applet_here
1991 * echo END_OF_SCRIPT
1992 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1993 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001994 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001995 * and in `cmd` handling.
1996 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1997 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001998static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001999static void fflush_and__exit(void)
2000{
2001 fflush_all();
2002 _exit(xfunc_error_retval);
2003}
2004
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002005/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002006# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00002007/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002008# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002009
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002010/* Restores tty foreground process group, and exits.
2011 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002012 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002013 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02002014 * We also call it if xfunc is exiting.
2015 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002016static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002017static void sigexit(int sig)
2018{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002019 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00002020 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002021 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
2022 /* Disable all signals: job control, SIGPIPE, etc.
2023 * Mostly paranoid measure, to prevent infinite SIGTTOU.
2024 */
2025 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04002026 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02002027 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002028
2029 /* Not a signal, just exit */
2030 if (sig <= 0)
2031 _exit(- sig);
2032
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00002033 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002034}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002035#else
2036
Denys Vlasenko8391c482010-05-22 17:50:43 +02002037# define disable_restore_tty_pgrp_on_exit() ((void)0)
2038# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002039
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00002040#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002041
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002042static sighandler_t pick_sighandler(unsigned sig)
2043{
2044 sighandler_t handler = SIG_DFL;
2045 if (sig < sizeof(unsigned)*8) {
2046 unsigned sigmask = (1 << sig);
2047
2048#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002049 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002050 if (G_fatal_sig_mask & sigmask)
2051 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002052 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002053#endif
2054 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02002055 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002056 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002057 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002058 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02002059 * in an endless loop when we try to do some
2060 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002061 */
2062 if (SPECIAL_JOBSTOP_SIGS & sigmask)
2063 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02002064 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002065 }
2066 return handler;
2067}
2068
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002069/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002070static void hush_exit(int exitcode)
2071{
Denys Vlasenkobede2152011-09-04 16:12:33 +02002072#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
Denys Vlasenko00eb23b2020-12-21 21:36:58 +01002073 save_history(G.line_input_state); /* may be NULL */
Denys Vlasenkobede2152011-09-04 16:12:33 +02002074#endif
2075
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01002076 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002077 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002078 char *argv[3];
2079 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01002080 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002081 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02002082 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002083 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02002084 * "trap" will still show it, if executed
2085 * in the handler */
2086 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00002087 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002088
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002089#if ENABLE_FEATURE_CLEAN_UP
2090 {
2091 struct variable *cur_var;
2092 if (G.cwd != bb_msg_unknown)
2093 free((char*)G.cwd);
2094 cur_var = G.top_var;
2095 while (cur_var) {
2096 struct variable *tmp = cur_var;
2097 if (!cur_var->max_len)
2098 free(cur_var->varstr);
2099 cur_var = cur_var->next;
2100 free(tmp);
2101 }
2102 }
2103#endif
2104
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002105 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002106#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002107 sigexit(- (exitcode & 0xff));
2108#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002109 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002110#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002111}
2112
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002113//TODO: return a mask of ALL handled sigs?
2114static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002115{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002116 int last_sig = 0;
2117
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002118 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002119 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002120
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002121 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002122 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002123 sig = 0;
2124 do {
2125 sig++;
2126 if (sigismember(&G.pending_set, sig)) {
2127 sigdelset(&G.pending_set, sig);
2128 goto got_sig;
2129 }
2130 } while (sig < NSIG);
2131 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002132 got_sig:
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002133#if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002134 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002135 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002136 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002137 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002138 smalluint save_rcode;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002139 int save_pre;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002140 char *argv[3];
2141 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002142 argv[1] = xstrdup(G_traps[sig]);
2143 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002144 argv[2] = NULL;
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002145 save_pre = G.pre_trap_exitcode;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +01002146 G.pre_trap_exitcode = save_rcode = G.last_exitcode;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002147 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002148 free(argv[1]);
Denys Vlasenko3ced8042020-02-21 02:55:53 +01002149 G.pre_trap_exitcode = save_pre;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002150 G.last_exitcode = save_rcode;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002151# if ENABLE_HUSH_FUNCTIONS
2152 if (G.return_exitcode >= 0) {
2153 debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
2154 G.last_exitcode = G.return_exitcode;
2155 }
2156# endif
Denys Vlasenkob8709032011-05-08 21:20:01 +02002157 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002158 } /* else: "" trap, ignoring signal */
2159 continue;
2160 }
Denys Vlasenkobb095f42020-02-20 16:37:59 +01002161#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002162 /* not a trap: special action */
2163 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002164 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002165 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002166 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002167 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002168 break;
2169#if ENABLE_HUSH_JOB
2170 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002171//TODO: why are we doing this? ash and dash don't do this,
2172//they have no handler for SIGHUP at all,
2173//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002174 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002175 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002176 /* bash is observed to signal whole process groups,
2177 * not individual processes */
2178 for (job = G.job_list; job; job = job->next) {
2179 if (job->pgrp <= 0)
2180 continue;
2181 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2182 if (kill(- job->pgrp, SIGHUP) == 0)
2183 kill(- job->pgrp, SIGCONT);
2184 }
2185 sigexit(SIGHUP);
2186 }
2187#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002188#if ENABLE_HUSH_FAST
2189 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002190 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002191 G.count_SIGCHLD++;
2192//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2193 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002194 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002195 * This simplifies wait builtin a bit.
2196 */
2197 break;
2198#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002199 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002200 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002201 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002202 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002203 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002204 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002205 * in interactive shell, because TERM is ignored.
2206 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002207 break;
2208 }
2209 }
2210 return last_sig;
2211}
2212
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002213
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002214static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002215{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002216 if (force || G.cwd == NULL) {
2217 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2218 * we must not try to free(bb_msg_unknown) */
2219 if (G.cwd == bb_msg_unknown)
2220 G.cwd = NULL;
2221 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2222 if (!G.cwd)
2223 G.cwd = bb_msg_unknown;
2224 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002225 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002226}
2227
Denis Vlasenko83506862007-11-23 13:11:42 +00002228
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002229/*
2230 * Shell and environment variable support
2231 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002232static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002233{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002234 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002235 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002236
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002237 pp = &G.top_var;
2238 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002239 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002240 return pp;
2241 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002242 }
2243 return NULL;
2244}
2245
Denys Vlasenko03dad222010-01-12 23:29:57 +01002246static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002247{
Denys Vlasenko29082232010-07-16 13:52:32 +02002248 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002249 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002250
2251 if (G.expanded_assignments) {
2252 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002253 while (*cpp) {
2254 char *cp = *cpp;
2255 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2256 return cp + len + 1;
2257 cpp++;
2258 }
2259 }
2260
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002261 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002262 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002263 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002264
Denys Vlasenkodea47882009-10-09 15:40:49 +02002265 if (strcmp(name, "PPID") == 0)
2266 return utoa(G.root_ppid);
2267 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002268#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002269 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002270 return utoa(next_random(&G.random_gen));
2271#endif
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002272#if ENABLE_HUSH_LINENO_VAR
2273 if (strcmp(name, "LINENO") == 0)
2274 return utoa(G.execute_lineno);
2275#endif
Ron Yorstona81700b2019-04-15 10:48:29 +01002276#if BASH_EPOCH_VARS
2277 {
2278 const char *fmt = NULL;
2279 if (strcmp(name, "EPOCHSECONDS") == 0)
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002280 fmt = "%llu";
Ron Yorstona81700b2019-04-15 10:48:29 +01002281 else if (strcmp(name, "EPOCHREALTIME") == 0)
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002282 fmt = "%llu.%06u";
Ron Yorstona81700b2019-04-15 10:48:29 +01002283 if (fmt) {
2284 struct timeval tv;
Denys Vlasenko3c13da32020-12-30 23:48:01 +01002285 xgettimeofday(&tv);
2286 sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
Ron Yorstona81700b2019-04-15 10:48:29 +01002287 (unsigned)tv.tv_usec);
2288 return G.epoch_buf;
2289 }
2290 }
2291#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002292 return NULL;
2293}
2294
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002295#if ENABLE_HUSH_GETOPTS
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002296static void handle_changed_special_names(const char *name, unsigned name_len)
2297{
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002298 if (name_len == 6) {
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002299 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002300 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002301 return;
2302 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002303 }
2304}
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002305#else
2306/* Do not even bother evaluating arguments */
2307# define handle_changed_special_names(...) ((void)0)
2308#endif
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002309
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002310/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002311 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002312 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002313#define SETFLAG_EXPORT (1 << 0)
2314#define SETFLAG_UNEXPORT (1 << 1)
2315#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002316#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002317static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002318{
Denys Vlasenko61407802018-04-04 21:14:28 +02002319 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002320 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002321 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002322 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002323 int name_len;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002324 int retval;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002325 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002326
Denis Vlasenko950bd722009-04-21 11:23:56 +00002327 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002328 if (HUSH_DEBUG && !eq_sign)
James Byrne69374872019-07-02 11:35:03 +02002329 bb_simple_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002330
Denis Vlasenko950bd722009-04-21 11:23:56 +00002331 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002332 cur_pp = &G.top_var;
2333 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002334 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002335 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002336 continue;
2337 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002338
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002339 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002340 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002341 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002342 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002343//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2344//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002345 return -1;
2346 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002347 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002348 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2349 *eq_sign = '\0';
2350 unsetenv(str);
2351 *eq_sign = '=';
2352 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002353 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002354 /* bash 3.2.33(1) and exported vars:
2355 * # export z=z
2356 * # f() { local z=a; env | grep ^z; }
2357 * # f
2358 * z=a
2359 * # env | grep ^z
2360 * z=z
2361 */
2362 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002363 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002364 /* New variable is local ("local VAR=VAL" or
2365 * "VAR=VAL cmd")
2366 * and existing one is global, or local
2367 * on a lower level that new one.
2368 * Remove it from global variable list:
2369 */
2370 *cur_pp = cur->next;
2371 if (G.shadowed_vars_pp) {
2372 /* Save in "shadowed" list */
2373 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2374 cur->flg_export ? "exported " : "",
2375 cur->varstr, cur->var_nest_level, str, local_lvl
2376 );
2377 cur->next = *G.shadowed_vars_pp;
2378 *G.shadowed_vars_pp = cur;
2379 } else {
2380 /* Came from pseudo_exec_argv(), no need to save: delete it */
2381 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2382 cur->flg_export ? "exported " : "",
2383 cur->varstr, cur->var_nest_level, str, local_lvl
2384 );
2385 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2386 free_me = cur->varstr; /* then free it later */
2387 free(cur);
2388 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002389 break;
2390 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002391
Denis Vlasenko950bd722009-04-21 11:23:56 +00002392 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002393 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002394 free_and_exp:
2395 free(str);
2396 goto exp;
2397 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002398
2399 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002400 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002401 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002402 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002403 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002404 strcpy(cur->varstr, str);
2405 goto free_and_exp;
2406 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002407 /* Can't reuse */
2408 cur->max_len = 0;
2409 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002410 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002411 /* max_len == 0 signifies "malloced" var, which we can
2412 * (and have to) free. But we can't free(cur->varstr) here:
2413 * if cur->flg_export is 1, it is in the environment.
2414 * We should either unsetenv+free, or wait until putenv,
2415 * then putenv(new)+free(old).
2416 */
2417 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002418 goto set_str_and_exp;
2419 }
2420
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002421 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002422 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002423 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002424 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002425 cur->next = *cur_pp;
2426 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002427
2428 set_str_and_exp:
2429 cur->varstr = str;
2430 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002431#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002432 if (flags & SETFLAG_MAKE_RO) {
2433 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002434 }
2435#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002436 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002437 cur->flg_export = 1;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002438 retval = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002439 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002440 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002441 cur->flg_export = 0;
2442 /* unsetenv was already done */
2443 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002444 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002445 retval = putenv(cur->varstr);
2446 /* fall through to "free(free_me)" -
2447 * only now we can free old exported malloced string
2448 */
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002449 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002450 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002451 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002452
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002453 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002454
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02002455 return retval;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002456}
2457
Denys Vlasenkofd6f2952018-08-05 15:13:08 +02002458static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2459{
2460 char *var = xasprintf("%s=%s", name, val);
2461 set_local_var(var, /*flag:*/ 0);
2462}
2463
Denys Vlasenko6db47842009-09-05 20:15:17 +02002464/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002465static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002466{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002467 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002468}
2469
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002470#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002471static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002472{
2473 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002474 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002475
Denys Vlasenko61407802018-04-04 21:14:28 +02002476 cur_pp = &G.top_var;
2477 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002478 if (strncmp(cur->varstr, name, name_len) == 0
2479 && cur->varstr[name_len] == '='
2480 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002481 if (cur->flg_read_only) {
2482 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002483 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002484 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002485
Denys Vlasenko61407802018-04-04 21:14:28 +02002486 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002487 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2488 bb_unsetenv(cur->varstr);
2489 if (!cur->max_len)
2490 free(cur->varstr);
2491 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002492
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002493 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002494 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002495 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002496 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002497
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002498 /* Handle "unset LINENO" et al even if did not find the variable to unset */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002499 handle_changed_special_names(name, name_len);
2500
Mike Frysingerd690f682009-03-30 06:50:54 +00002501 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002502}
2503
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002504static int unset_local_var(const char *name)
2505{
2506 return unset_local_var_len(name, strlen(name));
2507}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002508#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002509
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002510
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002511/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002512 * Helpers for "var1=val1 var2=val2 cmd" feature
2513 */
2514static void add_vars(struct variable *var)
2515{
2516 struct variable *next;
2517
2518 while (var) {
2519 next = var->next;
2520 var->next = G.top_var;
2521 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002522 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002523 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002524 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002525 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002526 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002527 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002528 var = next;
2529 }
2530}
2531
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002532/* We put strings[i] into variable table and possibly putenv them.
2533 * If variable is read only, we can free the strings[i]
2534 * which attempts to overwrite it.
2535 * The strings[] vector itself is freed.
2536 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002537static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002538{
2539 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002540
2541 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002542 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002543
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002544 s = strings;
2545 while (*s) {
2546 struct variable *var_p;
2547 struct variable **var_pp;
2548 char *eq;
2549
2550 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002551 if (HUSH_DEBUG && !eq)
James Byrne69374872019-07-02 11:35:03 +02002552 bb_simple_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002553 var_pp = get_ptr_to_local_var(*s, eq - *s);
2554 if (var_pp) {
2555 var_p = *var_pp;
2556 if (var_p->flg_read_only) {
2557 char **p;
2558 bb_error_msg("%s: readonly variable", *s);
2559 /*
2560 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2561 * If VAR is readonly, leaving it in the list
2562 * after asssignment error (msg above)
2563 * causes doubled error message later, on unset.
2564 */
2565 debug_printf_env("removing/freeing '%s' element\n", *s);
2566 free(*s);
2567 p = s;
2568 do { *p = p[1]; p++; } while (*p);
2569 goto next;
2570 }
2571 /* below, set_local_var() with nest level will
2572 * "shadow" (remove) this variable from
2573 * global linked list.
2574 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002575 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002576 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2577 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002578 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002579 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002580 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002581 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002582}
2583
2584
2585/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002586 * Unicode helper
2587 */
2588static void reinit_unicode_for_hush(void)
2589{
2590 /* Unicode support should be activated even if LANG is set
2591 * _during_ shell execution, not only if it was set when
2592 * shell was started. Therefore, re-check LANG every time:
2593 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002594 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2595 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002596 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002597 const char *s = get_local_var_value("LC_ALL");
2598 if (!s) s = get_local_var_value("LC_CTYPE");
2599 if (!s) s = get_local_var_value("LANG");
2600 reinit_unicode(s);
2601 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002602}
2603
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002604/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002605 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002606 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002607
2608#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002609/* To test correct lineedit/interactive behavior, type from command line:
2610 * echo $P\
2611 * \
2612 * AT\
2613 * H\
2614 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002615 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002616 */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002617static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002618{
2619 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002620
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002621 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002622
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002623# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2624 prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
2625 if (!prompt_str)
2626 prompt_str = "";
2627# else
2628 prompt_str = "> "; /* if PS2, else... */
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002629 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002630 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
2631 free(G.PS1);
2632 /* bash uses $PWD value, even if it is set by user.
2633 * It uses current dir only if PWD is unset.
2634 * We always use current dir. */
Denys Vlasenko649acb92020-12-23 15:29:13 +01002635 prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002636 }
Denys Vlasenko4ebcdf72019-05-16 15:39:19 +02002637# endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002638 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002639 return prompt_str;
2640}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002641static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002642{
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002643# if ENABLE_FEATURE_EDITING
2644 /* In EDITING case, this function reads next input line,
2645 * saves it in i->p, then returns 1st char of it.
2646 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002647 int r;
2648 const char *prompt_str;
2649
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002650 prompt_str = setup_prompt_string();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002651 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002652 reinit_unicode_for_hush();
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002653 G.flag_SIGINT = 0;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002654 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002655 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002656 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002657 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002658 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002659 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002660 if (r == 0) {
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002661 raise(SIGINT);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002662 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002663 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002664 if (r != 0 && !G.flag_SIGINT)
2665 break;
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01002666 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002667 /* bash prints ^C even on real SIGINT (non-kbd generated) */
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01002668 write(STDOUT_FILENO, "^C\n", 3);
Denys Vlasenko93e2a222020-12-23 12:23:21 +01002669 G.last_exitcode = 128 | SIGINT;
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002670 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002671 if (r < 0) {
2672 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002673 i->p = NULL;
2674 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002675 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002676 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002677 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002678 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002679# else
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002680 /* In !EDITING case, this function gets called for every char.
2681 * Buffering happens deeper in the call chain, in hfgetc(i->file).
2682 */
2683 int r;
2684
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002685 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002686 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002687 if (i->last_char == '\0' || i->last_char == '\n') {
Denys Vlasenko46a71dc2020-12-25 18:49:29 +01002688 const char *prompt_str = setup_prompt_string();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002689 /* Why check_and_run_traps here? Try this interactively:
2690 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2691 * $ <[enter], repeatedly...>
2692 * Without check_and_run_traps, handler never runs.
2693 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002694 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002695 fputs(prompt_str, stdout);
Denys Vlasenko521220e2020-12-23 23:44:55 +01002696 fflush_all();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002697 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002698 r = hfgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002699 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2700 * no ^C masking happens during fgetc, no special code for ^C:
2701 * it generates SIGINT as usual.
2702 */
2703 check_and_run_traps();
Denys Vlasenko521220e2020-12-23 23:44:55 +01002704 if (r != '\0' && !G.flag_SIGINT)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002705 break;
Denys Vlasenko521220e2020-12-23 23:44:55 +01002706 if (G.flag_SIGINT) {
2707 /* ^C or SIGINT: repeat */
2708 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2709 /* kernel prints "^C" itself, just print newline: */
2710 write(STDOUT_FILENO, "\n", 1);
2711 G.last_exitcode = 128 | SIGINT;
2712 }
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002713 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002714 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002715# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002716}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002717/* This is the magic location that prints prompts
2718 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002719static int fgetc_interactive(struct in_str *i)
2720{
2721 int ch;
2722 /* If it's interactive stdin, get new line. */
Denys Vlasenko21806562019-11-01 14:16:07 +01002723 if (G_interactive_fd && i->file == G.HFILE_stdin) {
Denys Vlasenko4074d492016-09-30 01:49:53 +02002724 /* Returns first char (or EOF), the rest is in i->p[] */
2725 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002726 G.promptmode = 1; /* PS2 */
2727 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002728 } else {
2729 /* Not stdin: script file, sourced file, etc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002730 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002731 }
2732 return ch;
2733}
Denys Vlasenko649acb92020-12-23 15:29:13 +01002734#else /* !INTERACTIVE */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002735static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
Denys Vlasenko4074d492016-09-30 01:49:53 +02002736{
2737 int ch;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002738 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002739 return ch;
2740}
Denys Vlasenko649acb92020-12-23 15:29:13 +01002741#endif /* !INTERACTIVE */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002742
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002743static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002744{
2745 int ch;
2746
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002747 if (!i->file) {
2748 /* string-based in_str */
2749 ch = (unsigned char)*i->p;
2750 if (ch != '\0') {
2751 i->p++;
2752 i->last_char = ch;
2753 return ch;
2754 }
2755 return EOF;
2756 }
2757
2758 /* FILE-based in_str */
2759
Denys Vlasenko4074d492016-09-30 01:49:53 +02002760#if ENABLE_FEATURE_EDITING
2761 /* This can be stdin, check line editing char[] buffer */
2762 if (i->p && *i->p != '\0') {
2763 ch = (unsigned char)*i->p++;
2764 goto out;
2765 }
2766#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002767 /* peek_buf[] is an int array, not char. Can contain EOF. */
2768 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002769 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002770 int ch2 = i->peek_buf[1];
2771 i->peek_buf[0] = ch2;
2772 if (ch2 == 0) /* very likely, avoid redundant write */
2773 goto out;
2774 i->peek_buf[1] = 0;
2775 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002776 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002777
Denys Vlasenko4074d492016-09-30 01:49:53 +02002778 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002779 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002780 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002781 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002782#if ENABLE_HUSH_LINENO_VAR
2783 if (ch == '\n') {
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02002784 G.parse_lineno++;
2785 debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
Denys Vlasenko5807e182018-02-08 19:19:04 +01002786 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002787#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002788 return ch;
2789}
2790
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002791static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002792{
2793 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002794
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002795 if (!i->file) {
2796 /* string-based in_str */
2797 /* Doesn't report EOF on NUL. None of the callers care. */
2798 return (unsigned char)*i->p;
2799 }
2800
2801 /* FILE-based in_str */
2802
Denys Vlasenko4074d492016-09-30 01:49:53 +02002803#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002804 /* This can be stdin, check line editing char[] buffer */
2805 if (i->p && *i->p != '\0')
2806 return (unsigned char)*i->p;
2807#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002808 /* peek_buf[] is an int array, not char. Can contain EOF. */
2809 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002810 if (ch != 0)
2811 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002812
Denys Vlasenko4074d492016-09-30 01:49:53 +02002813 /* Need to get a new char */
2814 ch = fgetc_interactive(i);
2815 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2816
2817 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2818#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2819 if (i->p) {
2820 i->p -= 1;
2821 return ch;
2822 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002823#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002824 i->peek_buf[0] = ch;
2825 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002826 return ch;
2827}
2828
Denys Vlasenko4074d492016-09-30 01:49:53 +02002829/* Only ever called if i_peek() was called, and did not return EOF.
2830 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2831 * not end-of-line. Therefore we never need to read a new editing line here.
2832 */
2833static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002834{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002835 int ch;
2836
2837 /* There are two cases when i->p[] buffer exists.
2838 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002839 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002840 * In both cases, we know that i->p[0] exists and not NUL, and
2841 * the peek2 result is in i->p[1].
2842 */
2843 if (i->p)
2844 return (unsigned char)i->p[1];
2845
2846 /* Now we know it is a file-based in_str. */
2847
2848 /* peek_buf[] is an int array, not char. Can contain EOF. */
2849 /* Is there 2nd char? */
2850 ch = i->peek_buf[1];
2851 if (ch == 0) {
2852 /* We did not read it yet, get it now */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002853 do ch = hfgetc(i->file); while (ch == '\0');
Denys Vlasenko4074d492016-09-30 01:49:53 +02002854 i->peek_buf[1] = ch;
2855 }
2856
2857 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2858 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002859}
2860
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002861static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2862{
2863 for (;;) {
2864 int ch, ch2;
2865
2866 ch = i_getch(input);
2867 if (ch != '\\')
2868 return ch;
2869 ch2 = i_peek(input);
2870 if (ch2 != '\n')
2871 return ch;
2872 /* backslash+newline, skip it */
2873 i_getch(input);
2874 }
2875}
2876
2877/* Note: this function _eats_ \<newline> pairs, safe to use plain
2878 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2879 */
2880static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2881{
2882 for (;;) {
2883 int ch, ch2;
2884
2885 ch = i_peek(input);
2886 if (ch != '\\')
2887 return ch;
2888 ch2 = i_peek2(input);
2889 if (ch2 != '\n')
2890 return ch;
2891 /* backslash+newline, skip it */
2892 i_getch(input);
2893 i_getch(input);
2894 }
2895}
2896
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002897static void setup_file_in_str(struct in_str *i, HFILE *fp)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002898{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002899 memset(i, 0, sizeof(*i));
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02002900 i->file = fp;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002901 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002902}
2903
2904static void setup_string_in_str(struct in_str *i, const char *s)
2905{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002906 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002907 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002908 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002909}
2910
2911
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002912/*
2913 * o_string support
2914 */
2915#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002916
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002917static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002918{
2919 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002920 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002921 if (o->data)
2922 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002923}
2924
Denys Vlasenko18567402018-07-20 17:51:31 +02002925static void o_free_and_set_NULL(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002926{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002927 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002928 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002929}
2930
Denys Vlasenko18567402018-07-20 17:51:31 +02002931static ALWAYS_INLINE void o_free(o_string *o)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002932{
2933 free(o->data);
2934}
2935
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002936static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002937{
2938 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002939 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002940 o->data = xrealloc(o->data, 1 + o->maxlen);
2941 }
2942}
2943
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002944static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002945{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002946 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002947 if (o->length < o->maxlen) {
2948 /* likely. avoid o_grow_by() call */
2949 add:
2950 o->data[o->length] = ch;
2951 o->length++;
2952 o->data[o->length] = '\0';
2953 return;
2954 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002955 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002956 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002957}
2958
Denys Vlasenko657086a2016-09-29 18:07:42 +02002959#if 0
2960/* Valid only if we know o_string is not empty */
2961static void o_delchr(o_string *o)
2962{
2963 o->length--;
2964 o->data[o->length] = '\0';
2965}
2966#endif
2967
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002968static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002969{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002970 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002971 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002972 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002973}
2974
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002975static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002976{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002977 o_addblock(o, str, strlen(str));
2978}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002979
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002980static void o_addstr_with_NUL(o_string *o, const char *str)
2981{
2982 o_addblock(o, str, strlen(str) + 1);
2983}
2984
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002985#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002986static void nommu_addchr(o_string *o, int ch)
2987{
2988 if (o)
2989 o_addchr(o, ch);
2990}
2991#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002992# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002993#endif
2994
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002995#if ENABLE_HUSH_MODE_X
2996static void x_mode_addchr(int ch)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002997{
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02002998 o_addchr(&G.x_mode_buf, ch);
Mike Frysinger98c52642009-04-02 10:02:37 +00002999}
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02003000static void x_mode_addstr(const char *str)
3001{
3002 o_addstr(&G.x_mode_buf, str);
3003}
3004static void x_mode_addblock(const char *str, int len)
3005{
3006 o_addblock(&G.x_mode_buf, str, len);
3007}
3008static void x_mode_prefix(void)
3009{
3010 int n = G.x_mode_depth;
3011 do x_mode_addchr('+'); while (--n >= 0);
3012}
3013static void x_mode_flush(void)
3014{
3015 int len = G.x_mode_buf.length;
3016 if (len <= 0)
3017 return;
3018 if (G.x_mode_fd > 0) {
3019 G.x_mode_buf.data[len] = '\n';
3020 full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
3021 }
3022 G.x_mode_buf.length = 0;
3023}
3024#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00003025
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003026/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02003027 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003028 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
3029 * Apparently, on unquoted $v bash still does globbing
3030 * ("v='*.txt'; echo $v" prints all .txt files),
3031 * but NOT brace expansion! Thus, there should be TWO independent
3032 * quoting mechanisms on $v expansion side: one protects
3033 * $v from brace expansion, and other additionally protects "$v" against globbing.
3034 * We have only second one.
3035 */
3036
Denys Vlasenko9e800222010-10-03 14:28:04 +02003037#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003038# define MAYBE_BRACES "{}"
3039#else
3040# define MAYBE_BRACES ""
3041#endif
3042
Eric Andersen25f27032001-04-26 23:22:31 +00003043/* My analysis of quoting semantics tells me that state information
3044 * is associated with a destination, not a source.
3045 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003046static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00003047{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003048 int sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003049 /* '-' is included because of this case:
3050 * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
3051 */
3052 char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003053 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003054 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003055 o_grow_by(o, sz);
3056 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003057 o->data[o->length] = '\\';
3058 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00003059 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003060 o->data[o->length] = ch;
3061 o->length++;
3062 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00003063}
3064
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003065static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003066{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003067 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003068 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003069 && strchr("*?[-\\" MAYBE_BRACES, ch)
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003070 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003071 sz++;
3072 o->data[o->length] = '\\';
3073 o->length++;
3074 }
3075 o_grow_by(o, sz);
3076 o->data[o->length] = ch;
3077 o->length++;
3078 o->data[o->length] = '\0';
3079}
3080
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003081static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003082{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003083 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003084 char ch;
3085 int sz;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003086 int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003087 if (ordinary_cnt > len) /* paranoia */
3088 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003089 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003090 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003091 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003092 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003093 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003094
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003095 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003096 sz = 1;
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01003097 if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003098 sz++;
3099 o->data[o->length] = '\\';
3100 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003101 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003102 o_grow_by(o, sz);
3103 o->data[o->length] = ch;
3104 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003105 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003106 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003107}
3108
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003109static void o_addQblock(o_string *o, const char *str, int len)
3110{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003111 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003112 o_addblock(o, str, len);
3113 return;
3114 }
3115 o_addqblock(o, str, len);
3116}
3117
Denys Vlasenko38292b62010-09-05 14:49:40 +02003118static void o_addQstr(o_string *o, const char *str)
3119{
3120 o_addQblock(o, str, strlen(str));
3121}
3122
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003123/* A special kind of o_string for $VAR and `cmd` expansion.
3124 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003125 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003126 * list[i] contains an INDEX (int!) into this string data.
3127 * It means that if list[] needs to grow, data needs to be moved higher up
3128 * but list[i]'s need not be modified.
3129 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003130 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003131 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
3132 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003133#if DEBUG_EXPAND || DEBUG_GLOB
3134static void debug_print_list(const char *prefix, o_string *o, int n)
3135{
3136 char **list = (char**)o->data;
3137 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3138 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003139
3140 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003141 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 +02003142 prefix, list, n, string_start, o->length, o->maxlen,
3143 !!(o->o_expflags & EXP_FLAG_GLOB),
3144 o->has_quoted_part,
3145 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003146 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003147 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003148 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
3149 o->data + (int)(uintptr_t)list[i] + string_start,
3150 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003151 i++;
3152 }
3153 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003154 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003155 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003156 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003157 }
3158}
3159#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003160# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003161#endif
3162
3163/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3164 * in list[n] so that it points past last stored byte so far.
3165 * It returns n+1. */
3166static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003167{
3168 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003169 int string_start;
3170 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003171
3172 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003173 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3174 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003175 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003176 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003177 /* list[n] points to string_start, make space for 16 more pointers */
3178 o->maxlen += 0x10 * sizeof(list[0]);
3179 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003180 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003181 memmove(list + n + 0x10, list + n, string_len);
Denys Vlasenko186cf492018-07-27 12:14:39 +02003182 /*
3183 * expand_on_ifs() has a "previous argv[] ends in IFS?"
3184 * check. (grep for -prev-ifs-check-).
3185 * Ensure that argv[-1][last] is not garbage
3186 * but zero bytes, to save index check there.
3187 */
3188 list[n + 0x10 - 1] = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003189 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003190 } else {
3191 debug_printf_list("list[%d]=%d string_start=%d\n",
3192 n, string_len, string_start);
3193 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003194 } else {
3195 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003196 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3197 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003198 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3199 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003200 o->has_empty_slot = 0;
3201 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003202 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003203 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003204 return n + 1;
3205}
3206
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003207/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003208static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003209{
3210 char **list = (char**)o->data;
3211 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3212
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003213 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003214}
3215
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003216/*
3217 * Globbing routines.
3218 *
3219 * Most words in commands need to be globbed, even ones which are
3220 * (single or double) quoted. This stems from the possiblity of
3221 * constructs like "abc"* and 'abc'* - these should be globbed.
3222 * Having a different code path for fully-quoted strings ("abc",
3223 * 'abc') would only help performance-wise, but we still need
3224 * code for partially-quoted strings.
3225 *
3226 * Unfortunately, if we want to match bash and ash behavior in all cases,
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003227 * the logic can't be "shell-syntax argument is first transformed
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003228 * to a string, then globbed, and if globbing does not match anything,
3229 * it is used verbatim". Here are two examples where it fails:
3230 *
3231 * echo 'b\*'?
3232 *
3233 * The globbing can't be avoided (because of '?' at the end).
3234 * The glob pattern is: b\\\*? - IOW, both \ and * are literals
3235 * and are glob-escaped. If this does not match, bash/ash print b\*?
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003236 * - IOW: they "unbackslash" the glob pattern.
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003237 * Now, look at this:
3238 *
3239 * v='\\\*'; echo b$v?
3240 *
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003241 * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003242 * should be used as glob pattern with no changes. However, if glob
Denys Vlasenkoc97df292018-08-14 11:04:58 +02003243 * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
Denys Vlasenko4bf08542018-08-11 18:44:11 +02003244 *
3245 * ash implements this by having an encoded representation of the word
3246 * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
3247 * Glob pattern is derived from it. If glob fails, the decision what result
3248 * should be is made using that encoded representation. Not glob pattern.
3249 */
3250
Denys Vlasenko9e800222010-10-03 14:28:04 +02003251#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003252/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3253 * first, it processes even {a} (no commas), second,
3254 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003255 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003256 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003257
3258/* Helper */
3259static int glob_needed(const char *s)
3260{
3261 while (*s) {
3262 if (*s == '\\') {
3263 if (!s[1])
3264 return 0;
3265 s += 2;
3266 continue;
3267 }
3268 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3269 return 1;
3270 s++;
3271 }
3272 return 0;
3273}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003274/* Return pointer to next closing brace or to comma */
3275static const char *next_brace_sub(const char *cp)
3276{
3277 unsigned depth = 0;
3278 cp++;
3279 while (*cp != '\0') {
3280 if (*cp == '\\') {
3281 if (*++cp == '\0')
3282 break;
3283 cp++;
3284 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003285 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003286 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003287 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003288 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003289 depth++;
3290 }
3291
3292 return *cp != '\0' ? cp : NULL;
3293}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003294/* Recursive brace globber. Note: may garble pattern[]. */
3295static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003296{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003297 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003298 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003299 const char *next;
3300 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003301 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003302 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003303
3304 debug_printf_glob("glob_brace('%s')\n", pattern);
3305
3306 begin = pattern;
3307 while (1) {
3308 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003309 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003310 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003311 /* Find the first sub-pattern and at the same time
3312 * find the rest after the closing brace */
3313 next = next_brace_sub(begin);
3314 if (next == NULL) {
3315 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003316 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003317 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003318 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003319 /* "{abc}" with no commas - illegal
3320 * brace expr, disregard and skip it */
3321 begin = next + 1;
3322 continue;
3323 }
3324 break;
3325 }
3326 if (*begin == '\\' && begin[1] != '\0')
3327 begin++;
3328 begin++;
3329 }
3330 debug_printf_glob("begin:%s\n", begin);
3331 debug_printf_glob("next:%s\n", next);
3332
3333 /* Now find the end of the whole brace expression */
3334 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003335 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003336 rest = next_brace_sub(rest);
3337 if (rest == NULL) {
3338 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003339 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003340 }
3341 debug_printf_glob("rest:%s\n", rest);
3342 }
3343 rest_len = strlen(++rest) + 1;
3344
3345 /* We are sure the brace expression is well-formed */
3346
3347 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003348 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003349
3350 /* We have a brace expression. BEGIN points to the opening {,
3351 * NEXT points past the terminator of the first element, and REST
3352 * points past the final }. We will accumulate result names from
3353 * recursive runs for each brace alternative in the buffer using
3354 * GLOB_APPEND. */
3355
3356 p = begin + 1;
3357 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003358 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003359 memcpy(
3360 mempcpy(
3361 mempcpy(new_pattern_buf,
3362 /* We know the prefix for all sub-patterns */
3363 pattern, begin - pattern),
3364 p, next - p),
3365 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003366
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003367 /* Note: glob_brace() may garble new_pattern_buf[].
3368 * That's why we re-copy prefix every time (1st memcpy above).
3369 */
3370 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003371 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003372 /* We saw the last entry */
3373 break;
3374 }
3375 p = next + 1;
3376 next = next_brace_sub(next);
3377 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003378 free(new_pattern_buf);
3379 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003380
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003381 simple_glob:
3382 {
3383 int gr;
3384 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003385
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003386 memset(&globdata, 0, sizeof(globdata));
3387 gr = glob(pattern, 0, NULL, &globdata);
3388 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3389 if (gr != 0) {
3390 if (gr == GLOB_NOMATCH) {
3391 globfree(&globdata);
3392 /* NB: garbles parameter */
3393 unbackslash(pattern);
3394 o_addstr_with_NUL(o, pattern);
3395 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3396 return o_save_ptr_helper(o, n);
3397 }
3398 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003399 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003400 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3401 * but we didn't specify it. Paranoia again. */
3402 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3403 }
3404 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3405 char **argv = globdata.gl_pathv;
3406 while (1) {
3407 o_addstr_with_NUL(o, *argv);
3408 n = o_save_ptr_helper(o, n);
3409 argv++;
3410 if (!*argv)
3411 break;
3412 }
3413 }
3414 globfree(&globdata);
3415 }
3416 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003417}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003418/* Performs globbing on last list[],
3419 * saving each result as a new list[].
3420 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003421static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003422{
3423 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003424
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003425 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003426 if (!o->data)
3427 return o_save_ptr_helper(o, n);
3428 pattern = o->data + o_get_last_ptr(o, n);
3429 debug_printf_glob("glob pattern '%s'\n", pattern);
3430 if (!glob_needed(pattern)) {
3431 /* unbackslash last string in o in place, fix length */
3432 o->length = unbackslash(pattern) - o->data;
3433 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3434 return o_save_ptr_helper(o, n);
3435 }
3436
3437 copy = xstrdup(pattern);
3438 /* "forget" pattern in o */
3439 o->length = pattern - o->data;
3440 n = glob_brace(copy, o, n);
3441 free(copy);
3442 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003443 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003444 return n;
3445}
3446
Denys Vlasenko238081f2010-10-03 14:26:26 +02003447#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003448
3449/* Helper */
3450static int glob_needed(const char *s)
3451{
3452 while (*s) {
3453 if (*s == '\\') {
3454 if (!s[1])
3455 return 0;
3456 s += 2;
3457 continue;
3458 }
3459 if (*s == '*' || *s == '[' || *s == '?')
3460 return 1;
3461 s++;
3462 }
3463 return 0;
3464}
3465/* Performs globbing on last list[],
3466 * saving each result as a new list[].
3467 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003468static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003469{
3470 glob_t globdata;
3471 int gr;
3472 char *pattern;
3473
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003474 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003475 if (!o->data)
3476 return o_save_ptr_helper(o, n);
3477 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003478 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003479 if (!glob_needed(pattern)) {
3480 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003481 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003482 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003483 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003484 return o_save_ptr_helper(o, n);
3485 }
3486
3487 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003488 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3489 * If we glob "*.\*" and don't find anything, we need
3490 * to fall back to using literal "*.*", but GLOB_NOCHECK
3491 * will return "*.\*"!
3492 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003493 gr = glob(pattern, 0, NULL, &globdata);
3494 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003495 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003496 if (gr == GLOB_NOMATCH) {
3497 globfree(&globdata);
3498 goto literal;
3499 }
3500 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003501 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003502 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3503 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003504 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003505 }
3506 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3507 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003508 /* "forget" pattern in o */
3509 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003510 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003511 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003512 n = o_save_ptr_helper(o, n);
3513 argv++;
3514 if (!*argv)
3515 break;
3516 }
3517 }
3518 globfree(&globdata);
3519 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003520 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003521 return n;
3522}
3523
Denys Vlasenko238081f2010-10-03 14:26:26 +02003524#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003525
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003526/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003527 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003528static int o_save_ptr(o_string *o, int n)
3529{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003530 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003531 /* If o->has_empty_slot, list[n] was already globbed
3532 * (if it was requested back then when it was filled)
3533 * so don't do that again! */
3534 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003535 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003536 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003537 return o_save_ptr_helper(o, n);
3538}
3539
3540/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003541static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003542{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003543 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003544 int string_start;
3545
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003546 if (DEBUG_EXPAND)
3547 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003548 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003549 list = (char**)o->data;
3550 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3551 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003552 while (n) {
3553 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003554 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003555 }
3556 return list;
3557}
3558
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003559static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003560
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003561/* Returns pi->next - next pipe in the list */
3562static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003563{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003564 struct pipe *next;
3565 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003566
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003567 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003568 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003569 struct command *command;
3570 struct redir_struct *r, *rnext;
3571
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003572 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003573 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003574 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003575 if (DEBUG_CLEAN) {
3576 int a;
3577 char **p;
3578 for (a = 0, p = command->argv; *p; a++, p++) {
3579 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3580 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003581 }
3582 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003583 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003584 }
3585 /* not "else if": on syntax error, we may have both! */
3586 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003587 debug_printf_clean(" begin group (cmd_type:%d)\n",
3588 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003589 free_pipe_list(command->group);
3590 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003591 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003592 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003593 /* else is crucial here.
3594 * If group != NULL, child_func is meaningless */
3595#if ENABLE_HUSH_FUNCTIONS
3596 else if (command->child_func) {
3597 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3598 command->child_func->parent_cmd = NULL;
3599 }
3600#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003601#if !BB_MMU
3602 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003603 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003604#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003605 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003606 debug_printf_clean(" redirect %d%s",
3607 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003608 /* guard against the case >$FOO, where foo is unset or blank */
3609 if (r->rd_filename) {
3610 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3611 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003612 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003613 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003614 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003615 rnext = r->next;
3616 free(r);
3617 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003618 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003619 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003620 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003621 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003622#if ENABLE_HUSH_JOB
3623 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003624 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003625#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003626
3627 next = pi->next;
3628 free(pi);
3629 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003630}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003631
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003632static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003633{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003634 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003635#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003636 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003637#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003638 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003639 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003640 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003641}
3642
3643
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003644/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003645
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003646#ifndef debug_print_tree
3647static void debug_print_tree(struct pipe *pi, int lvl)
3648{
3649 static const char *const PIPE[] = {
3650 [PIPE_SEQ] = "SEQ",
3651 [PIPE_AND] = "AND",
3652 [PIPE_OR ] = "OR" ,
3653 [PIPE_BG ] = "BG" ,
3654 };
3655 static const char *RES[] = {
3656 [RES_NONE ] = "NONE" ,
3657# if ENABLE_HUSH_IF
3658 [RES_IF ] = "IF" ,
3659 [RES_THEN ] = "THEN" ,
3660 [RES_ELIF ] = "ELIF" ,
3661 [RES_ELSE ] = "ELSE" ,
3662 [RES_FI ] = "FI" ,
3663# endif
3664# if ENABLE_HUSH_LOOPS
3665 [RES_FOR ] = "FOR" ,
3666 [RES_WHILE] = "WHILE",
3667 [RES_UNTIL] = "UNTIL",
3668 [RES_DO ] = "DO" ,
3669 [RES_DONE ] = "DONE" ,
3670# endif
3671# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3672 [RES_IN ] = "IN" ,
3673# endif
3674# if ENABLE_HUSH_CASE
3675 [RES_CASE ] = "CASE" ,
3676 [RES_CASE_IN ] = "CASE_IN" ,
3677 [RES_MATCH] = "MATCH",
3678 [RES_CASE_BODY] = "CASE_BODY",
3679 [RES_ESAC ] = "ESAC" ,
3680# endif
3681 [RES_XXXX ] = "XXXX" ,
3682 [RES_SNTX ] = "SNTX" ,
3683 };
3684 static const char *const CMDTYPE[] = {
3685 "{}",
3686 "()",
3687 "[noglob]",
3688# if ENABLE_HUSH_FUNCTIONS
3689 "func()",
3690# endif
3691 };
3692
3693 int pin, prn;
3694
3695 pin = 0;
3696 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003697 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3698 lvl*2, "",
3699 pin,
3700 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3701 RES[pi->res_word],
3702 pi->followup, PIPE[pi->followup]
3703 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003704 prn = 0;
3705 while (prn < pi->num_cmds) {
3706 struct command *command = &pi->cmds[prn];
3707 char **argv = command->argv;
3708
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003709 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003710 lvl*2, "", prn,
3711 command->assignment_cnt);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003712# if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko5807e182018-02-08 19:19:04 +01003713 fdprintf(2, " LINENO:%u", command->lineno);
Denys Vlasenko259747c2019-11-28 10:28:14 +01003714# endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003715 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003716 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003717 CMDTYPE[command->cmd_type],
3718 argv
3719# if !BB_MMU
3720 , " group_as_string:", command->group_as_string
3721# else
3722 , "", ""
3723# endif
3724 );
3725 debug_print_tree(command->group, lvl+1);
3726 prn++;
3727 continue;
3728 }
3729 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003730 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003731 argv++;
3732 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02003733 if (command->redirects)
3734 fdprintf(2, " {redir}");
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003735 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003736 prn++;
3737 }
3738 pi = pi->next;
3739 pin++;
3740 }
3741}
3742#endif /* debug_print_tree */
3743
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003744static struct pipe *new_pipe(void)
3745{
Eric Andersen25f27032001-04-26 23:22:31 +00003746 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003747 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003748 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003749 return pi;
3750}
3751
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003752/* Command (member of a pipe) is complete, or we start a new pipe
3753 * if ctx->command is NULL.
3754 * No errors possible here.
3755 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003756static int done_command(struct parse_context *ctx)
3757{
3758 /* The command is really already in the pipe structure, so
3759 * advance the pipe counter and make a new, null command. */
3760 struct pipe *pi = ctx->pipe;
3761 struct command *command = ctx->command;
3762
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003763#if 0 /* Instead we emit error message at run time */
3764 if (ctx->pending_redirect) {
3765 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003766 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003767 ctx->pending_redirect = NULL;
3768 }
3769#endif
3770
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003771 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003772 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003773 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003774 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003775 }
3776 pi->num_cmds++;
3777 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003778 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003779 } else {
3780 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3781 }
3782
3783 /* Only real trickiness here is that the uncommitted
3784 * command structure is not counted in pi->num_cmds. */
3785 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003786 ctx->command = command = &pi->cmds[pi->num_cmds];
3787 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003788 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003789#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02003790 command->lineno = G.parse_lineno;
3791 debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003792#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003793 return pi->num_cmds; /* used only for 0/nonzero check */
3794}
3795
3796static void done_pipe(struct parse_context *ctx, pipe_style type)
3797{
3798 int not_null;
3799
3800 debug_printf_parse("done_pipe entered, followup %d\n", type);
3801 /* Close previous command */
3802 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003803#if HAS_KEYWORDS
3804 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3805 ctx->ctx_inverted = 0;
3806 ctx->pipe->res_word = ctx->ctx_res_w;
3807#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003808 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3809 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003810 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3811 * in a backgrounded subshell.
3812 */
3813 struct pipe *pi;
3814 struct command *command;
3815
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003816 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003817 pi = ctx->list_head;
3818 while (pi != ctx->pipe) {
3819 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3820 goto no_conv;
3821 pi = pi->next;
3822 }
3823
3824 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3825 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3826 pi = xzalloc(sizeof(*pi));
3827 pi->followup = PIPE_BG;
3828 pi->num_cmds = 1;
3829 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3830 command = &pi->cmds[0];
3831 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3832 command->cmd_type = CMD_NORMAL;
3833 command->group = ctx->list_head;
3834#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003835 command->group_as_string = xstrndup(
3836 ctx->as_string.data,
3837 ctx->as_string.length - 1 /* do not copy last char, "&" */
3838 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003839#endif
3840 /* Replace all pipes in ctx with one newly created */
3841 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003842 } else {
3843 no_conv:
3844 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003845 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003846
3847 /* Without this check, even just <enter> on command line generates
3848 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003849 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003850 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003851#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003852 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003853#endif
3854#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003855 || ctx->ctx_res_w == RES_DONE
3856 || ctx->ctx_res_w == RES_FOR
3857 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003858#endif
3859#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003860 || ctx->ctx_res_w == RES_ESAC
3861#endif
3862 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003863 struct pipe *new_p;
3864 debug_printf_parse("done_pipe: adding new pipe: "
3865 "not_null:%d ctx->ctx_res_w:%d\n",
3866 not_null, ctx->ctx_res_w);
3867 new_p = new_pipe();
3868 ctx->pipe->next = new_p;
3869 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003870 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003871 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003872 * This is used to control execution.
3873 * RES_FOR and RES_IN are NOT sticky (needed to support
3874 * cases where variable or value happens to match a keyword):
3875 */
3876#if ENABLE_HUSH_LOOPS
3877 if (ctx->ctx_res_w == RES_FOR
3878 || ctx->ctx_res_w == RES_IN)
3879 ctx->ctx_res_w = RES_NONE;
3880#endif
3881#if ENABLE_HUSH_CASE
3882 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003883 ctx->ctx_res_w = RES_CASE_BODY;
3884 if (ctx->ctx_res_w == RES_CASE)
3885 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003886#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003887 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003888 /* Create the memory for command, roughly:
3889 * ctx->pipe->cmds = new struct command;
3890 * ctx->command = &ctx->pipe->cmds[0];
3891 */
3892 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003893 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003894 }
3895 debug_printf_parse("done_pipe return\n");
3896}
3897
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003898static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003899{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003900 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003901 if (MAYBE_ASSIGNMENT != 0)
3902 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003903 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003904 /* Create the memory for command, roughly:
3905 * ctx->pipe->cmds = new struct command;
3906 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003907 */
3908 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003909}
3910
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003911/* If a reserved word is found and processed, parse context is modified
3912 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003913 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003914#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003915struct reserved_combo {
3916 char literal[6];
3917 unsigned char res;
3918 unsigned char assignment_flag;
Denys Vlasenko965b7952020-11-30 13:03:03 +01003919 uint32_t flag;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003920};
3921enum {
3922 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003923# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003924 FLAG_IF = (1 << RES_IF ),
3925 FLAG_THEN = (1 << RES_THEN ),
3926 FLAG_ELIF = (1 << RES_ELIF ),
3927 FLAG_ELSE = (1 << RES_ELSE ),
3928 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003929# endif
3930# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003931 FLAG_FOR = (1 << RES_FOR ),
3932 FLAG_WHILE = (1 << RES_WHILE),
3933 FLAG_UNTIL = (1 << RES_UNTIL),
3934 FLAG_DO = (1 << RES_DO ),
3935 FLAG_DONE = (1 << RES_DONE ),
3936 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003937# endif
3938# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003939 FLAG_MATCH = (1 << RES_MATCH),
3940 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003941# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003942 FLAG_START = (1 << RES_XXXX ),
3943};
3944
3945static const struct reserved_combo* match_reserved_word(o_string *word)
3946{
Eric Andersen25f27032001-04-26 23:22:31 +00003947 /* Mostly a list of accepted follow-up reserved words.
3948 * FLAG_END means we are done with the sequence, and are ready
3949 * to turn the compound list into a command.
3950 * FLAG_START means the word must start a new compound list.
3951 */
Denys Vlasenko965b7952020-11-30 13:03:03 +01003952 static const struct reserved_combo reserved_list[] ALIGN4 = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003953# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003954 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3955 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3956 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3957 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3958 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3959 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003960# endif
3961# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003962 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3963 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3964 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3965 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3966 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3967 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003968# endif
3969# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003970 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3971 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003972# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003973 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003974 const struct reserved_combo *r;
3975
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003976 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003977 if (strcmp(word->data, r->literal) == 0)
3978 return r;
3979 }
3980 return NULL;
3981}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003982/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003983 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003984static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003985{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003986# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003987 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003988 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003989 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003990# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003991 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003992
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003993 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003994 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003995 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003996 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003997 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003998
3999 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004000# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004001 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4002 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004003 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004004 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004005# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004006 if (r->flag == 0) { /* '!' */
4007 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004008 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004009 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004010 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004011 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01004012 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004013 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004014 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004015 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004016
Denys Vlasenko9e55a152017-07-10 10:01:12 +02004017 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004018 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004019 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004020 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004021 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004022 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004023 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01004024 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004025 } else {
4026 /* "{...} fi" is ok. "{...} if" is not
4027 * Example:
4028 * if { echo foo; } then { echo bar; } fi */
4029 if (ctx->command->group)
4030 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004031 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004032
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004033 ctx->ctx_res_w = r->res;
4034 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004035 ctx->is_assignment = r->assignment_flag;
4036 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004037
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004038 if (ctx->old_flag & FLAG_END) {
4039 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004040
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004041 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004042 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004043 old = ctx->stack;
4044 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004045 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004046# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004047 /* At this point, the compound command's string is in
4048 * ctx->as_string... except for the leading keyword!
4049 * Consider this example: "echo a | if true; then echo a; fi"
4050 * ctx->as_string will contain "true; then echo a; fi",
4051 * with "if " remaining in old->as_string!
4052 */
4053 {
4054 char *str;
4055 int len = old->as_string.length;
4056 /* Concatenate halves */
4057 o_addstr(&old->as_string, ctx->as_string.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02004058 o_free(&ctx->as_string);
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004059 /* Find where leading keyword starts in first half */
4060 str = old->as_string.data + len;
4061 if (str > old->as_string.data)
4062 str--; /* skip whitespace after keyword */
4063 while (str > old->as_string.data && isalpha(str[-1]))
4064 str--;
4065 /* Ugh, we're done with this horrid hack */
4066 old->command->group_as_string = xstrdup(str);
4067 debug_printf_parse("pop, remembering as:'%s'\n",
4068 old->command->group_as_string);
4069 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004070# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004071 *ctx = *old; /* physical copy */
4072 free(old);
4073 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01004074 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00004075}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004076#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004077
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004078/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004079 * Normal return is 0. Syntax errors return 1.
4080 * Note: on return, word is reset, but not o_free'd!
4081 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004082static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004083{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004084 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004085
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004086 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
4087 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004088 debug_printf_parse("done_word return 0: true null, ignored\n");
4089 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004090 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004091
Eric Andersen25f27032001-04-26 23:22:31 +00004092 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004093 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4094 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004095 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004096 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004097 * If the redirection operator is "<<" or "<<-", the word
4098 * that follows the redirection operator shall be
4099 * subjected to quote removal; it is unspecified whether
4100 * any of the other expansions occur. For the other
4101 * redirection operators, the word that follows the
4102 * redirection operator shall be subjected to tilde
4103 * expansion, parameter expansion, command substitution,
4104 * arithmetic expansion, and quote removal.
4105 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004106 * on the word by a non-interactive shell; an interactive
4107 * shell may perform it, but shall do so only when
4108 * the expansion would result in one word."
4109 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004110//bash does not do parameter/command substitution or arithmetic expansion
4111//for _heredoc_ redirection word: these constructs look for exact eof marker
4112// as written:
4113// <<EOF$t
4114// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02004115// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
4116
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004117 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004118 /* Cater for >\file case:
4119 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4120 * Same with heredocs:
4121 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4122 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004123 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4124 unbackslash(ctx->pending_redirect->rd_filename);
4125 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004126 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004127 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4128 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004129 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004130 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004131 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004132 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004133#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004134# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004135 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004136 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00004137 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004138 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004139 /* ctx->ctx_res_w = RES_MATCH; */
4140 ctx->ctx_dsemicolon = 0;
4141 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004142# endif
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004143# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4144 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
4145 && strcmp(ctx->word.data, "]]") == 0
4146 ) {
4147 /* allow "[[ ]] >file" etc */
4148 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4149 } else
4150# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004151 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004152# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004153 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4154 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004155# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004156# if ENABLE_HUSH_CASE
4157 && ctx->ctx_res_w != RES_CASE
4158# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004159 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004160 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004161 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01004162 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004163 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01004164# if ENABLE_HUSH_LINENO_VAR
4165/* Case:
4166 * "while ...; do
4167 * cmd ..."
4168 * If we don't close the pipe _now_, immediately after "do", lineno logic
4169 * sees "cmd" as starting at "do" - i.e., at the previous line.
4170 */
4171 if (0
4172 IF_HUSH_IF(|| reserved->res == RES_THEN)
4173 IF_HUSH_IF(|| reserved->res == RES_ELIF)
4174 IF_HUSH_IF(|| reserved->res == RES_ELSE)
4175 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
4176 ) {
4177 done_pipe(ctx, PIPE_SEQ);
4178 }
4179# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004180 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004181 debug_printf_parse("done_word return %d\n",
4182 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004183 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004184 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004185# if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
4186 if (strcmp(ctx->word.data, "[[") == 0) {
4187 command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
4188 } else
4189# endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02004190# if defined(CMD_SINGLEWORD_NOGLOB)
4191 if (0
Denys Vlasenko11752d42018-04-03 08:20:58 +02004192 /* In bash, local/export/readonly are special, args
4193 * are assignments and therefore expansion of them
4194 * should be "one-word" expansion:
4195 * $ export i=`echo 'a b'` # one arg: "i=a b"
4196 * compare with:
4197 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
4198 * ls: cannot access i=a: No such file or directory
4199 * ls: cannot access b: No such file or directory
4200 * Note: bash 3.2.33(1) does this only if export word
4201 * itself is not quoted:
4202 * $ export i=`echo 'aaa bbb'`; echo "$i"
4203 * aaa bbb
4204 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
4205 * aaa
4206 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004207 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
4208 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
4209 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02004210 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004211 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4212 }
Denys Vlasenkod2241f52020-10-31 03:34:07 +01004213# else
4214 { /* empty block to pair "if ... else" */ }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004215# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004216 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004217#endif /* HAS_KEYWORDS */
4218
Denis Vlasenkobb929512009-04-16 10:59:40 +00004219 if (command->group) {
4220 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004221 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004222 debug_printf_parse("done_word return 1: syntax error, "
4223 "groups and arglists don't mix\n");
4224 return 1;
4225 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004226
4227 /* If this word wasn't an assignment, next ones definitely
4228 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004229 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4230 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004231 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004232 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004233 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004234 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004235 command->assignment_cnt++;
4236 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4237 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004238 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4239 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004240 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004241 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4242 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004243 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004244 }
Eric Andersen25f27032001-04-26 23:22:31 +00004245
Denis Vlasenko06810332007-05-21 23:30:54 +00004246#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004247 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004248 if (ctx->word.has_quoted_part
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02004249 || endofname(command->argv[0])[0] != '\0'
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004250 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004251 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004252 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004253 return 1;
4254 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004255 /* Force FOR to have just one word (variable name) */
4256 /* NB: basically, this makes hush see "for v in ..."
4257 * syntax as if it is "for v; in ...". FOR and IN become
4258 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004259 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004260 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004261#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004262#if ENABLE_HUSH_CASE
4263 /* Force CASE to have just one word */
4264 if (ctx->ctx_res_w == RES_CASE) {
4265 done_pipe(ctx, PIPE_SEQ);
4266 }
4267#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004268
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004269 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004270
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004271 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004272 return 0;
4273}
4274
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004275
4276/* Peek ahead in the input to find out if we have a "&n" construct,
4277 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004278 * Return:
4279 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4280 * REDIRFD_SYNTAX_ERR if syntax error,
4281 * REDIRFD_TO_FILE if no & was seen,
4282 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004283 */
4284#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004285#define parse_redir_right_fd(as_string, input) \
4286 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004287#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004288static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004289{
4290 int ch, d, ok;
4291
4292 ch = i_peek(input);
4293 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004294 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004295
4296 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004297 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004298 ch = i_peek(input);
4299 if (ch == '-') {
4300 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004301 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004302 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004303 }
4304 d = 0;
4305 ok = 0;
4306 while (ch != EOF && isdigit(ch)) {
4307 d = d*10 + (ch-'0');
4308 ok = 1;
4309 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004310 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004311 ch = i_peek(input);
4312 }
4313 if (ok) return d;
4314
4315//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4316
James Byrne69374872019-07-02 11:35:03 +02004317 bb_simple_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004318 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004319}
4320
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004321/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004322 */
4323static int parse_redirect(struct parse_context *ctx,
4324 int fd,
4325 redir_type style,
4326 struct in_str *input)
4327{
4328 struct command *command = ctx->command;
4329 struct redir_struct *redir;
4330 struct redir_struct **redirp;
4331 int dup_num;
4332
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004333 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004334 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004335 /* Check for a '>&1' type redirect */
4336 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4337 if (dup_num == REDIRFD_SYNTAX_ERR)
4338 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004339 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004340 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004341 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004342 if (dup_num) { /* <<-... */
4343 ch = i_getch(input);
4344 nommu_addchr(&ctx->as_string, ch);
4345 ch = i_peek(input);
4346 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004347 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004348
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004349 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004350 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004351 if (ch == '|') {
4352 /* >|FILE redirect ("clobbering" >).
4353 * Since we do not support "set -o noclobber" yet,
4354 * >| and > are the same for now. Just eat |.
4355 */
4356 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004357 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004358 }
4359 }
4360
4361 /* Create a new redir_struct and append it to the linked list */
4362 redirp = &command->redirects;
4363 while ((redir = *redirp) != NULL) {
4364 redirp = &(redir->next);
4365 }
4366 *redirp = redir = xzalloc(sizeof(*redir));
4367 /* redir->next = NULL; */
4368 /* redir->rd_filename = NULL; */
4369 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004370 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004371
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004372 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4373 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004374
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004375 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004376 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004377 /* Erik had a check here that the file descriptor in question
4378 * is legit; I postpone that to "run time"
4379 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004380 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4381 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004382 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004383#if 0 /* Instead we emit error message at run time */
4384 if (ctx->pending_redirect) {
4385 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004386 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004387 }
4388#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004389 /* Set ctx->pending_redirect, so we know what to do at the
4390 * end of the next parsed word. */
4391 ctx->pending_redirect = redir;
4392 }
4393 return 0;
4394}
4395
Eric Andersen25f27032001-04-26 23:22:31 +00004396/* If a redirect is immediately preceded by a number, that number is
4397 * supposed to tell which file descriptor to redirect. This routine
4398 * looks for such preceding numbers. In an ideal world this routine
4399 * needs to handle all the following classes of redirects...
4400 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4401 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4402 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4403 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004404 *
4405 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4406 * "2.7 Redirection
4407 * ... If n is quoted, the number shall not be recognized as part of
4408 * the redirection expression. For example:
4409 * echo \2>a
4410 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004411 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004412 *
4413 * A -1 return means no valid number was found,
4414 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004415 */
4416static int redirect_opt_num(o_string *o)
4417{
4418 int num;
4419
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004420 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004421 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004422 num = bb_strtou(o->data, NULL, 10);
4423 if (errno || num < 0)
4424 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004425 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004426 return num;
4427}
4428
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004429#if BB_MMU
4430#define fetch_till_str(as_string, input, word, skip_tabs) \
4431 fetch_till_str(input, word, skip_tabs)
4432#endif
4433static char *fetch_till_str(o_string *as_string,
4434 struct in_str *input,
4435 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004436 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004437{
4438 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004439 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004440 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004441 int ch;
4442
Denys Vlasenkod73cdbf2018-07-23 15:43:57 +02004443 /* Starting with "" is necessary for this case:
4444 * cat <<EOF
4445 *
4446 * xxx
4447 * EOF
4448 */
4449 heredoc.data = xzalloc(1); /* start as "", not as NULL */
4450
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004451 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004452
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004453 while (1) {
4454 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004455 if (ch != EOF)
4456 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004457 if (ch == '\n' || ch == EOF) {
4458 check_heredoc_end:
4459 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004460 /* End-of-line, and not a line continuation */
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004461 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4462 heredoc.data[past_EOL] = '\0';
Denys Vlasenko3675c372018-07-23 16:31:21 +02004463 debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004464 return heredoc.data;
4465 }
4466 if (ch == '\n') {
4467 /* This is a new line.
4468 * Remember position and backslash-escaping status.
4469 */
4470 o_addchr(&heredoc, ch);
4471 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004472 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004473 past_EOL = heredoc.length;
4474 /* Get 1st char of next line, possibly skipping leading tabs */
4475 do {
4476 ch = i_getch(input);
4477 if (ch != EOF)
4478 nommu_addchr(as_string, ch);
4479 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4480 /* If this immediately ended the line,
4481 * go back to end-of-line checks.
4482 */
4483 if (ch == '\n')
4484 goto check_heredoc_end;
4485 }
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004486 } else {
4487 /* Backslash-line continuation in an unquoted
4488 * heredoc. This does not need special handling
4489 * for heredoc body (unquoted heredocs are
4490 * expanded on "execution" and that would take
4491 * care of this case too), but not the case
4492 * of line continuation *in terminator*:
4493 * cat <<EOF
4494 * Ok1
4495 * EO\
4496 * F
4497 */
4498 heredoc.data[--heredoc.length] = '\0';
4499 prev = 0; /* not '\' */
4500 continue;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004501 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004502 }
4503 if (ch == EOF) {
Denys Vlasenko18567402018-07-20 17:51:31 +02004504 o_free(&heredoc);
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004505 return NULL; /* error */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004506 }
4507 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004508 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004509 if (prev == '\\' && ch == '\\')
4510 /* Correctly handle foo\\<eol> (not a line cont.) */
Denys Vlasenkodfc73942018-07-24 14:03:18 +02004511 prev = 0; /* not '\' */
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004512 else
4513 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004514 }
4515}
4516
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004517/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4518 * and load them all. There should be exactly heredoc_cnt of them.
4519 */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004520#if BB_MMU
4521#define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
4522 fetch_heredocs(pi, heredoc_cnt, input)
4523#endif
4524static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004525{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004526 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004527 int i;
4528 struct command *cmd = pi->cmds;
4529
Denys Vlasenko3675c372018-07-23 16:31:21 +02004530 debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004531 pi->num_cmds,
Denys Vlasenko3675c372018-07-23 16:31:21 +02004532 cmd->argv ? cmd->argv[0] : "NONE"
4533 );
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004534 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004535 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004536
Denys Vlasenko3675c372018-07-23 16:31:21 +02004537 debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004538 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004539 while (redir) {
4540 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004541 char *p;
4542
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004543 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004544 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenko474cb202018-07-24 13:03:03 +02004545 p = fetch_till_str(as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004546 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004547 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004548 syntax_error("unexpected EOF in here document");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004549 return -1;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004550 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004551 free(redir->rd_filename);
4552 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004553 heredoc_cnt--;
4554 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004555 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004556 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004557 if (cmd->group) {
4558 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4559 heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
4560 //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
4561 if (heredoc_cnt < 0)
4562 return heredoc_cnt; /* error */
4563 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004564 cmd++;
4565 }
4566 pi = pi->next;
4567 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02004568 return heredoc_cnt;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004569}
4570
4571
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004572static int run_list(struct pipe *pi);
4573#if BB_MMU
Denys Vlasenko474cb202018-07-24 13:03:03 +02004574#define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
4575 parse_stream(heredoc_cnt_ptr, input, end_trigger)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004576#endif
4577static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004578 int *heredoc_cnt_ptr,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004579 struct in_str *input,
4580 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004581
Denys Vlasenko474cb202018-07-24 13:03:03 +02004582/* Returns number of heredocs not yet consumed,
4583 * or -1 on error.
4584 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004585static int parse_group(struct parse_context *ctx,
Denys Vlasenko474cb202018-07-24 13:03:03 +02004586 struct in_str *input, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00004587{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004588 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004589 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004590 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004591#if BB_MMU
4592# define as_string NULL
4593#else
4594 char *as_string = NULL;
4595#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004596 struct pipe *pipe_list;
Denys Vlasenko474cb202018-07-24 13:03:03 +02004597 int heredoc_cnt = 0;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004598 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004599 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004600
4601 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004602#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004603 if (ch == '(' && !ctx->word.has_quoted_part) {
4604 if (ctx->word.length)
4605 if (done_word(ctx))
Denys Vlasenko474cb202018-07-24 13:03:03 +02004606 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004607 if (!command->argv)
4608 goto skip; /* (... */
4609 if (command->argv[1]) { /* word word ... (... */
4610 syntax_error_unexpected_ch('(');
Denys Vlasenko474cb202018-07-24 13:03:03 +02004611 return -1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004612 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004613 /* it is "word(..." or "word (..." */
4614 do
4615 ch = i_getch(input);
4616 while (ch == ' ' || ch == '\t');
4617 if (ch != ')') {
4618 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004619 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004620 }
4621 nommu_addchr(&ctx->as_string, ch);
4622 do
4623 ch = i_getch(input);
4624 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004625 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004626 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004627 return -1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004628 }
4629 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004630 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004631 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004632 }
4633#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004634
4635#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004636 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004637 || ctx->word.length /* word{... */
4638 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004639 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004640 syntax_error(NULL);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004641 debug_printf_parse("parse_group return -1: "
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004642 "syntax error, groups and arglists don't mix\n");
Denys Vlasenko474cb202018-07-24 13:03:03 +02004643 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004644 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004645#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004646
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004647 IF_HUSH_FUNCTIONS(skip:)
4648
Denis Vlasenko240c2552009-04-03 03:45:05 +00004649 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004650 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004651 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004652 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4653 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004654 } else {
4655 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004656 ch = i_peek(input);
4657 if (ch != ' ' && ch != '\t' && ch != '\n'
4658 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4659 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004660 syntax_error_unexpected_ch(ch);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004661 return -1;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004662 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004663 if (ch != '(') {
4664 ch = i_getch(input);
4665 nommu_addchr(&ctx->as_string, ch);
4666 }
Eric Andersen25f27032001-04-26 23:22:31 +00004667 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004668
Denys Vlasenko474cb202018-07-24 13:03:03 +02004669 debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
4670 pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
4671 debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004672#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004673 if (as_string)
4674 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004675#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004676
4677 /* empty ()/{} or parse error? */
4678 if (!pipe_list || pipe_list == ERR_PTR) {
4679 /* parse_stream already emitted error msg */
4680 if (!BB_MMU)
4681 free(as_string);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004682 debug_printf_parse("parse_group return -1: "
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004683 "parse_stream returned %p\n", pipe_list);
Denys Vlasenko474cb202018-07-24 13:03:03 +02004684 return -1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004685 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004686#if !BB_MMU
4687 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4688 command->group_as_string = as_string;
4689 debug_printf_parse("end of group, remembering as:'%s'\n",
4690 command->group_as_string);
4691#endif
4692
4693#if ENABLE_HUSH_FUNCTIONS
4694 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4695 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4696 struct command *cmd2;
4697
4698 cmd2 = xzalloc(sizeof(*cmd2));
4699 cmd2->cmd_type = CMD_SUBSHELL;
4700 cmd2->group = pipe_list;
4701# if !BB_MMU
4702//UNTESTED!
4703 cmd2->group_as_string = command->group_as_string;
4704 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4705# endif
4706
4707 pipe_list = new_pipe();
4708 pipe_list->cmds = cmd2;
4709 pipe_list->num_cmds = 1;
4710 }
4711#endif
4712
4713 command->group = pipe_list;
4714
Denys Vlasenko474cb202018-07-24 13:03:03 +02004715 debug_printf_parse("parse_group return %d\n", heredoc_cnt);
4716 return heredoc_cnt;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004717 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004718#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004719}
4720
Denys Vlasenko0b883582016-12-23 16:49:07 +01004721#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004722/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004723/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004724static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004725{
4726 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004727 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004728 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004729 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004730 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004731 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004732 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004733 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004734 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004735 }
4736}
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004737static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
4738{
4739 while (1) {
4740 int ch = i_getch(input);
4741 if (ch == EOF) {
4742 syntax_error_unterm_ch('\'');
4743 return 0;
4744 }
4745 if (ch == '\'')
4746 return 1;
4747 o_addqchr(dest, ch);
4748 }
4749}
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004750/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02004751static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004752static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004753{
4754 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004755 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004756 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004757 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004758 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004759 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004760 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004761 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004762 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004763 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004764 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004765 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004766 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004767 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004768 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4769 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004770 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004771 continue;
4772 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004773 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004774 }
4775}
4776/* Process `cmd` - copy contents until "`" is seen. Complicated by
4777 * \` quoting.
4778 * "Within the backquoted style of command substitution, backslash
4779 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4780 * The search for the matching backquote shall be satisfied by the first
4781 * backquote found without a preceding backslash; during this search,
4782 * if a non-escaped backquote is encountered within a shell comment,
4783 * a here-document, an embedded command substitution of the $(command)
4784 * form, or a quoted string, undefined results occur. A single-quoted
4785 * or double-quoted string that begins, but does not end, within the
4786 * "`...`" sequence produces undefined results."
4787 * Example Output
4788 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4789 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004790static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004791{
4792 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004793 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004794 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004795 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004796 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004797 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4798 ch = i_getch(input);
4799 if (ch != '`'
4800 && ch != '$'
4801 && ch != '\\'
4802 && (!in_dquote || ch != '"')
4803 ) {
4804 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004805 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004806 }
4807 if (ch == EOF) {
4808 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004809 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004810 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004811 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004812 }
4813}
4814/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4815 * quoting and nested ()s.
4816 * "With the $(command) style of command substitution, all characters
4817 * following the open parenthesis to the matching closing parenthesis
4818 * constitute the command. Any valid shell script can be used for command,
4819 * except a script consisting solely of redirections which produces
4820 * unspecified results."
4821 * Example Output
4822 * echo $(echo '(TEST)' BEST) (TEST) BEST
4823 * echo $(echo 'TEST)' BEST) TEST) BEST
4824 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004825 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004826 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004827 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004828 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4829 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004830 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004831#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004832static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004833{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004834 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004835 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004836# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004837 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004838# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004839 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4840
Denys Vlasenko259747c2019-11-28 10:28:14 +01004841# if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004842 G.promptmode = 1; /* PS2 */
Denys Vlasenko259747c2019-11-28 10:28:14 +01004843# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004844 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4845
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004846 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004847 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004848 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004849 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004850 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004851 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004852 if (ch == end_ch
4853# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004854 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004855# endif
4856 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004857 if (!dbl)
4858 break;
4859 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004860 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004861 i_getch(input); /* eat second ')' */
4862 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004863 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004864 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004865 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004866 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004867 if (ch == '(' || ch == '{') {
4868 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004869 if (!add_till_closing_bracket(dest, input, ch))
4870 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004871 o_addchr(dest, ch);
4872 continue;
4873 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004874 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004875 if (!add_till_single_quote(dest, input))
4876 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004877 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004878 continue;
4879 }
4880 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004881 if (!add_till_double_quote(dest, input))
4882 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004883 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004884 continue;
4885 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004886 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004887 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4888 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004889 o_addchr(dest, ch);
4890 continue;
4891 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004892 if (ch == '\\') {
4893 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004894 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004895 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004896 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004897 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004898 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004899# if 0
Denys Vlasenko657086a2016-09-29 18:07:42 +02004900 if (ch == '\n') {
4901 /* "backslash+newline", ignore both */
4902 o_delchr(dest); /* undo insertion of '\' */
4903 continue;
4904 }
Denys Vlasenko259747c2019-11-28 10:28:14 +01004905# endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004906 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004907 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004908 continue;
4909 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004910 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004911 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004912 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004913}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004914#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004915
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004916/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004917#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004918#define parse_dollar(as_string, dest, input, quote_mask) \
4919 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004920#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004921#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004922static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004923 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004924 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004925{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004926 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004927
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004928 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004929 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004930 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004931 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004932 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004933 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004934 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004935 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004936 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004937 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004938 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004939 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004940 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004941 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004942 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004943 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004944 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004945 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004946 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004947 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004948 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004949 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004950 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004951 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004952 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004953 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004954 o_addchr(dest, ch | quote_mask);
4955 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004956 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004957 case '$': /* pid */
4958 case '!': /* last bg pid */
4959 case '?': /* last exit code */
4960 case '#': /* number of args */
4961 case '*': /* args */
4962 case '@': /* args */
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02004963 case '-': /* $- option flags set by set builtin or shell options (-i etc) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004964 goto make_one_char_var;
4965 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004966 char len_single_ch;
4967
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004968 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4969
Denys Vlasenko74369502010-05-21 19:52:01 +02004970 ch = i_getch(input); /* eat '{' */
4971 nommu_addchr(as_string, ch);
4972
Denys Vlasenko46e64982016-09-29 19:50:55 +02004973 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004974 /* It should be ${?}, or ${#var},
4975 * or even ${?+subst} - operator acting on a special variable,
4976 * or the beginning of variable name.
4977 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004978 if (ch == EOF
4979 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4980 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004981 bad_dollar_syntax:
4982 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004983 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4984 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004985 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004986 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004987 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004988 ch |= quote_mask;
4989
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004990 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004991 * However, this regresses some of our testsuite cases
4992 * which check invalid constructs like ${%}.
4993 * Oh well... let's check that the var name part is fine... */
4994
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004995 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004996 unsigned pos;
4997
Denys Vlasenko74369502010-05-21 19:52:01 +02004998 o_addchr(dest, ch);
4999 debug_printf_parse(": '%c'\n", ch);
5000
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005001 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005002 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02005003 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00005004 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00005005
Denys Vlasenko74369502010-05-21 19:52:01 +02005006 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005007 unsigned end_ch;
5008 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005009 /* handle parameter expansions
5010 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5011 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005012 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
5013 if (len_single_ch != '#'
5014 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
5015 || i_peek(input) != '}'
5016 ) {
5017 goto bad_dollar_syntax;
5018 }
5019 /* else: it's "length of C" ${#C} op,
5020 * where C is a single char
5021 * special var name, e.g. ${#!}.
5022 */
5023 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005024 /* Eat everything until closing '}' (or ':') */
5025 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005026 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005027 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005028 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005029 ) {
5030 /* It's ${var:N[:M]} thing */
5031 end_ch = '}' * 0x100 + ':';
5032 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005033 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005034 && ch == '/'
5035 ) {
5036 /* It's ${var/[/]pattern[/repl]} thing */
5037 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
5038 i_getch(input);
5039 nommu_addchr(as_string, '/');
5040 ch = '\\';
5041 }
5042 end_ch = '}' * 0x100 + '/';
5043 }
5044 o_addchr(dest, ch);
Denys Vlasenkoc2aa2182018-08-04 22:25:28 +02005045 /* The pattern can't be empty.
5046 * IOW: if the first char after "${v//" is a slash,
5047 * it does not terminate the pattern - it's the first char of the pattern:
5048 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
5049 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
5050 */
5051 if (i_peek(input) == '/') {
5052 o_addchr(dest, i_getch(input));
5053 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005054 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005055 if (!BB_MMU)
5056 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005057#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005058 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005059 if (last_ch == 0) /* error? */
5060 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005061#else
Denys Vlasenko259747c2019-11-28 10:28:14 +01005062# error Simple code to only allow ${var} is not implemented
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02005063#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005064 if (as_string) {
5065 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005066 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005067 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005068
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005069 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
5070 && (end_ch & 0xff00)
5071 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005072 /* close the first block: */
5073 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005074 /* while parsing N from ${var:N[:M]}
5075 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005076 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005077 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005078 end_ch = '}';
5079 goto again;
5080 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005081 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005082 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02005083 /* it's ${var:N} - emulate :999999999 */
5084 o_addstr(dest, "999999999");
5085 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02005086 }
Denys Vlasenko74369502010-05-21 19:52:01 +02005087 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005088 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005089 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02005090 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005091 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5092 break;
5093 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01005094#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005095 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005096 unsigned pos;
5097
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005098 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005099 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01005100# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02005101 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005102 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005103 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005104 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01005105 o_addchr(dest, quote_mask | '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005106 if (!BB_MMU)
5107 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005108 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
5109 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005110 if (as_string) {
5111 o_addstr(as_string, dest->data + pos);
5112 o_addchr(as_string, ')');
5113 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005114 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005115 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005116 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005117 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005118# endif
5119# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005120 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5121 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005122 if (!BB_MMU)
5123 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005124 if (!add_till_closing_bracket(dest, input, ')'))
5125 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005126 if (as_string) {
5127 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01005128 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005129 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005130 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005131# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005132 break;
5133 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005134#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005135 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005136 goto make_var;
5137#if 0
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02005138 /* TODO: $_: */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005139 /* $_ Shell or shell script name; or last argument of last command
5140 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5141 * but in command's env, set to full pathname used to invoke it */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005142 ch = i_getch(input);
5143 nommu_addchr(as_string, ch);
5144 ch = i_peek_and_eat_bkslash_nl(input);
5145 if (isalnum(ch)) { /* it's $_name or $_123 */
5146 ch = '_';
5147 goto make_var1;
5148 }
5149 /* else: it's $_ */
5150#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005151 default:
5152 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005153 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005154 debug_printf_parse("parse_dollar return 1 (ok)\n");
5155 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005156#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00005157}
5158
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005159#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02005160#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005161 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005162#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005163#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005164static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005165 o_string *dest,
5166 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005167 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005168{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005169 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005170 int next;
5171
5172 again:
5173 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005174 if (ch != EOF)
5175 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005176 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005177 debug_printf_parse("encode_string return 1 (ok)\n");
5178 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005179 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005180 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005181 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005182 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005183 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005184 }
5185 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005186 if (ch != '\n') {
5187 next = i_peek(input);
5188 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005189 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005190 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02005191 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005192 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02005193 /* Testcase: in interactive shell a file with
5194 * echo "unterminated string\<eof>
5195 * is sourced.
5196 */
5197 syntax_error_unterm_ch('"');
5198 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005199 }
5200 /* bash:
5201 * "The backslash retains its special meaning [in "..."]
5202 * only when followed by one of the following characters:
5203 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005204 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005205 * NB: in (unquoted) heredoc, above does not apply to ",
5206 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005207 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005208 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005209 ch = i_getch(input); /* eat next */
5210 if (ch == '\n')
5211 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005212 } /* else: ch remains == '\\', and we double it below: */
5213 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02005214 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005215 goto again;
5216 }
5217 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005218 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
5219 debug_printf_parse("encode_string return 0: "
5220 "parse_dollar returned 0 (error)\n");
5221 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005222 }
5223 goto again;
5224 }
5225#if ENABLE_HUSH_TICK
5226 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005227 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005228 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5229 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005230 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
5231 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005232 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5233 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005234 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005235 }
5236#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005237 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005238 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02005239#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005240}
5241
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005242/*
5243 * Scan input until EOF or end_trigger char.
5244 * Return a list of pipes to execute, or NULL on EOF
5245 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005246 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005247 * reset parsing machinery and start parsing anew,
5248 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005249 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005250static struct pipe *parse_stream(char **pstring,
Denys Vlasenko474cb202018-07-24 13:03:03 +02005251 int *heredoc_cnt_ptr,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005252 struct in_str *input,
5253 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005254{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005255 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005256 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005257
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005258 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005259 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005260 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005261 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005262 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005263 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005264
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005265 initialize_context(&ctx);
5266
5267 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5268 * Preventing this:
5269 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005270 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005271
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005272 /* We used to separate words on $IFS here. This was wrong.
5273 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005274 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005275 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005276
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005277 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005278 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005279 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005280 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005281 int ch;
5282 int next;
5283 int redir_fd;
5284 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005285
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005286 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005287 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005288 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005289 if (ch == EOF) {
5290 struct pipe *pi;
Denys Vlasenko18bcaf32020-12-23 23:01:18 +01005291
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005292 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005293 syntax_error_unterm_str("here document");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005294 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005295 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005296 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005297 syntax_error_unterm_ch('(');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005298 goto parse_error_exitcode1;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005299 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005300 if (end_trigger == '}') {
5301 syntax_error_unterm_ch('{');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005302 goto parse_error_exitcode1;
Denys Vlasenko42246472016-11-07 16:22:35 +01005303 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005304
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005305 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005306 goto parse_error_exitcode1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005307 }
Denys Vlasenko18567402018-07-20 17:51:31 +02005308 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005309 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005310 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005311 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005312 /* (this makes bare "&" cmd a no-op.
5313 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005314 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005315 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005316 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005317 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005318 pi = NULL;
5319 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005320#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005321 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005322 if (pstring)
5323 *pstring = ctx.as_string.data;
5324 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005325 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005326#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005327 // heredoc_cnt must be 0 here anyway
5328 //if (heredoc_cnt_ptr)
5329 // *heredoc_cnt_ptr = heredoc_cnt;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005330 debug_leave();
Denys Vlasenko474cb202018-07-24 13:03:03 +02005331 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005332 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005333 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005334 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005335
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005336 /* Handle "'" and "\" first, as they won't play nice with
5337 * i_peek_and_eat_bkslash_nl() anyway:
5338 * echo z\\
5339 * and
5340 * echo '\
5341 * '
5342 * would break.
5343 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005344 if (ch == '\\') {
5345 ch = i_getch(input);
5346 if (ch == '\n')
5347 continue; /* drop \<newline>, get next char */
5348 nommu_addchr(&ctx.as_string, '\\');
5349 o_addchr(&ctx.word, '\\');
5350 if (ch == EOF) {
5351 /* Testcase: eval 'echo Ok\' */
5352 /* bash-4.3.43 was removing backslash,
5353 * but 4.4.19 retains it, most other shells too
5354 */
5355 continue; /* get next char */
5356 }
5357 /* Example: echo Hello \2>file
5358 * we need to know that word 2 is quoted
5359 */
5360 ctx.word.has_quoted_part = 1;
5361 nommu_addchr(&ctx.as_string, ch);
5362 o_addchr(&ctx.word, ch);
5363 continue; /* get next char */
5364 }
5365 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005366 if (ch == '\'') {
5367 ctx.word.has_quoted_part = 1;
5368 next = i_getch(input);
5369 if (next == '\'' && !ctx.pending_redirect)
5370 goto insert_empty_quoted_str_marker;
5371
5372 ch = next;
5373 while (1) {
5374 if (ch == EOF) {
5375 syntax_error_unterm_ch('\'');
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005376 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005377 }
5378 nommu_addchr(&ctx.as_string, ch);
5379 if (ch == '\'')
5380 break;
5381 if (ch == SPECIAL_VAR_SYMBOL) {
5382 /* Convert raw ^C to corresponding special variable reference */
5383 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5384 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5385 }
5386 o_addqchr(&ctx.word, ch);
5387 ch = i_getch(input);
5388 }
5389 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005390 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005391
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005392 next = '\0';
5393 if (ch != '\n')
5394 next = i_peek_and_eat_bkslash_nl(input);
5395
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005396 is_special = "{}<>&|();#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005397 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005398 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod2241f52020-10-31 03:34:07 +01005399#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
5400 if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
5401 /* In [[ ]], {}<>&|() are not special */
5402 is_special += 8;
5403 } else
5404#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005405 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005406 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005407 || ctx.word.length /* word{... - non-special */
5408 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005409 || (next != ';' /* }; - special */
5410 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005411 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005412 && next != '&' /* }& and }&& ... - special */
5413 && next != '|' /* }|| ... - special */
5414 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005415 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005416 ) {
5417 /* They are not special, skip "{}" */
5418 is_special += 2;
5419 }
5420 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005421 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005422
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005423 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005424 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005425 o_addQchr(&ctx.word, ch);
5426 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5427 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005428 && ch == '='
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02005429 && endofname(ctx.word.data)[0] == '='
Denis Vlasenko55789c62008-06-18 16:30:42 +00005430 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005431 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5432 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005433 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005434 continue;
5435 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005436
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005437 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005438#if ENABLE_HUSH_LINENO_VAR
5439/* Case:
5440 * "while ...; do<whitespace><newline>
5441 * cmd ..."
5442 * would think that "cmd" starts in <whitespace> -
5443 * i.e., at the previous line.
5444 * We need to skip all whitespace before newlines.
5445 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005446 while (ch != '\n') {
5447 next = i_peek(input);
5448 if (next != ' ' && next != '\t' && next != '\n')
5449 break; /* next char is not ws */
5450 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005451 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005452 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005453#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005454 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005455 goto parse_error_exitcode1;
Eric Andersenaac75e52001-04-30 18:18:45 +00005456 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005457 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005458 /* Is this a case when newline is simply ignored?
5459 * Some examples:
5460 * "cmd | <newline> cmd ..."
5461 * "case ... in <newline> word) ..."
5462 */
5463 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko3675c372018-07-23 16:31:21 +02005464 && ctx.word.length == 0
5465 && !ctx.word.has_quoted_part
5466 && heredoc_cnt == 0
Denis Vlasenkof1736072008-07-31 10:09:26 +00005467 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005468 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005469 * Without check #1, interactive shell
5470 * ignores even bare <newline>,
5471 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005472 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005473 * ps2> _ <=== wrong, should be ps1
5474 * Without check #2, "cmd & <newline>"
5475 * is similarly mistreated.
5476 * (BTW, this makes "cmd & cmd"
5477 * and "cmd && cmd" non-orthogonal.
5478 * Really, ask yourself, why
5479 * "cmd && <newline>" doesn't start
5480 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005481 * The only reason is that it might be
5482 * a "cmd1 && <nl> cmd2 &" construct,
5483 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005484 */
5485 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005486 if (pi->num_cmds != 0 /* check #1 */
5487 && pi->followup != PIPE_BG /* check #2 */
5488 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005489 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005490 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005491 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005492 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005493 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko3675c372018-07-23 16:31:21 +02005494 debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005495 if (heredoc_cnt) {
Denys Vlasenko474cb202018-07-24 13:03:03 +02005496 heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
5497 if (heredoc_cnt != 0)
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005498 goto parse_error_exitcode1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005499 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005500 ctx.is_assignment = MAYBE_ASSIGNMENT;
5501 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005502 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005503 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005504 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005505 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005506 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005507
5508 /* "cmd}" or "cmd }..." without semicolon or &:
5509 * } is an ordinary char in this case, even inside { cmd; }
5510 * Pathological example: { ""}; } should exec "}" cmd
5511 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005512 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005513 if (ctx.word.length != 0 /* word} */
5514 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005515 ) {
5516 goto ordinary_char;
5517 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005518 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5519 /* Generally, there should be semicolon: "cmd; }"
5520 * However, bash allows to omit it if "cmd" is
5521 * a group. Examples:
5522 * { { echo 1; } }
5523 * {(echo 1)}
5524 * { echo 0 >&2 | { echo 1; } }
5525 * { while false; do :; done }
5526 * { case a in b) ;; esac }
5527 */
5528 if (ctx.command->group)
5529 goto term_group;
5530 goto ordinary_char;
5531 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005532 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005533 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005534 goto skip_end_trigger;
5535 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005536 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005537 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005538 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005539 && (ch != ';' || heredoc_cnt == 0)
5540#if ENABLE_HUSH_CASE
5541 && (ch != ')'
5542 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005543 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005544 )
5545#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005546 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005547 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005548 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005549 }
5550 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005551 ctx.is_assignment = MAYBE_ASSIGNMENT;
5552 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005553 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005554 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005555 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005556 ) {
Denys Vlasenko18567402018-07-20 17:51:31 +02005557 o_free_and_set_NULL(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005558#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005559 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005560 if (pstring)
5561 *pstring = ctx.as_string.data;
5562 else
Denys Vlasenko18567402018-07-20 17:51:31 +02005563 o_free(&ctx.as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005564#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005565 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5566 /* Example: bare "{ }", "()" */
5567 G.last_exitcode = 2; /* bash compat */
5568 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005569 goto parse_error;
Denys Vlasenko39701202017-08-02 19:44:05 +02005570 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005571 if (heredoc_cnt_ptr)
5572 *heredoc_cnt_ptr = heredoc_cnt;
5573 debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005574 debug_printf_parse("parse_stream return %p: "
5575 "end_trigger char found\n",
5576 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005577 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005578 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005579 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005580 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005581
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005582 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005583 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005584
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005585 /* Catch <, > before deciding whether this word is
5586 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5587 switch (ch) {
5588 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005589 redir_fd = redirect_opt_num(&ctx.word);
5590 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005591 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005592 }
5593 redir_style = REDIRECT_OVERWRITE;
5594 if (next == '>') {
5595 redir_style = REDIRECT_APPEND;
5596 ch = i_getch(input);
5597 nommu_addchr(&ctx.as_string, ch);
5598 }
5599#if 0
5600 else if (next == '(') {
5601 syntax_error(">(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005602 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005603 }
5604#endif
5605 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005606 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005607 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005608 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005609 redir_fd = redirect_opt_num(&ctx.word);
5610 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005611 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005612 }
5613 redir_style = REDIRECT_INPUT;
5614 if (next == '<') {
5615 redir_style = REDIRECT_HEREDOC;
5616 heredoc_cnt++;
Denys Vlasenko3675c372018-07-23 16:31:21 +02005617 debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005618 ch = i_getch(input);
5619 nommu_addchr(&ctx.as_string, ch);
5620 } else if (next == '>') {
5621 redir_style = REDIRECT_IO;
5622 ch = i_getch(input);
5623 nommu_addchr(&ctx.as_string, ch);
5624 }
5625#if 0
5626 else if (next == '(') {
5627 syntax_error("<(process) not supported");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005628 goto parse_error_exitcode1;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005629 }
5630#endif
5631 if (parse_redirect(&ctx, redir_fd, redir_style, input))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005632 goto parse_error_exitcode1;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005633 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005634 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005635 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005636 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005637 /* note: we do not add it to &ctx.as_string */
5638/* TODO: in bash:
5639 * comment inside $() goes to the next \n, even inside quoted string (!):
5640 * cmd "$(cmd2 #comment)" - syntax error
5641 * cmd "`cmd2 #comment`" - ok
5642 * We accept both (comment ends where command subst ends, in both cases).
5643 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005644 while (1) {
5645 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005646 if (ch == '\n') {
5647 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005648 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005649 }
5650 ch = i_getch(input);
5651 if (ch == EOF)
5652 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005653 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005654 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005655 }
5656 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005657 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005658 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005659
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005660 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005661 /* check that we are not in word in "a=1 2>word b=1": */
5662 && !ctx.pending_redirect
5663 ) {
5664 /* ch is a special char and thus this word
5665 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005666 ctx.is_assignment = NOT_ASSIGNMENT;
5667 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005668 }
5669
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005670 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5671
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005672 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005673 case SPECIAL_VAR_SYMBOL:
5674 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005675 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5676 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005677 /* fall through */
5678 case '#':
5679 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005680 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005681 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005682 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005683 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005684 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005685 "parse_dollar returned 0 (error)\n");
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005686 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005687 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005688 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005689 case '"':
5690 ctx.word.has_quoted_part = 1;
5691 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005692 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005693 insert_empty_quoted_str_marker:
5694 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005695 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5696 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005697 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005698 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005699 if (ctx.is_assignment == NOT_ASSIGNMENT)
5700 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005701 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005702 goto parse_error_exitcode1;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005703 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005704 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005705#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005706 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005707 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005708
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005709 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5710 o_addchr(&ctx.word, '`');
5711 USE_FOR_NOMMU(pos = ctx.word.length;)
5712 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005713 goto parse_error_exitcode1;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005714# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005715 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005716 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005717# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005718 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5719 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005720 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005721 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005722#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005723 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005724#if ENABLE_HUSH_CASE
5725 case_semi:
5726#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005727 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005728 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005729 }
5730 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005731#if ENABLE_HUSH_CASE
5732 /* Eat multiple semicolons, detect
5733 * whether it means something special */
5734 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005735 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005736 if (ch != ';')
5737 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005738 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005739 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005740 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005741 ctx.ctx_dsemicolon = 1;
5742 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005743 break;
5744 }
5745 }
5746#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005747 new_cmd:
5748 /* We just finished a cmd. New one may start
5749 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005750 ctx.is_assignment = MAYBE_ASSIGNMENT;
5751 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005752 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005753 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005754 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005755 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005756 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005757 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005758 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005759 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005760 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005761 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005762 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005763 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005764 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005765 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005766 if (done_word(&ctx)) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005767 goto parse_error_exitcode1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005768 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005769#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005770 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005771 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005772#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005773 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005774 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005775 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005776 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005777 } else {
5778 /* we could pick up a file descriptor choice here
5779 * with redirect_opt_num(), but bash doesn't do it.
5780 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005781 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005782 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005783 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005784 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005785#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005786 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005787 if (ctx.ctx_res_w == RES_MATCH
5788 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005789 && ctx.word.length == 0 /* not word(... */
5790 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005791 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005792 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005793 }
5794#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005795 /* fall through */
5796 case '{': {
5797 int n = parse_group(&ctx, input, ch);
5798 if (n < 0) {
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005799 goto parse_error_exitcode1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005800 }
Denys Vlasenko474cb202018-07-24 13:03:03 +02005801 debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
5802 heredoc_cnt += n;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005803 goto new_cmd;
Denys Vlasenko474cb202018-07-24 13:03:03 +02005804 }
Eric Andersen25f27032001-04-26 23:22:31 +00005805 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005806#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005807 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005808 goto case_semi;
5809#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02005810
Eric Andersen25f27032001-04-26 23:22:31 +00005811 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005812 /* proper use of this character is caught by end_trigger:
5813 * if we see {, we call parse_group(..., end_trigger='}')
5814 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005815 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005816 syntax_error_unexpected_ch(ch);
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005817 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005818 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005819 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005820 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005821 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005822 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005823
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005824 parse_error_exitcode1:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005825 G.last_exitcode = 1;
Denys Vlasenkodc9c10a2020-11-16 13:00:44 +01005826 parse_error:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005827 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005828 struct parse_context *pctx;
5829 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005830
5831 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005832 * Sample for finding leaks on syntax error recovery path.
5833 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005834 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005835 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005836 * while if (true | { true;}); then echo ok; fi; do break; done
5837 * 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 +00005838 */
5839 pctx = &ctx;
5840 do {
5841 /* Update pipe/command counts,
5842 * otherwise freeing may miss some */
5843 done_pipe(pctx, PIPE_SEQ);
5844 debug_printf_clean("freeing list %p from ctx %p\n",
5845 pctx->list_head, pctx);
5846 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005847 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005848 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005849#if !BB_MMU
Denys Vlasenko18567402018-07-20 17:51:31 +02005850 o_free(&pctx->as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005851#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005852 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005853 if (pctx != &ctx) {
5854 free(pctx);
5855 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005856 IF_HAS_KEYWORDS(pctx = p2;)
5857 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005858
Denys Vlasenko474cb202018-07-24 13:03:03 +02005859 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005860#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005861 if (pstring)
5862 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005863#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005864 debug_leave();
5865 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005866 }
Eric Andersen25f27032001-04-26 23:22:31 +00005867}
5868
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005869
5870/*** Execution routines ***/
5871
5872/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005873#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005874#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005875 expand_string_to_string(str)
5876#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005877static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005878#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005879static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005880#endif
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02005881static int expand_vars_to_list(o_string *output, int n, char *arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005882
5883/* expand_strvec_to_strvec() takes a list of strings, expands
5884 * all variable references within and returns a pointer to
5885 * a list of expanded strings, possibly with larger number
5886 * of strings. (Think VAR="a b"; echo $VAR).
5887 * This new list is allocated as a single malloc block.
5888 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005889 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005890 * Caller can deallocate entire list by single free(list). */
5891
Denys Vlasenko238081f2010-10-03 14:26:26 +02005892/* A horde of its helpers come first: */
5893
5894static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5895{
5896 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005897 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005898
Denys Vlasenko9e800222010-10-03 14:28:04 +02005899#if ENABLE_HUSH_BRACE_EXPANSION
5900 if (c == '{' || c == '}') {
5901 /* { -> \{, } -> \} */
5902 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005903 /* And now we want to add { or } and continue:
5904 * o_addchr(o, c);
5905 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005906 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005907 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005908 }
5909#endif
5910 o_addchr(o, c);
5911 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005912 /* \z -> \\\z; \<eol> -> \\<eol> */
5913 o_addchr(o, '\\');
5914 if (len) {
5915 len--;
5916 o_addchr(o, '\\');
5917 o_addchr(o, *str++);
5918 }
5919 }
5920 }
5921}
5922
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005923/* Store given string, finalizing the word and starting new one whenever
5924 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005925 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005926 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005927 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5928 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005929static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005930{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005931 int last_is_ifs = 0;
5932
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005933 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005934 int word_len;
5935
5936 if (!*str) /* EOL - do not finalize word */
5937 break;
5938 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005939 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005940 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005941 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005942 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005943 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005944 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005945 * Example: "v='\*'; echo b$v" prints "b\*"
5946 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005947 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005948 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005949 /*/ Why can't we do it easier? */
5950 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5951 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5952 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005953 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005954 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005955 if (!*str) /* EOL - do not finalize word */
5956 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005957 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005958
5959 /* We know str here points to at least one IFS char */
5960 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005961 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005962 if (!*str) /* EOL - do not finalize word */
5963 break;
5964
Denys Vlasenko96786362018-04-11 16:02:58 +02005965 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5966 && strchr(G.ifs, *str) /* the second check would fail */
5967 ) {
5968 /* This is a non-whitespace $IFS char */
5969 /* Skip it and IFS whitespace chars, start new word */
5970 str++;
5971 str += strspn(str, G.ifs_whitespace);
5972 goto new_word;
5973 }
5974
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005975 /* Start new word... but not always! */
5976 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005977 if (output->has_quoted_part
Denys Vlasenko186cf492018-07-27 12:14:39 +02005978 /*
5979 * Case "v=' a'; echo $v":
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005980 * here nothing precedes the space in $v expansion,
5981 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005982 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko186cf492018-07-27 12:14:39 +02005983 * It's okay if this accesses the byte before first argv[]:
5984 * past call to o_save_ptr() cleared it to zero byte
5985 * (grep for -prev-ifs-check-).
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005986 */
Denys Vlasenko186cf492018-07-27 12:14:39 +02005987 || output->data[output->length - 1]
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005988 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005989 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005990 o_addchr(output, '\0');
5991 debug_print_list("expand_on_ifs", output, n);
5992 n = o_save_ptr(output, n);
5993 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005994 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005995
Denys Vlasenko168579a2018-07-19 13:45:54 +02005996 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005997 debug_print_list("expand_on_ifs[1]", output, n);
5998 return n;
5999}
6000
6001/* Helper to expand $((...)) and heredoc body. These act as if
6002 * they are in double quotes, with the exception that they are not :).
6003 * Just the rules are similar: "expand only $var and `cmd`"
6004 *
6005 * Returns malloced string.
6006 * As an optimization, we return NULL if expansion is not needed.
6007 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006008static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006009{
6010 char *exp_str;
6011 struct in_str input;
6012 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006013 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006014
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006015 cp = str;
6016 for (;;) {
6017 if (!*cp) return NULL; /* string has no special chars */
6018 if (*cp == '$') break;
6019 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006020#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006021 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006022#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02006023 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006024 }
6025
6026 /* We need to expand. Example:
6027 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
6028 */
6029 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006030 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01006031//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006032 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02006033 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02006034 EXP_FLAG_ESC_GLOB_CHARS,
6035 /*unbackslash:*/ 1
6036 );
6037 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006038 o_free(&dest);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006039 return exp_str;
6040}
6041
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006042static const char *first_special_char_in_vararg(const char *cp)
6043{
6044 for (;;) {
6045 if (!*cp) return NULL; /* string has no special chars */
6046 if (*cp == '$') return cp;
6047 if (*cp == '\\') return cp;
6048 if (*cp == '\'') return cp;
6049 if (*cp == '"') return cp;
6050#if ENABLE_HUSH_TICK
6051 if (*cp == '`') return cp;
6052#endif
6053 /* dquoted "${x:+ARG}" should not glob, therefore
6054 * '*' et al require some non-literal processing: */
6055 if (*cp == '*') return cp;
6056 if (*cp == '?') return cp;
6057 if (*cp == '[') return cp;
6058 cp++;
6059 }
6060}
6061
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006062/* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
6063 * These can contain single- and double-quoted strings,
6064 * and treated as if the ARG string is initially unquoted. IOW:
6065 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
6066 * a dquoted string: "${var#"zz"}"), the difference only comes later
6067 * (word splitting and globbing of the ${var...} result).
6068 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006069#if !BASH_PATTERN_SUBST
6070#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
6071 encode_then_expand_vararg(str, handle_squotes)
6072#endif
6073static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
6074{
Denys Vlasenko3d27d432018-12-27 18:03:20 +01006075#if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
Denys Vlasenkob762c782018-07-17 14:21:38 +02006076 const int do_unbackslash = 0;
6077#endif
6078 char *exp_str;
6079 struct in_str input;
6080 o_string dest = NULL_O_STRING;
6081
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006082 if (!first_special_char_in_vararg(str)) {
6083 /* string has no special chars */
6084 return NULL;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006085 }
6086
Denys Vlasenkob762c782018-07-17 14:21:38 +02006087 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02006088 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006089 exp_str = NULL;
6090
6091 for (;;) {
6092 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006093
6094 ch = i_getch(&input);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006095 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
6096 __func__, ch, ch, !!dest.o_expflags);
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006097
6098 if (!dest.o_expflags) {
6099 if (ch == EOF)
6100 break;
6101 if (handle_squotes && ch == '\'') {
6102 if (!add_till_single_quote_dquoted(&dest, &input))
Denys Vlasenkob762c782018-07-17 14:21:38 +02006103 goto ret; /* error */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006104 continue;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006105 }
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006106 }
6107 if (ch == EOF) {
6108 syntax_error_unterm_ch('"');
6109 goto ret; /* error */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006110 }
6111 if (ch == '"') {
6112 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
6113 continue;
6114 }
6115 if (ch == '\\') {
6116 ch = i_getch(&input);
6117 if (ch == EOF) {
6118//example? error message? syntax_error_unterm_ch('"');
6119 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6120 goto ret;
6121 }
6122 o_addqchr(&dest, ch);
6123 continue;
6124 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02006125 if (ch == '$') {
6126 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
6127 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6128 goto ret;
6129 }
6130 continue;
6131 }
6132#if ENABLE_HUSH_TICK
6133 if (ch == '`') {
6134 //unsigned pos = dest->length;
6135 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6136 o_addchr(&dest, 0x80 | '`');
6137 if (!add_till_backquote(&dest, &input,
6138 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6139 )
6140 ) {
6141 goto ret; /* error */
6142 }
6143 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6144 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6145 continue;
6146 }
6147#endif
6148 o_addQchr(&dest, ch);
6149 } /* for (;;) */
6150
6151 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
6152 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02006153 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
6154 do_unbackslash
6155 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02006156 ret:
6157 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenko18567402018-07-20 17:51:31 +02006158 o_free(&dest);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006159 return exp_str;
6160}
6161
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006162/* Expanding ARG in ${var+ARG}, ${var-ARG}
6163 */
Denys Vlasenko294eb462018-07-20 16:18:59 +02006164static int encode_then_append_var_plusminus(o_string *output, int n,
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006165 char *str, int dquoted)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006166{
6167 struct in_str input;
6168 o_string dest = NULL_O_STRING;
6169
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006170 if (!first_special_char_in_vararg(str)
6171 && '\0' == str[strcspn(str, G.ifs)]
6172 ) {
6173 /* string has no special chars
6174 * && string has no $IFS chars
6175 */
Denys Vlasenko9e0adb92019-05-15 13:39:19 +02006176 if (dquoted) {
6177 /* Prints 1 (quoted expansion is a "" word, not nothing):
6178 * set -- "${notexist-}"; echo $#
6179 */
6180 output->has_quoted_part = 1;
6181 }
Denys Vlasenko54fdabd2018-07-31 10:36:29 +02006182 return expand_vars_to_list(output, n, str);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006183 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006184
Denys Vlasenko294eb462018-07-20 16:18:59 +02006185 setup_string_in_str(&input, str);
6186
6187 for (;;) {
6188 int ch;
6189
6190 ch = i_getch(&input);
6191 debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
6192 __func__, ch, ch, dest.o_expflags);
6193
6194 if (!dest.o_expflags) {
6195 if (ch == EOF)
6196 break;
6197 if (!dquoted && strchr(G.ifs, ch)) {
6198 /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
6199 * do not assume we are at the start of the word (PREFIX above).
6200 */
6201 if (dest.data) {
6202 n = expand_vars_to_list(output, n, dest.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006203 o_free_and_set_NULL(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006204 o_addchr(output, '\0');
6205 n = o_save_ptr(output, n); /* create next word */
6206 } else
6207 if (output->length != o_get_last_ptr(output, n)
6208 || output->has_quoted_part
6209 ) {
6210 /* For these cases:
6211 * f() { for i; do echo "|$i|"; done; }; x=x
6212 * f a${x:+ }b # 1st condition
6213 * |a|
6214 * |b|
6215 * f ""${x:+ }b # 2nd condition
6216 * ||
6217 * |b|
6218 */
6219 o_addchr(output, '\0');
6220 n = o_save_ptr(output, n); /* create next word */
6221 }
6222 continue;
6223 }
6224 if (!dquoted && ch == '\'') {
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006225 if (!add_till_single_quote_dquoted(&dest, &input))
6226 goto ret; /* error */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006227 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6228 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006229 continue;
6230 }
6231 }
6232 if (ch == EOF) {
6233 syntax_error_unterm_ch('"');
6234 goto ret; /* error */
6235 }
6236 if (ch == '"') {
6237 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006238 if (dest.o_expflags) {
6239 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6240 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6241 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006242 continue;
6243 }
6244 if (ch == '\\') {
6245 ch = i_getch(&input);
6246 if (ch == EOF) {
6247//example? error message? syntax_error_unterm_ch('"');
6248 debug_printf_parse("%s: error: \\<eof>\n", __func__);
6249 goto ret;
6250 }
6251 o_addqchr(&dest, ch);
6252 continue;
6253 }
6254 if (ch == '$') {
6255 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
6256 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
6257 goto ret;
6258 }
6259 continue;
6260 }
6261#if ENABLE_HUSH_TICK
6262 if (ch == '`') {
6263 //unsigned pos = dest->length;
6264 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6265 o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
6266 if (!add_till_backquote(&dest, &input,
6267 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
6268 )
6269 ) {
6270 goto ret; /* error */
6271 }
6272 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6273 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6274 continue;
6275 }
6276#endif
Denys Vlasenkof36caa42018-07-20 19:29:41 +02006277 if (dquoted) {
6278 /* Always glob-protect if in dquotes:
6279 * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
6280 * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
6281 */
6282 o_addqchr(&dest, ch);
6283 } else {
6284 /* Glob-protect only if char is quoted:
6285 * x=x; echo ${x:+/bin/c*} - prints many filenames
6286 * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
6287 */
6288 o_addQchr(&dest, ch);
6289 }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006290 } /* for (;;) */
6291
6292 if (dest.data) {
6293 n = expand_vars_to_list(output, n, dest.data);
6294 }
6295 ret:
Denys Vlasenko18567402018-07-20 17:51:31 +02006296 o_free(&dest);
Denys Vlasenko294eb462018-07-20 16:18:59 +02006297 return n;
6298}
6299
Denys Vlasenko0b883582016-12-23 16:49:07 +01006300#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02006301static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006302{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006303 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006304 arith_t res;
6305 char *exp_str;
6306
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006307 math_state.lookupvar = get_local_var_value;
6308 math_state.setvar = set_local_var_from_halves;
6309 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006310 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02006311 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006312 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006313 if (errmsg_p)
6314 *errmsg_p = math_state.errmsg;
6315 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02006316 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006317 return res;
6318}
6319#endif
6320
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006321#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006322/* ${var/[/]pattern[/repl]} helpers */
6323static char *strstr_pattern(char *val, const char *pattern, int *size)
6324{
6325 while (1) {
6326 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
6327 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
6328 if (end) {
6329 *size = end - val;
6330 return val;
6331 }
6332 if (*val == '\0')
6333 return NULL;
6334 /* Optimization: if "*pat" did not match the start of "string",
6335 * we know that "tring", "ring" etc will not match too:
6336 */
6337 if (pattern[0] == '*')
6338 return NULL;
6339 val++;
6340 }
6341}
6342static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
6343{
6344 char *result = NULL;
6345 unsigned res_len = 0;
6346 unsigned repl_len = strlen(repl);
6347
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006348 /* Null pattern never matches, including if "var" is empty */
6349 if (!pattern[0])
6350 return result; /* NULL, no replaces happened */
6351
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006352 while (1) {
6353 int size;
6354 char *s = strstr_pattern(val, pattern, &size);
6355 if (!s)
6356 break;
6357
6358 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02006359 strcpy(mempcpy(result + res_len, val, s - val), repl);
6360 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006361 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
6362
6363 val = s + size;
6364 if (exp_op == '/')
6365 break;
6366 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02006367 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006368 result = xrealloc(result, res_len + strlen(val) + 1);
6369 strcpy(result + res_len, val);
6370 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
6371 }
6372 debug_printf_varexp("result:'%s'\n", result);
6373 return result;
6374}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006375#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006376
Denys Vlasenko168579a2018-07-19 13:45:54 +02006377static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006378 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006379{
6380 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6381 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6382 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6383 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02006384 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006385 } else { /* quoted "$VAR" */
6386 output->has_quoted_part = 1;
6387 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6388 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6389 if (val && val[0])
6390 o_addQstr(output, val);
6391 }
6392 return n;
6393}
6394
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006395/* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006396 */
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006397static NOINLINE int expand_one_var(o_string *output, int n,
6398 int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006399{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006400 const char *val;
6401 char *to_be_freed;
6402 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006403 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006404 char exp_op;
6405 char exp_save = exp_save; /* for compiler */
6406 char *exp_saveptr; /* points to expansion operator */
6407 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006408 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006409
Denys Vlasenko0ca31982018-01-25 13:20:50 +01006410 val = NULL;
6411 to_be_freed = NULL;
6412 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006413 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006414 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006415 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006416 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02006417 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006418 exp_op = 0;
6419
Denys Vlasenkob762c782018-07-17 14:21:38 +02006420 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02006421 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
6422 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6423 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006424 ) {
6425 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006426 var++;
6427 exp_op = 'L';
6428 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006429 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006430 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006431 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006432 ) {
6433 /* ${?:0}, ${#[:]%0} etc */
6434 exp_saveptr = var + 1;
6435 } else {
6436 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6437 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6438 }
6439 exp_op = exp_save = *exp_saveptr;
6440 if (exp_op) {
6441 exp_word = exp_saveptr + 1;
6442 if (exp_op == ':') {
6443 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006444//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006445 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006446 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006447 ) {
6448 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6449 exp_op = ':';
6450 exp_word--;
6451 }
6452 }
6453 *exp_saveptr = '\0';
6454 } /* else: it's not an expansion op, but bare ${var} */
6455 }
6456
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006457 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006458 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006459 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006460 int nn = xatoi_positive(var);
6461 if (nn < G.global_argc)
6462 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006463 /* else val remains NULL: $N with too big N */
6464 } else {
6465 switch (var[0]) {
6466 case '$': /* pid */
6467 val = utoa(G.root_pid);
6468 break;
6469 case '!': /* bg pid */
6470 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6471 break;
6472 case '?': /* exitcode */
6473 val = utoa(G.last_exitcode);
6474 break;
6475 case '#': /* argc */
6476 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6477 break;
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006478 case '-': { /* active options */
6479 /* Check set_mode() to see what option chars we support */
6480 char *cp;
6481 val = cp = G.optstring_buf;
6482 if (G.o_opt[OPT_O_ERREXIT])
6483 *cp++ = 'e';
6484 if (G_interactive_fd)
6485 *cp++ = 'i';
6486 if (G_x_mode)
6487 *cp++ = 'x';
6488 /* If G.o_opt[OPT_O_NOEXEC] is true,
6489 * commands read but are not executed,
6490 * so $- can not execute too, 'n' is never seen in $-.
6491 */
Denys Vlasenkof3634582019-06-03 12:21:04 +02006492 if (G.opt_c)
6493 *cp++ = 'c';
Denys Vlasenkod8740b22019-05-19 19:11:21 +02006494 if (G.opt_s)
6495 *cp++ = 's';
Denys Vlasenkoef8985c2019-05-19 16:29:09 +02006496 *cp = '\0';
6497 break;
6498 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006499 default:
6500 val = get_local_var_value(var);
6501 }
6502 }
6503
6504 /* Handle any expansions */
6505 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006506 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006507 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006508 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006509 debug_printf_expand("%s\n", val);
6510 } else if (exp_op) {
6511 if (exp_op == '%' || exp_op == '#') {
6512 /* Standard-mandated substring removal ops:
6513 * ${parameter%word} - remove smallest suffix pattern
6514 * ${parameter%%word} - remove largest suffix pattern
6515 * ${parameter#word} - remove smallest prefix pattern
6516 * ${parameter##word} - remove largest prefix pattern
6517 *
6518 * Word is expanded to produce a glob pattern.
6519 * Then var's value is matched to it and matching part removed.
6520 */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006521 /* bash compat: if x is "" and no shrinking of it is possible,
6522 * inner ${...} is not evaluated. Example:
6523 * unset b; : ${a%${b=B}}; echo $b
6524 * assignment b=B only happens if $a is not "".
6525 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006526 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006527 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006528 char *exp_exp_word;
6529 char *loc;
6530 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006531 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006532 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006533 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006534 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006535 if (exp_exp_word)
6536 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006537 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6538 /*
6539 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006540 * G.global_argv and results of utoa and get_local_var_value
6541 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006542 * scan_and_match momentarily stores NULs there.
6543 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006544 t = (char*)val;
6545 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006546 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 +02006547 free(exp_exp_word);
6548 if (loc) { /* match was found */
6549 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006550 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006551 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006552 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006553 }
6554 }
6555 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006556#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006557 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006558 /* It's ${var/[/]pattern[/repl]} thing.
6559 * Note that in encoded form it has TWO parts:
6560 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006561 * and if // is used, it is encoded as \:
6562 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006563 */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006564 /* bash compat: if var is "", both pattern and repl
6565 * are still evaluated, if it is unset, then not:
6566 * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
6567 * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
6568 */
6569 if (val /*&& val[0]*/) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006570 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006571 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006572 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006573 * >az >bz
6574 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6575 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6576 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6577 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006578 * (note that a*z _pattern_ is never globbed!)
6579 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006580 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006581 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006582 if (!pattern)
6583 pattern = xstrdup(exp_word);
6584 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6585 *p++ = SPECIAL_VAR_SYMBOL;
6586 exp_word = p;
6587 p = strchr(p, SPECIAL_VAR_SYMBOL);
6588 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006589 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006590 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6591 /* HACK ALERT. We depend here on the fact that
6592 * G.global_argv and results of utoa and get_local_var_value
6593 * are actually in writable memory:
6594 * replace_pattern momentarily stores NULs there. */
6595 t = (char*)val;
6596 to_be_freed = replace_pattern(t,
6597 pattern,
6598 (repl ? repl : exp_word),
6599 exp_op);
6600 if (to_be_freed) /* at least one replace happened */
6601 val = to_be_freed;
6602 free(pattern);
6603 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006604 } else {
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006605 /* Unset variable always gives nothing */
6606 // a=; echo ${a/*/w} # "w"
6607 // unset a; echo ${a/*/w} # ""
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006608 /* Just skip "replace" part */
6609 *p++ = SPECIAL_VAR_SYMBOL;
6610 p = strchr(p, SPECIAL_VAR_SYMBOL);
6611 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006612 }
6613 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006614#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006615 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006616#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006617 /* It's ${var:N[:M]} bashism.
6618 * Note that in encoded form it has TWO parts:
6619 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6620 */
6621 arith_t beg, len;
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006622 unsigned vallen;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006623 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006624
Denys Vlasenko063847d2010-09-15 13:33:02 +02006625 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6626 if (errmsg)
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006627 goto empty_result;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006628 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6629 *p++ = SPECIAL_VAR_SYMBOL;
6630 exp_word = p;
6631 p = strchr(p, SPECIAL_VAR_SYMBOL);
6632 *p = '\0';
Denys Vlasenkoa7b52d22020-12-23 12:38:03 +01006633 vallen = val ? strlen(val) : 0;
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006634 if (beg < 0) {
6635 /* negative beg counts from the end */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006636 beg = (arith_t)vallen + beg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006637 }
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006638 /* If expansion will be empty, do not even evaluate len */
6639 if (!val || beg < 0 || beg > vallen) {
6640 /* Why > vallen, not >=? bash:
6641 * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
6642 * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
6643 */
6644 goto empty_result;
6645 }
6646 len = expand_and_evaluate_arith(exp_word, &errmsg);
6647 if (errmsg)
6648 goto empty_result;
6649 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006650 debug_printf_varexp("from val:'%s'\n", val);
6651 if (len < 0) {
6652 /* in bash, len=-n means strlen()-n */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006653 len = (arith_t)vallen - beg + len;
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006654 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006655 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006656 }
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006657 if (len <= 0 || !val /*|| beg >= vallen*/) {
6658 empty_result:
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006659 val = NULL;
6660 } else {
6661 /* Paranoia. What if user entered 9999999999999
6662 * which fits in arith_t but not int? */
Denys Vlasenko07abc7c2020-12-21 10:09:48 +01006663 if (len > INT_MAX)
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006664 len = INT_MAX;
6665 val = to_be_freed = xstrndup(val + beg, len);
6666 }
6667 debug_printf_varexp("val:'%s'\n", val);
6668#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006669 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006670 val = NULL;
6671#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006672 } else { /* one of "-=+?" */
6673 /* Standard-mandated substitution ops:
6674 * ${var?word} - indicate error if unset
6675 * If var is unset, word (or a message indicating it is unset
6676 * if word is null) is written to standard error
6677 * and the shell exits with a non-zero exit status.
6678 * Otherwise, the value of var is substituted.
6679 * ${var-word} - use default value
6680 * If var is unset, word is substituted.
6681 * ${var=word} - assign and use default value
6682 * If var is unset, word is assigned to var.
6683 * In all cases, final value of var is substituted.
6684 * ${var+word} - use alternative value
6685 * If var is unset, null is substituted.
6686 * Otherwise, word is substituted.
6687 *
6688 * Word is subjected to tilde expansion, parameter expansion,
6689 * command substitution, and arithmetic expansion.
6690 * If word is not needed, it is not expanded.
6691 *
6692 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6693 * but also treat null var as if it is unset.
Denys Vlasenko294eb462018-07-20 16:18:59 +02006694 *
6695 * Word-splitting and single quote behavior:
6696 *
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006697 * $ f() { for i; do echo "|$i|"; done; }
Denys Vlasenko294eb462018-07-20 16:18:59 +02006698 *
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006699 * $ x=; f ${x:?'x y' z}; echo $?
6700 * bash: x: x y z # neither f nor "echo $?" executes
6701 * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
Denys Vlasenko294eb462018-07-20 16:18:59 +02006702 * $ x=; f "${x:?'x y' z}"
Denys Vlasenkoc7ef8182020-12-27 16:04:54 +01006703 * bash: x: x y z # dash prints: dash: x: 'x y' z
Denys Vlasenko294eb462018-07-20 16:18:59 +02006704 *
6705 * $ x=; f ${x:='x y' z}
6706 * |x|
6707 * |y|
6708 * |z|
6709 * $ x=; f "${x:='x y' z}"
6710 * |'x y' z|
6711 *
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006712 * $ x=x; f ${x:+'x y' z}
Denys Vlasenko294eb462018-07-20 16:18:59 +02006713 * |x y|
6714 * |z|
6715 * $ x=x; f "${x:+'x y' z}"
6716 * |'x y' z|
6717 *
6718 * $ x=; f ${x:-'x y' z}
6719 * |x y|
6720 * |z|
6721 * $ x=; f "${x:-'x y' z}"
6722 * |'x y' z|
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006723 */
6724 int use_word = (!val || ((exp_save == ':') && !val[0]));
6725 if (exp_op == '+')
6726 use_word = !use_word;
6727 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6728 (exp_save == ':') ? "true" : "false", use_word);
6729 if (use_word) {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006730 if (exp_op == '+' || exp_op == '-') {
6731 /* ${var+word} - use alternative value */
6732 /* ${var-word} - use default value */
6733 n = encode_then_append_var_plusminus(output, n, exp_word,
6734 /*dquoted:*/ (arg0 & 0x80)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006735 );
Denys Vlasenko294eb462018-07-20 16:18:59 +02006736 val = NULL;
6737 } else {
6738 /* ${var?word} - indicate error if unset */
6739 /* ${var=word} - assign and use default value */
6740 to_be_freed = encode_then_expand_vararg(exp_word,
6741 /*handle_squotes:*/ !(arg0 & 0x80),
6742 /*unbackslash:*/ 0
6743 );
6744 if (to_be_freed)
6745 exp_word = to_be_freed;
6746 if (exp_op == '?') {
6747 /* mimic bash message */
6748 msg_and_die_if_script("%s: %s",
6749 var,
6750 exp_word[0]
6751 ? exp_word
6752 : "parameter null or not set"
6753 /* ash has more specific messages, a-la: */
6754 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
6755 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006756//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006757//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006758// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6759// bash: x: x y z
6760// $
6761// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006762 } else {
Denys Vlasenko294eb462018-07-20 16:18:59 +02006763 val = exp_word;
6764 }
6765 if (exp_op == '=') {
6766 /* ${var=[word]} or ${var:=[word]} */
6767 if (isdigit(var[0]) || var[0] == '#') {
6768 /* mimic bash message */
6769 msg_and_die_if_script("$%s: cannot assign in this way", var);
6770 val = NULL;
6771 } else {
6772 char *new_var = xasprintf("%s=%s", var, val);
6773 set_local_var(new_var, /*flag:*/ 0);
6774 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006775 }
6776 }
6777 }
6778 } /* one of "-=+?" */
6779
6780 *exp_saveptr = exp_save;
6781 } /* if (exp_op) */
6782
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006783 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006784 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006785
Denys Vlasenko168579a2018-07-19 13:45:54 +02006786 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006787
6788 free(to_be_freed);
6789 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006790}
6791
6792/* Expand all variable references in given string, adding words to list[]
6793 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6794 * to be filled). This routine is extremely tricky: has to deal with
6795 * variables/parameters with whitespace, $* and $@, and constructs like
6796 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006797static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006798{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006799 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006800 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006801 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006802 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006803 char *p;
6804
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006805 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6806 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006807 debug_print_list("expand_vars_to_list[0]", output, n);
6808
6809 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6810 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006811#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006812 char arith_buf[sizeof(arith_t)*3 + 2];
6813#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006814
Denys Vlasenko168579a2018-07-19 13:45:54 +02006815 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006816 o_addchr(output, '\0');
6817 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006818 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006819 }
6820
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006821 o_addblock(output, arg, p - arg);
6822 debug_print_list("expand_vars_to_list[1]", output, n);
6823 arg = ++p;
6824 p = strchr(p, SPECIAL_VAR_SYMBOL);
6825
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006826 /* Fetch special var name (if it is indeed one of them)
6827 * and quote bit, force the bit on if singleword expansion -
6828 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006829 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006830
6831 /* Is this variable quoted and thus expansion can't be null?
6832 * "$@" is special. Even if quoted, it can still
6833 * expand to nothing (not even an empty string),
6834 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006835 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006836 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006837
6838 switch (first_ch & 0x7f) {
6839 /* Highest bit in first_ch indicates that var is double-quoted */
6840 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006841 case '@': {
6842 int i;
6843 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006844 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006845 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006846 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006847 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006848 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006849 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006850 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6851 if (G.global_argv[i++][0] && G.global_argv[i]) {
6852 /* this argv[] is not empty and not last:
6853 * put terminating NUL, start new word */
6854 o_addchr(output, '\0');
6855 debug_print_list("expand_vars_to_list[2]", output, n);
6856 n = o_save_ptr(output, n);
6857 debug_print_list("expand_vars_to_list[3]", output, n);
6858 }
6859 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006860 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006861 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006862 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006863 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006864 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006865 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006866 while (1) {
6867 o_addQstr(output, G.global_argv[i]);
6868 if (++i >= G.global_argc)
6869 break;
6870 o_addchr(output, '\0');
6871 debug_print_list("expand_vars_to_list[4]", output, n);
6872 n = o_save_ptr(output, n);
6873 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006874 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006875 while (1) {
6876 o_addQstr(output, G.global_argv[i]);
6877 if (!G.global_argv[++i])
6878 break;
6879 if (G.ifs[0])
6880 o_addchr(output, G.ifs[0]);
6881 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006882 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006883 }
6884 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006885 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006886 case SPECIAL_VAR_SYMBOL: {
6887 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006888 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006889 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006890 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006891 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006892 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006893 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006894 case SPECIAL_VAR_QUOTED_SVS:
6895 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006896 /* "^C variable", represents literal ^C char (possible in scripts) */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006897 o_addchr(output, SPECIAL_VAR_SYMBOL);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006898 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006899 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006900#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006901 case '`': {
6902 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006903 o_string subst_result = NULL_O_STRING;
6904
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006905 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006906 arg++;
6907 /* Can't just stuff it into output o_string,
6908 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006909 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006910 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6911 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006912 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006913 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006914 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko18567402018-07-20 17:51:31 +02006915 o_free(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006916 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006917 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006918#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006919#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006920 case '+': {
6921 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006922 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006923
6924 arg++; /* skip '+' */
6925 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6926 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006927 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006928 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6929 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkoe4a06122020-02-21 17:21:34 +01006930 if (res < 0
6931 && first_ch == (char)('+'|0x80)
6932 /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
6933 ) {
6934 /* Quoted negative ariths, like filename[0"$((-9))"],
6935 * should not be interpreted as glob ranges.
6936 * Convert leading '-' to '\-':
6937 */
6938 o_grow_by(output, 1);
6939 output->data[output->length++] = '\\';
6940 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006941 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006942 break;
6943 }
6944#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006945 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006946 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006947 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006948 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006949 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6950
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006951 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6952 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006953 if (*p != SPECIAL_VAR_SYMBOL)
6954 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006955 arg = ++p;
6956 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6957
Denys Vlasenko4c3c8a12018-07-20 19:11:09 +02006958 if (*arg) {
6959 /* handle trailing string */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006960 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006961 o_addchr(output, '\0');
6962 n = o_save_ptr(output, n);
6963 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006964 debug_print_list("expand_vars_to_list[a]", output, n);
6965 /* this part is literal, and it was already pre-quoted
Denys Vlasenko294eb462018-07-20 16:18:59 +02006966 * if needed (much earlier), do not use o_addQstr here!
6967 */
6968 o_addstr(output, arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006969 debug_print_list("expand_vars_to_list[b]", output, n);
Denys Vlasenko18567402018-07-20 17:51:31 +02006970 } else
6971 if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenko83e434d2018-07-20 17:36:06 +02006972 && !(cant_be_null & 0x80) /* and all vars were not quoted */
6973 && !output->has_quoted_part
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006974 ) {
6975 n--;
6976 /* allow to reuse list[n] later without re-growth */
6977 output->has_empty_slot = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006978 }
6979
6980 return n;
6981}
6982
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006983static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006984{
6985 int n;
6986 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006987 o_string output = NULL_O_STRING;
6988
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006989 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006990
6991 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006992 for (;;) {
6993 /* go to next list[n] */
6994 output.ended_in_ifs = 0;
6995 n = o_save_ptr(&output, n);
6996
6997 if (!*argv)
6998 break;
6999
7000 /* expand argv[i] */
7001 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenko294eb462018-07-20 16:18:59 +02007002 /* if (!output->has_empty_slot) -- need this?? */
7003 o_addchr(&output, '\0');
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007004 }
7005 debug_print_list("expand_variables", &output, n);
7006
7007 /* output.data (malloced in one block) gets returned in "list" */
7008 list = o_finalize_list(&output, n);
7009 debug_print_strings("expand_variables[1]", list);
7010 return list;
7011}
7012
7013static char **expand_strvec_to_strvec(char **argv)
7014{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007015 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007016}
7017
Denys Vlasenkod2241f52020-10-31 03:34:07 +01007018#if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007019static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
7020{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007021 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007022}
7023#endif
7024
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007025/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007026 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007027 *
7028 * NB: should NOT do globbing!
7029 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
7030 */
Denys Vlasenko34179952018-04-11 13:47:59 +02007031static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007032{
Denys Vlasenko637982f2017-07-06 01:52:23 +02007033#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007034 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02007035 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02007036#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007037 char *argv[2], **list;
7038
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007039 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007040 /* This is generally an optimization, but it also
7041 * handles "", which otherwise trips over !list[0] check below.
7042 * (is this ever happens that we actually get str="" here?)
7043 */
7044 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
7045 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007046 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007047 return xstrdup(str);
7048 }
7049
7050 argv[0] = (char*)str;
7051 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02007052 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02007053 if (!list[0]) {
7054 /* Example where it happens:
7055 * x=; echo ${x:-"$@"}
7056 */
7057 ((char*)list)[0] = '\0';
7058 } else {
7059 if (HUSH_DEBUG)
7060 if (list[1])
James Byrne69374872019-07-02 11:35:03 +02007061 bb_simple_error_msg_and_die("BUG in varexp2");
Denys Vlasenko2e711012018-07-18 16:02:25 +02007062 /* actually, just move string 2*sizeof(char*) bytes back */
7063 overlapping_strcpy((char*)list, list[0]);
7064 if (do_unbackslash)
7065 unbackslash((char*)list);
7066 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007067 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007068 return (char*)list;
7069}
7070
Denys Vlasenkoabf75562018-04-02 17:25:18 +02007071#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007072static char* expand_strvec_to_string(char **argv)
7073{
7074 char **list;
7075
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02007076 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007077 /* Convert all NULs to spaces */
7078 if (list[0]) {
7079 int n = 1;
7080 while (list[n]) {
7081 if (HUSH_DEBUG)
7082 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
7083 bb_error_msg_and_die("BUG in varexp3");
7084 /* bash uses ' ' regardless of $IFS contents */
7085 list[n][-1] = ' ';
7086 n++;
7087 }
7088 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02007089 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007090 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
7091 return (char*)list;
7092}
Denys Vlasenko1f191122018-01-11 13:17:30 +01007093#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007094
7095static char **expand_assignments(char **argv, int count)
7096{
7097 int i;
7098 char **p;
7099
7100 G.expanded_assignments = p = NULL;
7101 /* Expand assignments into one string each */
7102 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02007103 p = add_string_to_strings(p,
7104 expand_string_to_string(argv[i],
7105 EXP_FLAG_ESC_GLOB_CHARS,
7106 /*unbackslash:*/ 1
7107 )
7108 );
7109 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007110 }
7111 G.expanded_assignments = NULL;
7112 return p;
7113}
7114
7115
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007116static void switch_off_special_sigs(unsigned mask)
7117{
7118 unsigned sig = 0;
7119 while ((mask >>= 1) != 0) {
7120 sig++;
7121 if (!(mask & 1))
7122 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007123#if ENABLE_HUSH_TRAP
7124 if (G_traps) {
7125 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007126 /* trap is '', has to remain SIG_IGN */
7127 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007128 free(G_traps[sig]);
7129 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007130 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007131#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007132 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007133 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007134 }
7135}
7136
Denys Vlasenkob347df92011-08-09 22:49:15 +02007137#if BB_MMU
7138/* never called */
7139void re_execute_shell(char ***to_free, const char *s,
7140 char *g_argv0, char **g_argv,
7141 char **builtin_argv) NORETURN;
7142
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007143static void reset_traps_to_defaults(void)
7144{
7145 /* This function is always called in a child shell
7146 * after fork (not vfork, NOMMU doesn't use this function).
7147 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007148 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007149 unsigned mask;
7150
7151 /* Child shells are not interactive.
7152 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
7153 * Testcase: (while :; do :; done) + ^Z should background.
7154 * Same goes for SIGTERM, SIGHUP, SIGINT.
7155 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007156 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007157 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007158 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007159
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007160 /* Switch off special sigs */
7161 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007162# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007163 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007164# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02007165 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007166 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
7167 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007168
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007169# if ENABLE_HUSH_TRAP
7170 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007171 return;
7172
7173 /* Reset all sigs to default except ones with empty traps */
7174 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007175 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007176 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007177 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007178 continue; /* empty trap: has to remain SIG_IGN */
7179 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007180 free(G_traps[sig]);
7181 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007182 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007183 if (sig == 0)
7184 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007185 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007186 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007187# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007188}
7189
7190#else /* !BB_MMU */
7191
7192static void re_execute_shell(char ***to_free, const char *s,
7193 char *g_argv0, char **g_argv,
7194 char **builtin_argv) NORETURN;
7195static void re_execute_shell(char ***to_free, const char *s,
7196 char *g_argv0, char **g_argv,
7197 char **builtin_argv)
7198{
7199# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
7200 /* delims + 2 * (number of bytes in printed hex numbers) */
7201 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
7202 char *heredoc_argv[4];
7203 struct variable *cur;
7204# if ENABLE_HUSH_FUNCTIONS
7205 struct function *funcp;
7206# endif
7207 char **argv, **pp;
7208 unsigned cnt;
7209 unsigned long long empty_trap_mask;
7210
7211 if (!g_argv0) { /* heredoc */
7212 argv = heredoc_argv;
7213 argv[0] = (char *) G.argv0_for_re_execing;
7214 argv[1] = (char *) "-<";
7215 argv[2] = (char *) s;
7216 argv[3] = NULL;
7217 pp = &argv[3]; /* used as pointer to empty environment */
7218 goto do_exec;
7219 }
7220
7221 cnt = 0;
7222 pp = builtin_argv;
7223 if (pp) while (*pp++)
7224 cnt++;
7225
7226 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007227 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007228 int sig;
7229 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007230 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007231 empty_trap_mask |= 1LL << sig;
7232 }
7233 }
7234
7235 sprintf(param_buf, NOMMU_HACK_FMT
7236 , (unsigned) G.root_pid
7237 , (unsigned) G.root_ppid
7238 , (unsigned) G.last_bg_pid
7239 , (unsigned) G.last_exitcode
7240 , cnt
7241 , empty_trap_mask
7242 IF_HUSH_LOOPS(, G.depth_of_loop)
7243 );
7244# undef NOMMU_HACK_FMT
7245 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
7246 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
7247 */
7248 cnt += 6;
7249 for (cur = G.top_var; cur; cur = cur->next) {
7250 if (!cur->flg_export || cur->flg_read_only)
7251 cnt += 2;
7252 }
7253# if ENABLE_HUSH_FUNCTIONS
7254 for (funcp = G.top_func; funcp; funcp = funcp->next)
7255 cnt += 3;
7256# endif
7257 pp = g_argv;
7258 while (*pp++)
7259 cnt++;
7260 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
7261 *pp++ = (char *) G.argv0_for_re_execing;
7262 *pp++ = param_buf;
7263 for (cur = G.top_var; cur; cur = cur->next) {
7264 if (strcmp(cur->varstr, hush_version_str) == 0)
7265 continue;
7266 if (cur->flg_read_only) {
7267 *pp++ = (char *) "-R";
7268 *pp++ = cur->varstr;
7269 } else if (!cur->flg_export) {
7270 *pp++ = (char *) "-V";
7271 *pp++ = cur->varstr;
7272 }
7273 }
7274# if ENABLE_HUSH_FUNCTIONS
7275 for (funcp = G.top_func; funcp; funcp = funcp->next) {
7276 *pp++ = (char *) "-F";
7277 *pp++ = funcp->name;
7278 *pp++ = funcp->body_as_string;
7279 }
7280# endif
7281 /* We can pass activated traps here. Say, -Tnn:trap_string
7282 *
7283 * However, POSIX says that subshells reset signals with traps
7284 * to SIG_DFL.
7285 * I tested bash-3.2 and it not only does that with true subshells
7286 * of the form ( list ), but with any forked children shells.
7287 * I set trap "echo W" WINCH; and then tried:
7288 *
7289 * { echo 1; sleep 20; echo 2; } &
7290 * while true; do echo 1; sleep 20; echo 2; break; done &
7291 * true | { echo 1; sleep 20; echo 2; } | cat
7292 *
7293 * In all these cases sending SIGWINCH to the child shell
7294 * did not run the trap. If I add trap "echo V" WINCH;
7295 * _inside_ group (just before echo 1), it works.
7296 *
7297 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007298 */
7299 *pp++ = (char *) "-c";
7300 *pp++ = (char *) s;
7301 if (builtin_argv) {
7302 while (*++builtin_argv)
7303 *pp++ = *builtin_argv;
7304 *pp++ = (char *) "";
7305 }
7306 *pp++ = g_argv0;
7307 while (*g_argv)
7308 *pp++ = *g_argv++;
7309 /* *pp = NULL; - is already there */
7310 pp = environ;
7311
7312 do_exec:
7313 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007314 /* Don't propagate SIG_IGN to the child */
7315 if (SPECIAL_JOBSTOP_SIGS != 0)
7316 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007317 execve(bb_busybox_exec_path, argv, pp);
7318 /* Fallback. Useful for init=/bin/hush usage etc */
7319 if (argv[0][0] == '/')
7320 execve(argv[0], argv, pp);
7321 xfunc_error_retval = 127;
James Byrne69374872019-07-02 11:35:03 +02007322 bb_simple_error_msg_and_die("can't re-execute the shell");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007323}
7324#endif /* !BB_MMU */
7325
7326
7327static int run_and_free_list(struct pipe *pi);
7328
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007329/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007330 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7331 * end_trigger controls how often we stop parsing
7332 * NUL: parse all, execute, return
7333 * ';': parse till ';' or newline, execute, repeat till EOF
7334 */
7335static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007336{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007337 /* Why we need empty flag?
7338 * An obscure corner case "false; ``; echo $?":
7339 * empty command in `` should still set $? to 0.
7340 * But we can't just set $? to 0 at the start,
7341 * this breaks "false; echo `echo $?`" case.
7342 */
7343 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007344 while (1) {
7345 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007346
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007347#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02007348 if (end_trigger == ';') {
7349 G.promptmode = 0; /* PS1 */
7350 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
7351 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01007352#endif
Denys Vlasenko474cb202018-07-24 13:03:03 +02007353 pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02007354 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
7355 /* If we are in "big" script
7356 * (not in `cmd` or something similar)...
7357 */
7358 if (pipe_list == ERR_PTR && end_trigger == ';') {
7359 /* Discard cached input (rest of line) */
7360 int ch = inp->last_char;
7361 while (ch != EOF && ch != '\n') {
7362 //bb_error_msg("Discarded:'%c'", ch);
7363 ch = i_getch(inp);
7364 }
7365 /* Force prompt */
7366 inp->p = NULL;
7367 /* This stream isn't empty */
7368 empty = 0;
7369 continue;
7370 }
7371 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01007372 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007373 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007374 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007375 debug_print_tree(pipe_list, 0);
7376 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7377 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007378 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007379 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01007380 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007381 }
Eric Andersen25f27032001-04-26 23:22:31 +00007382}
7383
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007384static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007385{
7386 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007387 //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007388
Eric Andersen25f27032001-04-26 23:22:31 +00007389 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007390 parse_and_run_stream(&input, '\0');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007391 //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007392}
7393
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007394static void parse_and_run_file(HFILE *fp)
Eric Andersen25f27032001-04-26 23:22:31 +00007395{
Eric Andersen25f27032001-04-26 23:22:31 +00007396 struct in_str input;
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007397 IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01007398
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007399 IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007400 setup_file_in_str(&input, fp);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007401 parse_and_run_stream(&input, ';');
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02007402 IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00007403}
7404
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007405#if ENABLE_HUSH_TICK
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007406static int generate_stream_from_string(const char *s, pid_t *pid_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007407{
7408 pid_t pid;
7409 int channel[2];
7410# if !BB_MMU
7411 char **to_free = NULL;
7412# endif
7413
7414 xpipe(channel);
7415 pid = BB_MMU ? xfork() : xvfork();
7416 if (pid == 0) { /* child */
7417 disable_restore_tty_pgrp_on_exit();
7418 /* Process substitution is not considered to be usual
7419 * 'command execution'.
7420 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
7421 */
7422 bb_signals(0
7423 + (1 << SIGTSTP)
7424 + (1 << SIGTTIN)
7425 + (1 << SIGTTOU)
7426 , SIG_IGN);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007427 close(channel[0]); /* NB: close _first_, then move fd! */
7428 xmove_fd(channel[1], 1);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007429# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007430 /* Awful hack for `trap` or $(trap).
7431 *
7432 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
7433 * contains an example where "trap" is executed in a subshell:
7434 *
7435 * save_traps=$(trap)
7436 * ...
7437 * eval "$save_traps"
7438 *
7439 * Standard does not say that "trap" in subshell shall print
7440 * parent shell's traps. It only says that its output
7441 * must have suitable form, but then, in the above example
7442 * (which is not supposed to be normative), it implies that.
7443 *
7444 * bash (and probably other shell) does implement it
7445 * (traps are reset to defaults, but "trap" still shows them),
7446 * but as a result, "trap" logic is hopelessly messed up:
7447 *
7448 * # trap
7449 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
7450 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
7451 * # true | trap <--- trap is in subshell - no output (ditto)
7452 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
7453 * trap -- 'echo Ho' SIGWINCH
7454 * # echo `(trap)` <--- in subshell in subshell - output
7455 * trap -- 'echo Ho' SIGWINCH
7456 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
7457 * trap -- 'echo Ho' SIGWINCH
7458 *
7459 * The rules when to forget and when to not forget traps
7460 * get really complex and nonsensical.
7461 *
7462 * Our solution: ONLY bare $(trap) or `trap` is special.
7463 */
7464 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01007465 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007466 && skip_whitespace(s + 4)[0] == '\0'
7467 ) {
7468 static const char *const argv[] = { NULL, NULL };
7469 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007470 fflush_all(); /* important */
7471 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007472 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01007473# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007474# if BB_MMU
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007475 /* Prevent it from trying to handle ctrl-z etc */
7476 IF_HUSH_JOB(G.run_list_level = 1;)
7477 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007478 reset_traps_to_defaults();
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +02007479 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +02007480 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007481 parse_and_run_string(s);
7482 _exit(G.last_exitcode);
7483# else
7484 /* We re-execute after vfork on NOMMU. This makes this script safe:
7485 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7486 * huge=`cat BIG` # was blocking here forever
7487 * echo OK
7488 */
7489 re_execute_shell(&to_free,
7490 s,
7491 G.global_argv[0],
7492 G.global_argv + 1,
7493 NULL);
7494# endif
7495 }
7496
7497 /* parent */
7498 *pid_p = pid;
7499# if ENABLE_HUSH_FAST
7500 G.count_SIGCHLD++;
7501//bb_error_msg("[%d] fork in generate_stream_from_string:"
7502// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7503// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7504# endif
7505 enable_restore_tty_pgrp_on_exit();
7506# if !BB_MMU
7507 free(to_free);
7508# endif
7509 close(channel[1]);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007510 return channel[0];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007511}
7512
7513/* Return code is exit status of the process that is run. */
7514static int process_command_subs(o_string *dest, const char *s)
7515{
7516 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007517 pid_t pid;
7518 int status, ch, eol_cnt;
7519
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007520 fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007521
7522 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007523 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007524 while ((ch = getc(fp)) != EOF) {
7525 if (ch == '\0')
7526 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007527 if (ch == '\n') {
7528 eol_cnt++;
7529 continue;
7530 }
7531 while (eol_cnt) {
7532 o_addchr(dest, '\n');
7533 eol_cnt--;
7534 }
7535 o_addQchr(dest, ch);
7536 }
7537
7538 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007539 fclose(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007540 /* We need to extract exitcode. Test case
7541 * "true; echo `sleep 1; false` $?"
7542 * should print 1 */
7543 safe_waitpid(pid, &status, 0);
7544 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7545 return WEXITSTATUS(status);
7546}
7547#endif /* ENABLE_HUSH_TICK */
7548
7549
7550static void setup_heredoc(struct redir_struct *redir)
7551{
7552 struct fd_pair pair;
7553 pid_t pid;
7554 int len, written;
7555 /* the _body_ of heredoc (misleading field name) */
7556 const char *heredoc = redir->rd_filename;
7557 char *expanded;
7558#if !BB_MMU
7559 char **to_free;
7560#endif
7561
7562 expanded = NULL;
7563 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007564 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007565 if (expanded)
7566 heredoc = expanded;
7567 }
7568 len = strlen(heredoc);
7569
7570 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7571 xpiped_pair(pair);
7572 xmove_fd(pair.rd, redir->rd_fd);
7573
7574 /* Try writing without forking. Newer kernels have
7575 * dynamically growing pipes. Must use non-blocking write! */
7576 ndelay_on(pair.wr);
7577 while (1) {
7578 written = write(pair.wr, heredoc, len);
7579 if (written <= 0)
7580 break;
7581 len -= written;
7582 if (len == 0) {
7583 close(pair.wr);
7584 free(expanded);
7585 return;
7586 }
7587 heredoc += written;
7588 }
7589 ndelay_off(pair.wr);
7590
7591 /* Okay, pipe buffer was not big enough */
7592 /* Note: we must not create a stray child (bastard? :)
7593 * for the unsuspecting parent process. Child creates a grandchild
7594 * and exits before parent execs the process which consumes heredoc
7595 * (that exec happens after we return from this function) */
7596#if !BB_MMU
7597 to_free = NULL;
7598#endif
7599 pid = xvfork();
7600 if (pid == 0) {
7601 /* child */
7602 disable_restore_tty_pgrp_on_exit();
7603 pid = BB_MMU ? xfork() : xvfork();
7604 if (pid != 0)
7605 _exit(0);
7606 /* grandchild */
7607 close(redir->rd_fd); /* read side of the pipe */
7608#if BB_MMU
7609 full_write(pair.wr, heredoc, len); /* may loop or block */
7610 _exit(0);
7611#else
7612 /* Delegate blocking writes to another process */
7613 xmove_fd(pair.wr, STDOUT_FILENO);
7614 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7615#endif
7616 }
7617 /* parent */
7618#if ENABLE_HUSH_FAST
7619 G.count_SIGCHLD++;
7620//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7621#endif
7622 enable_restore_tty_pgrp_on_exit();
7623#if !BB_MMU
7624 free(to_free);
7625#endif
7626 close(pair.wr);
7627 free(expanded);
7628 wait(NULL); /* wait till child has died */
7629}
7630
Denys Vlasenko2db74612017-07-07 22:07:28 +02007631struct squirrel {
7632 int orig_fd;
7633 int moved_to;
7634 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7635 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7636};
7637
Denys Vlasenko621fc502017-07-24 12:42:17 +02007638static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7639{
7640 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7641 sq[i].orig_fd = orig;
7642 sq[i].moved_to = moved;
7643 sq[i+1].orig_fd = -1; /* end marker */
7644 return sq;
7645}
7646
Denys Vlasenko2db74612017-07-07 22:07:28 +02007647static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7648{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007649 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007650 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007651
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007652 i = 0;
7653 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007654 /* If we collide with an already moved fd... */
7655 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007656 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007657 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7658 if (sq[i].moved_to < 0) /* what? */
7659 xfunc_die();
7660 return sq;
7661 }
7662 if (fd == sq[i].orig_fd) {
7663 /* Example: echo Hello >/dev/null 1>&2 */
7664 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7665 return sq;
7666 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007667 }
7668
Denys Vlasenko2db74612017-07-07 22:07:28 +02007669 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007670 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007671 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7672 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007673 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007674 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007675}
7676
Denys Vlasenko657e9002017-07-30 23:34:04 +02007677static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7678{
7679 int i;
7680
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007681 i = 0;
7682 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007683 /* If we collide with an already moved fd... */
7684 if (fd == sq[i].orig_fd) {
7685 /* Examples:
7686 * "echo 3>FILE 3>&- 3>FILE"
7687 * "echo 3>&- 3>FILE"
7688 * No need for last redirect to insert
7689 * another "need to close 3" indicator.
7690 */
7691 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7692 return sq;
7693 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007694 }
7695
7696 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7697 return append_squirrel(sq, i, fd, -1);
7698}
7699
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007700/* fd: redirect wants this fd to be used (e.g. 3>file).
7701 * Move all conflicting internally used fds,
7702 * and remember them so that we can restore them later.
7703 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007704static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007705{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007706 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7707 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007708
7709#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko21806562019-11-01 14:16:07 +01007710 if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
7711 && fd == G_interactive_fd
7712 ) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007713 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007714 G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
7715 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 +02007716 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007717 }
7718#endif
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007719 /* Are we called from setup_redirects(squirrel==NULL)
7720 * in redirect in a [v]forked child?
7721 */
7722 if (sqp == NULL) {
7723 /* No need to move script fds.
7724 * For NOMMU case, it's actively wrong: we'd change ->fd
7725 * fields in memory for the parent, but parent's fds
Denys Vlasenko21806562019-11-01 14:16:07 +01007726 * aren't moved, it would use wrong fd!
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007727 * Reproducer: "cmd 3>FILE" in script.
7728 * If we would call move_HFILEs_on_redirect(), child would:
7729 * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
7730 * close(3) = 0
7731 * and change ->fd to 10 if fd#3 is a script fd. WRONG.
7732 */
7733 //bb_error_msg("sqp == NULL: [v]forked child");
7734 return 0;
7735 }
7736
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007737 /* If this one of script's fds? */
7738 if (move_HFILEs_on_redirect(fd, avoid_fd))
7739 return 1; /* yes. "we closed fd" (actually moved it) */
7740
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007741 /* Are we called for "exec 3>FILE"? Came through
7742 * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
7743 * This case used to fail for this script:
7744 * exec 3>FILE
7745 * echo Ok
7746 * ...100000 more lines...
7747 * echo Ok
7748 * as follows:
7749 * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
7750 * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
7751 * dup2(4, 3) = 3
7752 * ^^^^^^^^ oops, we lost fd#3 opened to our script!
7753 * close(4) = 0
7754 * write(1, "Ok\n", 3) = 3
7755 * ... = 3
7756 * write(1, "Ok\n", 3) = 3
7757 * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
7758 * ^^^^^^^^ oops, wrong fd!!!
7759 * With this case separate from sqp == NULL and *after* move_HFILEs,
7760 * it now works:
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007761 */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007762 if (sqp == ERR_PTR) {
7763 /* Don't preserve redirected fds: exec is _meant_ to change these */
7764 //bb_error_msg("sqp == ERR_PTR: exec >FILE");
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007765 return 0;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007766 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007767
Denys Vlasenko2db74612017-07-07 22:07:28 +02007768 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7769 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7770 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007771}
7772
Denys Vlasenko2db74612017-07-07 22:07:28 +02007773static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007774{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007775 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007776 int i;
7777 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007778 if (sq[i].moved_to >= 0) {
7779 /* We simply die on error */
7780 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7781 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7782 } else {
7783 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7784 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7785 close(sq[i].orig_fd);
7786 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007787 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007788 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007789 }
Denys Vlasenko21806562019-11-01 14:16:07 +01007790 if (G.HFILE_stdin
Denys Vlasenko1237d622020-12-25 19:01:49 +01007791 && G.HFILE_stdin->fd > STDIN_FILENO
7792 /* we compare > STDIN, not == STDIN, since hfgetc()
7793 * closes fd and sets ->fd to -1 if EOF is reached.
7794 * Testcase: echo 'pwd' | hush
7795 */
Denys Vlasenko21806562019-11-01 14:16:07 +01007796 ) {
7797 /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
7798 * Redirect moves ->fd to e.g. 10,
7799 * and it is not restored above (we do not restore script fds
7800 * after redirects, we just use new, "moved" fds).
7801 * However for stdin, get_user_input() -> read_line_input(),
7802 * and read builtin, depend on fd == STDIN_FILENO.
7803 */
7804 debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
7805 xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
7806 G.HFILE_stdin->fd = STDIN_FILENO;
7807 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007808
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007809 /* If moved, G_interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007810}
7811
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007812#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007813static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007814{
7815 if (G_interactive_fd)
7816 close(G_interactive_fd);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007817 close_all_HFILE_list();
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007818}
7819#endif
7820
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007821static int internally_opened_fd(int fd, struct squirrel *sq)
7822{
7823 int i;
7824
7825#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod8bd7012019-05-14 18:53:24 +02007826 if (fd == G_interactive_fd)
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007827 return 1;
7828#endif
7829 /* If this one of script's fds? */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007830 if (fd_in_HFILEs(fd))
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007831 return 1;
7832
7833 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7834 if (fd == sq[i].moved_to)
7835 return 1;
7836 }
7837 return 0;
7838}
7839
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007840/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7841 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007842static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007843{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007844 struct redir_struct *redir;
7845
7846 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007847 int newfd;
7848 int closed;
7849
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007850 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007851 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007852 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007853 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7854 * of the heredoc */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007855 debug_printf_redir("set heredoc '%s'\n",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007856 redir->rd_filename);
7857 setup_heredoc(redir);
7858 continue;
7859 }
7860
7861 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007862 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007863 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007864 int mode;
7865
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007866 if (redir->rd_filename == NULL) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02007867 /* Examples:
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007868 * "cmd >" (no filename)
7869 * "cmd > <file" (2nd redirect starts too early)
7870 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007871 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007872 continue;
7873 }
7874 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007875 p = expand_string_to_string(redir->rd_filename,
7876 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007877 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007878 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007879 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007880 /* Error message from open_or_warn can be lost
7881 * if stderr has been redirected, but bash
7882 * and ash both lose it as well
7883 * (though zsh doesn't!)
7884 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007885 return 1;
7886 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007887 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007888 /* open() gave us precisely the fd we wanted.
7889 * This means that this fd was not busy
7890 * (not opened to anywhere).
7891 * Remember to close it on restore:
7892 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007893 *sqp = add_squirrel_closed(*sqp, newfd);
7894 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007895 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007896 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007897 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7898 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007899 }
7900
Denys Vlasenko657e9002017-07-30 23:34:04 +02007901 if (newfd == redir->rd_fd)
7902 continue;
7903
7904 /* if "N>FILE": move newfd to redir->rd_fd */
7905 /* if "N>&M": dup newfd to redir->rd_fd */
7906 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7907
7908 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7909 if (newfd == REDIRFD_CLOSE) {
7910 /* "N>&-" means "close me" */
7911 if (!closed) {
7912 /* ^^^ optimization: saving may already
7913 * have closed it. If not... */
7914 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007915 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007916 /* Sometimes we do another close on restore, getting EBADF.
7917 * Consider "echo 3>FILE 3>&-"
7918 * first redirect remembers "need to close 3",
7919 * and second redirect closes 3! Restore code then closes 3 again.
7920 */
7921 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007922 /* if newfd is a script fd or saved fd, simulate EBADF */
Denys Vlasenko945e9b02018-07-24 18:01:22 +02007923 if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007924 //errno = EBADF;
7925 //bb_perror_msg_and_die("can't duplicate file descriptor");
7926 newfd = -1; /* same effect as code above */
7927 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007928 xdup2(newfd, redir->rd_fd);
7929 if (redir->rd_dup == REDIRFD_TO_FILE)
7930 /* "rd_fd > FILE" */
7931 close(newfd);
7932 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007933 }
7934 }
7935 return 0;
7936}
7937
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007938static char *find_in_path(const char *arg)
7939{
7940 char *ret = NULL;
7941 const char *PATH = get_local_var_value("PATH");
7942
7943 if (!PATH)
7944 return NULL;
7945
7946 while (1) {
7947 const char *end = strchrnul(PATH, ':');
7948 int sz = end - PATH; /* must be int! */
7949
7950 free(ret);
7951 if (sz != 0) {
7952 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7953 } else {
7954 /* We have xxx::yyyy in $PATH,
7955 * it means "use current dir" */
7956 ret = xstrdup(arg);
7957 }
7958 if (access(ret, F_OK) == 0)
7959 break;
7960
7961 if (*end == '\0') {
7962 free(ret);
7963 return NULL;
7964 }
7965 PATH = end + 1;
7966 }
7967
7968 return ret;
7969}
7970
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007971static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007972 const struct built_in_command *x,
7973 const struct built_in_command *end)
7974{
7975 while (x != end) {
7976 if (strcmp(name, x->b_cmd) != 0) {
7977 x++;
7978 continue;
7979 }
7980 debug_printf_exec("found builtin '%s'\n", name);
7981 return x;
7982 }
7983 return NULL;
7984}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007985static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007986{
7987 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7988}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007989static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007990{
7991 const struct built_in_command *x = find_builtin1(name);
7992 if (x)
7993 return x;
7994 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7995}
7996
Denys Vlasenkod5314e72020-06-24 09:31:30 +02007997#if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
Ron Yorston9e2a5662020-01-21 16:01:58 +00007998static const char * FAST_FUNC get_builtin_name(int i)
7999{
8000 if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
8001 return bltins1[i].b_cmd;
8002 }
8003 i -= ARRAY_SIZE(bltins1);
8004 if (i < ARRAY_SIZE(bltins2)) {
8005 return bltins2[i].b_cmd;
8006 }
8007 return NULL;
8008}
8009#endif
8010
Denys Vlasenko99496dc2018-06-26 15:36:58 +02008011static void remove_nested_vars(void)
8012{
8013 struct variable *cur;
8014 struct variable **cur_pp;
8015
8016 cur_pp = &G.top_var;
8017 while ((cur = *cur_pp) != NULL) {
8018 if (cur->var_nest_level <= G.var_nest_level) {
8019 cur_pp = &cur->next;
8020 continue;
8021 }
8022 /* Unexport */
8023 if (cur->flg_export) {
8024 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
8025 bb_unsetenv(cur->varstr);
8026 }
8027 /* Remove from global list */
8028 *cur_pp = cur->next;
8029 /* Free */
8030 if (!cur->max_len) {
8031 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
8032 free(cur->varstr);
8033 }
8034 free(cur);
8035 }
8036}
8037
8038static void enter_var_nest_level(void)
8039{
8040 G.var_nest_level++;
8041 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
8042
8043 /* Try: f() { echo -n .; f; }; f
8044 * struct variable::var_nest_level is uint16_t,
8045 * thus limiting recursion to < 2^16.
8046 * In any case, with 8 Mbyte stack SEGV happens
8047 * not too long after 2^16 recursions anyway.
8048 */
8049 if (G.var_nest_level > 0xff00)
8050 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
8051}
8052
8053static void leave_var_nest_level(void)
8054{
8055 G.var_nest_level--;
8056 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
8057 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
James Byrne69374872019-07-02 11:35:03 +02008058 bb_simple_error_msg_and_die("BUG: nesting underflow");
Denys Vlasenko99496dc2018-06-26 15:36:58 +02008059
8060 remove_nested_vars();
8061}
8062
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008063#if ENABLE_HUSH_FUNCTIONS
8064static struct function **find_function_slot(const char *name)
8065{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008066 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008067 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008068
8069 while ((funcp = *funcpp) != NULL) {
8070 if (strcmp(name, funcp->name) == 0) {
8071 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008072 break;
8073 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008074 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008075 }
8076 return funcpp;
8077}
8078
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01008079static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008080{
8081 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008082 return funcp;
8083}
8084
8085/* Note: takes ownership on name ptr */
8086static struct function *new_function(char *name)
8087{
8088 struct function **funcpp = find_function_slot(name);
8089 struct function *funcp = *funcpp;
8090
8091 if (funcp != NULL) {
8092 struct command *cmd = funcp->parent_cmd;
8093 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
8094 if (!cmd) {
8095 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
8096 free(funcp->name);
8097 /* Note: if !funcp->body, do not free body_as_string!
8098 * This is a special case of "-F name body" function:
8099 * body_as_string was not malloced! */
8100 if (funcp->body) {
8101 free_pipe_list(funcp->body);
8102# if !BB_MMU
8103 free(funcp->body_as_string);
8104# endif
8105 }
8106 } else {
8107 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
8108 cmd->argv[0] = funcp->name;
8109 cmd->group = funcp->body;
8110# if !BB_MMU
8111 cmd->group_as_string = funcp->body_as_string;
8112# endif
8113 }
8114 } else {
8115 debug_printf_exec("remembering new function '%s'\n", name);
8116 funcp = *funcpp = xzalloc(sizeof(*funcp));
8117 /*funcp->next = NULL;*/
8118 }
8119
8120 funcp->name = name;
8121 return funcp;
8122}
8123
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008124# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008125static void unset_func(const char *name)
8126{
8127 struct function **funcpp = find_function_slot(name);
8128 struct function *funcp = *funcpp;
8129
8130 if (funcp != NULL) {
8131 debug_printf_exec("freeing function '%s'\n", funcp->name);
8132 *funcpp = funcp->next;
8133 /* funcp is unlinked now, deleting it.
8134 * Note: if !funcp->body, the function was created by
8135 * "-F name body", do not free ->body_as_string
8136 * and ->name as they were not malloced. */
8137 if (funcp->body) {
8138 free_pipe_list(funcp->body);
8139 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008140# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008141 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008142# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008143 }
8144 free(funcp);
8145 }
8146}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01008147# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008148
8149# if BB_MMU
8150#define exec_function(to_free, funcp, argv) \
8151 exec_function(funcp, argv)
8152# endif
8153static void exec_function(char ***to_free,
8154 const struct function *funcp,
8155 char **argv) NORETURN;
8156static void exec_function(char ***to_free,
8157 const struct function *funcp,
8158 char **argv)
8159{
8160# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008161 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008162
8163 argv[0] = G.global_argv[0];
8164 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02008165 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008166
8167// Example when we are here: "cmd | func"
8168// func will run with saved-redirect fds open.
8169// $ f() { echo /proc/self/fd/*; }
8170// $ true | f
8171// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
8172// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
8173// Same in script:
8174// $ . ./SCRIPT
8175// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
8176// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
8177// They are CLOEXEC so external programs won't see them, but
8178// for "more correctness" we might want to close those extra fds here:
8179//? close_saved_fds_and_FILE_fds();
8180
Denys Vlasenko332e4112018-04-04 22:32:59 +02008181 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008182 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008183 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008184 IF_HUSH_LOCAL(G.func_nest_level++;)
8185
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008186 /* On MMU, funcp->body is always non-NULL */
8187 n = run_list(funcp->body);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008188 _exit(n);
8189# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008190//? close_saved_fds_and_FILE_fds();
8191
8192//TODO: check whether "true | func_with_return" works
8193
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008194 re_execute_shell(to_free,
8195 funcp->body_as_string,
8196 G.global_argv[0],
8197 argv + 1,
8198 NULL);
8199# endif
8200}
8201
8202static int run_function(const struct function *funcp, char **argv)
8203{
8204 int rc;
8205 save_arg_t sv;
8206 smallint sv_flg;
8207
8208 save_and_replace_G_args(&sv, argv);
8209
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008210 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008211 sv_flg = G_flag_return_in_progress;
8212 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02008213
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008214 /* Make "local" variables properly shadow previous ones */
8215 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008216 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008217
8218 /* On MMU, funcp->body is always non-NULL */
8219# if !BB_MMU
8220 if (!funcp->body) {
8221 /* Function defined by -F */
8222 parse_and_run_string(funcp->body_as_string);
8223 rc = G.last_exitcode;
8224 } else
8225# endif
8226 {
8227 rc = run_list(funcp->body);
8228 }
8229
Denys Vlasenko332e4112018-04-04 22:32:59 +02008230 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008231 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008232
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008233 G_flag_return_in_progress = sv_flg;
Denys Vlasenkobb095f42020-02-20 16:37:59 +01008234# if ENABLE_HUSH_TRAP
8235 debug_printf_exec("G.return_exitcode=-1\n");
8236 G.return_exitcode = -1; /* invalidate stashed return value */
8237# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008238
8239 restore_G_args(&sv, argv);
8240
8241 return rc;
8242}
8243#endif /* ENABLE_HUSH_FUNCTIONS */
8244
8245
8246#if BB_MMU
8247#define exec_builtin(to_free, x, argv) \
8248 exec_builtin(x, argv)
8249#else
8250#define exec_builtin(to_free, x, argv) \
8251 exec_builtin(to_free, argv)
8252#endif
8253static void exec_builtin(char ***to_free,
8254 const struct built_in_command *x,
8255 char **argv) NORETURN;
8256static void exec_builtin(char ***to_free,
8257 const struct built_in_command *x,
8258 char **argv)
8259{
8260#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008261 int rcode;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008262//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008263 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008264 fflush_all();
8265 _exit(rcode);
8266#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008267 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008268 /* On NOMMU, we must never block!
8269 * Example: { sleep 99 | read line; } & echo Ok
8270 */
8271 re_execute_shell(to_free,
8272 argv[0],
8273 G.global_argv[0],
8274 G.global_argv + 1,
8275 argv);
8276#endif
8277}
8278
8279
8280static void execvp_or_die(char **argv) NORETURN;
8281static void execvp_or_die(char **argv)
8282{
Denys Vlasenko04465da2016-10-03 01:01:15 +02008283 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008284 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008285 /* Don't propagate SIG_IGN to the child */
8286 if (SPECIAL_JOBSTOP_SIGS != 0)
8287 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008288 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008289 e = 2;
8290 if (errno == EACCES) e = 126;
8291 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008292 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02008293 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008294}
8295
8296#if ENABLE_HUSH_MODE_X
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008297static void x_mode_print_optionally_squoted(const char *str)
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008298{
8299 unsigned len;
8300 const char *cp;
8301
8302 cp = str;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008303
8304 /* the set of chars which-cause-string-to-be-squoted mimics bash */
8305 /* test a char with: bash -c 'set -x; echo "CH"' */
8306 if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
8307 " " "\001\002\003\004\005\006\007"
8308 "\010\011\012\013\014\015\016\017"
8309 "\020\021\022\023\024\025\026\027"
8310 "\030\031\032\033\034\035\036\037"
8311 )
8312 ] == '\0'
8313 ) {
8314 /* string has no special chars */
8315 x_mode_addstr(str);
8316 return;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008317 }
8318
8319 cp = str;
8320 for (;;) {
8321 /* print '....' up to EOL or first squote */
8322 len = (int)(strchrnul(cp, '\'') - cp);
8323 if (len != 0) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008324 x_mode_addchr('\'');
8325 x_mode_addblock(cp, len);
8326 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008327 cp += len;
8328 }
8329 if (*cp == '\0')
8330 break;
8331 /* string contains squote(s), print them as \' */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008332 x_mode_addchr('\\');
8333 x_mode_addchr('\'');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008334 cp++;
8335 }
8336}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008337static void dump_cmd_in_x_mode(char **argv)
8338{
8339 if (G_x_mode && argv) {
Denys Vlasenko9dda9272018-07-27 14:12:05 +02008340 unsigned n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008341
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008342 /* "+[+++...][ cmd...]\n\0" */
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008343 x_mode_prefix();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008344 n = 0;
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008345 while (argv[n]) {
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008346 x_mode_addchr(' ');
8347 if (argv[n][0] == '\0') {
8348 x_mode_addchr('\'');
8349 x_mode_addchr('\'');
8350 } else {
8351 x_mode_print_optionally_squoted(argv[n]);
Denys Vlasenko4b70c922018-07-27 17:42:38 +02008352 }
8353 n++;
8354 }
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02008355 x_mode_flush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008356 }
8357}
8358#else
8359# define dump_cmd_in_x_mode(argv) ((void)0)
8360#endif
8361
Denys Vlasenko57000292018-01-12 14:41:45 +01008362#if ENABLE_HUSH_COMMAND
8363static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
8364{
8365 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008366
Denys Vlasenko57000292018-01-12 14:41:45 +01008367 if (!opt_vV)
8368 return;
8369
8370 to_free = NULL;
8371 if (!explanation) {
8372 char *path = getenv("PATH");
8373 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008374 if (!explanation)
8375 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01008376 if (opt_vV != 'V')
8377 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
8378 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008379 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01008380 free(to_free);
8381 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01008382 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01008383}
8384#else
8385# define if_command_vV_print_and_exit(a,b,c) ((void)0)
8386#endif
8387
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008388#if BB_MMU
8389#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
8390 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
8391#define pseudo_exec(nommu_save, command, argv_expanded) \
8392 pseudo_exec(command, argv_expanded)
8393#endif
8394
8395/* Called after [v]fork() in run_pipe, or from builtin_exec.
8396 * Never returns.
8397 * Don't exit() here. If you don't exec, use _exit instead.
8398 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008399 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02008400 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008401static void pseudo_exec_argv(nommu_save_t *nommu_save,
8402 char **argv, int assignment_cnt,
8403 char **argv_expanded) NORETURN;
8404static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
8405 char **argv, int assignment_cnt,
8406 char **argv_expanded)
8407{
Denys Vlasenko57000292018-01-12 14:41:45 +01008408 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008409 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008410 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008411 IF_HUSH_COMMAND(char opt_vV = 0;)
8412 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008413
8414 new_env = expand_assignments(argv, assignment_cnt);
8415 dump_cmd_in_x_mode(new_env);
8416
8417 if (!argv[assignment_cnt]) {
8418 /* Case when we are here: ... | var=val | ...
8419 * (note that we do not exit early, i.e., do not optimize out
8420 * expand_assignments(): think about ... | var=`sleep 1` | ...
8421 */
8422 free_strings(new_env);
8423 _exit(EXIT_SUCCESS);
8424 }
8425
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008426 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008427#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008428 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008429#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008430 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008431 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008432#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008433 set_vars_and_save_old(new_env);
8434 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008435
8436 if (argv_expanded) {
8437 argv = argv_expanded;
8438 } else {
8439 argv = expand_strvec_to_strvec(argv + assignment_cnt);
8440#if !BB_MMU
8441 nommu_save->argv = argv;
8442#endif
8443 }
8444 dump_cmd_in_x_mode(argv);
8445
8446#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8447 if (strchr(argv[0], '/') != NULL)
8448 goto skip;
8449#endif
8450
Denys Vlasenko75481d32017-07-31 05:27:09 +02008451#if ENABLE_HUSH_FUNCTIONS
8452 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008453 funcp = find_function(argv[0]);
8454 if (funcp)
8455 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02008456#endif
8457
Denys Vlasenko57000292018-01-12 14:41:45 +01008458#if ENABLE_HUSH_COMMAND
8459 /* "command BAR": run BAR without looking it up among functions
8460 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
8461 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
8462 */
8463 while (strcmp(argv[0], "command") == 0 && argv[1]) {
8464 char *p;
8465
8466 argv++;
8467 p = *argv;
8468 if (p[0] != '-' || !p[1])
8469 continue; /* bash allows "command command command [-OPT] BAR" */
8470
8471 for (;;) {
8472 p++;
8473 switch (*p) {
8474 case '\0':
8475 argv++;
8476 p = *argv;
8477 if (p[0] != '-' || !p[1])
8478 goto after_opts;
8479 continue; /* next arg is also -opts, process it too */
8480 case 'v':
8481 case 'V':
8482 opt_vV = *p;
8483 continue;
8484 default:
8485 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
8486 }
8487 }
8488 }
8489 after_opts:
8490# if ENABLE_HUSH_FUNCTIONS
8491 if (opt_vV && find_function(argv[0]))
8492 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
8493# endif
8494#endif
8495
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008496 /* Check if the command matches any of the builtins.
8497 * Depending on context, this might be redundant. But it's
8498 * easier to waste a few CPU cycles than it is to figure out
8499 * if this is one of those cases.
8500 */
Denys Vlasenko57000292018-01-12 14:41:45 +01008501 /* Why "BB_MMU ? :" difference in logic? -
8502 * On NOMMU, it is more expensive to re-execute shell
8503 * just in order to run echo or test builtin.
8504 * It's better to skip it here and run corresponding
8505 * non-builtin later. */
8506 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
8507 if (x) {
8508 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
8509 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008510 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008511
8512#if ENABLE_FEATURE_SH_STANDALONE
8513 /* Check if the command matches any busybox applets */
8514 {
8515 int a = find_applet_by_name(argv[0]);
8516 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01008517 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008518# if BB_MMU /* see above why on NOMMU it is not allowed */
8519 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02008520 /* Do not leak open fds from opened script files etc.
8521 * Testcase: interactive "ls -l /proc/self/fd"
8522 * should not show tty fd open.
8523 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02008524 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02008525//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02008526//This casuses test failures in
8527//redir_children_should_not_see_saved_fd_2.tests
8528//redir_children_should_not_see_saved_fd_3.tests
8529//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008530 /* Without this, "rm -i FILE" can't be ^C'ed: */
8531 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02008532 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02008533 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008534 }
8535# endif
8536 /* Re-exec ourselves */
8537 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02008538 /* Don't propagate SIG_IGN to the child */
8539 if (SPECIAL_JOBSTOP_SIGS != 0)
8540 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008541 execv(bb_busybox_exec_path, argv);
8542 /* If they called chroot or otherwise made the binary no longer
8543 * executable, fall through */
8544 }
8545 }
8546#endif
8547
8548#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
8549 skip:
8550#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01008551 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008552 execvp_or_die(argv);
8553}
8554
8555/* Called after [v]fork() in run_pipe
8556 */
8557static void pseudo_exec(nommu_save_t *nommu_save,
8558 struct command *command,
8559 char **argv_expanded) NORETURN;
8560static void pseudo_exec(nommu_save_t *nommu_save,
8561 struct command *command,
8562 char **argv_expanded)
8563{
Denys Vlasenko49015a62018-04-03 13:02:43 +02008564#if ENABLE_HUSH_FUNCTIONS
8565 if (command->cmd_type == CMD_FUNCDEF) {
8566 /* Ignore funcdefs in pipes:
8567 * true | f() { cmd }
8568 */
8569 _exit(0);
8570 }
8571#endif
8572
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008573 if (command->argv) {
8574 pseudo_exec_argv(nommu_save, command->argv,
8575 command->assignment_cnt, argv_expanded);
8576 }
8577
8578 if (command->group) {
8579 /* Cases when we are here:
8580 * ( list )
8581 * { list } &
8582 * ... | ( list ) | ...
8583 * ... | { list } | ...
8584 */
8585#if BB_MMU
8586 int rcode;
8587 debug_printf_exec("pseudo_exec: run_list\n");
8588 reset_traps_to_defaults();
8589 rcode = run_list(command->group);
8590 /* OK to leak memory by not calling free_pipe_list,
8591 * since this process is about to exit */
8592 _exit(rcode);
8593#else
8594 re_execute_shell(&nommu_save->argv_from_re_execing,
8595 command->group_as_string,
8596 G.global_argv[0],
8597 G.global_argv + 1,
8598 NULL);
8599#endif
8600 }
8601
8602 /* Case when we are here: ... | >file */
8603 debug_printf_exec("pseudo_exec'ed null command\n");
8604 _exit(EXIT_SUCCESS);
8605}
8606
8607#if ENABLE_HUSH_JOB
8608static const char *get_cmdtext(struct pipe *pi)
8609{
8610 char **argv;
8611 char *p;
8612 int len;
8613
8614 /* This is subtle. ->cmdtext is created only on first backgrounding.
8615 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8616 * On subsequent bg argv is trashed, but we won't use it */
8617 if (pi->cmdtext)
8618 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008619
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008620 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008621 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008622 pi->cmdtext = xzalloc(1);
8623 return pi->cmdtext;
8624 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008625 len = 0;
8626 do {
8627 len += strlen(*argv) + 1;
8628 } while (*++argv);
8629 p = xmalloc(len);
8630 pi->cmdtext = p;
8631 argv = pi->cmds[0].argv;
8632 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008633 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008634 *p++ = ' ';
8635 } while (*++argv);
8636 p[-1] = '\0';
8637 return pi->cmdtext;
8638}
8639
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008640static void remove_job_from_table(struct pipe *pi)
8641{
8642 struct pipe *prev_pipe;
8643
8644 if (pi == G.job_list) {
8645 G.job_list = pi->next;
8646 } else {
8647 prev_pipe = G.job_list;
8648 while (prev_pipe->next != pi)
8649 prev_pipe = prev_pipe->next;
8650 prev_pipe->next = pi->next;
8651 }
8652 G.last_jobid = 0;
8653 if (G.job_list)
8654 G.last_jobid = G.job_list->jobid;
8655}
8656
8657static void delete_finished_job(struct pipe *pi)
8658{
8659 remove_job_from_table(pi);
8660 free_pipe(pi);
8661}
8662
8663static void clean_up_last_dead_job(void)
8664{
8665 if (G.job_list && !G.job_list->alive_cmds)
8666 delete_finished_job(G.job_list);
8667}
8668
Denys Vlasenko16096292017-07-10 10:00:28 +02008669static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008670{
8671 struct pipe *job, **jobp;
8672 int i;
8673
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008674 clean_up_last_dead_job();
8675
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008676 /* Find the end of the list, and find next job ID to use */
8677 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008678 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008679 while ((job = *jobp) != NULL) {
8680 if (job->jobid > i)
8681 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008682 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008683 }
8684 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008685
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008686 /* Create a new job struct at the end */
8687 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008688 job->next = NULL;
8689 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8690 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8691 for (i = 0; i < pi->num_cmds; i++) {
8692 job->cmds[i].pid = pi->cmds[i].pid;
8693 /* all other fields are not used and stay zero */
8694 }
8695 job->cmdtext = xstrdup(get_cmdtext(pi));
8696
8697 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008698 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008699 G.last_jobid = job->jobid;
8700}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008701#endif /* JOB */
8702
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008703static int job_exited_or_stopped(struct pipe *pi)
8704{
8705 int rcode, i;
8706
8707 if (pi->alive_cmds != pi->stopped_cmds)
8708 return -1;
8709
8710 /* All processes in fg pipe have exited or stopped */
8711 rcode = 0;
8712 i = pi->num_cmds;
8713 while (--i >= 0) {
8714 rcode = pi->cmds[i].cmd_exitcode;
8715 /* usually last process gives overall exitstatus,
8716 * but with "set -o pipefail", last *failed* process does */
8717 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8718 break;
8719 }
8720 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8721 return rcode;
8722}
8723
Denys Vlasenko7e675362016-10-28 21:57:31 +02008724static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008725{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008726#if ENABLE_HUSH_JOB
8727 struct pipe *pi;
8728#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008729 int i, dead;
8730
8731 dead = WIFEXITED(status) || WIFSIGNALED(status);
8732
8733#if DEBUG_JOBS
8734 if (WIFSTOPPED(status))
8735 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8736 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8737 if (WIFSIGNALED(status))
8738 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8739 childpid, WTERMSIG(status), WEXITSTATUS(status));
8740 if (WIFEXITED(status))
8741 debug_printf_jobs("pid %d exited, exitcode %d\n",
8742 childpid, WEXITSTATUS(status));
8743#endif
8744 /* Were we asked to wait for a fg pipe? */
8745 if (fg_pipe) {
8746 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008747
Denys Vlasenko7e675362016-10-28 21:57:31 +02008748 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008749 int rcode;
8750
Denys Vlasenko7e675362016-10-28 21:57:31 +02008751 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8752 if (fg_pipe->cmds[i].pid != childpid)
8753 continue;
8754 if (dead) {
8755 int ex;
8756 fg_pipe->cmds[i].pid = 0;
8757 fg_pipe->alive_cmds--;
8758 ex = WEXITSTATUS(status);
8759 /* bash prints killer signal's name for *last*
8760 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8761 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8762 */
8763 if (WIFSIGNALED(status)) {
8764 int sig = WTERMSIG(status);
Denys Vlasenko77a51a22020-12-29 16:53:11 +01008765#if ENABLE_HUSH_JOB
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008766 if (G.run_list_level == 1
8767 /* ^^^^^ Do not print in nested contexts, example:
8768 * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
8769 */
8770 && i == fg_pipe->num_cmds-1
8771 ) {
Denys Vlasenkoe16f7eb2020-10-24 04:26:43 +02008772 /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
8773 puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
Denys Vlasenkob65d6cb2020-10-24 03:33:32 +02008774 }
Denys Vlasenko77a51a22020-12-29 16:53:11 +01008775#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008776 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko93e2a222020-12-23 12:23:21 +01008777 /* MIPS has 128 sigs (1..128), if sig==128,
8778 * 128 + sig would result in exitcode 256 -> 0!
8779 */
8780 ex = 128 | sig;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008781 }
8782 fg_pipe->cmds[i].cmd_exitcode = ex;
8783 } else {
8784 fg_pipe->stopped_cmds++;
8785 }
8786 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8787 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008788 rcode = job_exited_or_stopped(fg_pipe);
8789 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008790/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8791 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8792 * and "killall -STOP cat" */
8793 if (G_interactive_fd) {
8794#if ENABLE_HUSH_JOB
8795 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008796 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008797#endif
8798 return rcode;
8799 }
8800 if (fg_pipe->alive_cmds == 0)
8801 return rcode;
8802 }
8803 /* There are still running processes in the fg_pipe */
8804 return -1;
8805 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008806 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008807 }
8808
8809#if ENABLE_HUSH_JOB
8810 /* We were asked to wait for bg or orphaned children */
8811 /* No need to remember exitcode in this case */
8812 for (pi = G.job_list; pi; pi = pi->next) {
8813 for (i = 0; i < pi->num_cmds; i++) {
8814 if (pi->cmds[i].pid == childpid)
8815 goto found_pi_and_prognum;
8816 }
8817 }
8818 /* Happens when shell is used as init process (init=/bin/sh) */
8819 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8820 return -1; /* this wasn't a process from fg_pipe */
8821
8822 found_pi_and_prognum:
8823 if (dead) {
8824 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008825 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008826 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01008827 /* NB: not 128 + sig, MIPS has sig 128 */
8828 rcode = 128 | WTERMSIG(status);
Denys Vlasenko840a4352017-07-07 22:56:02 +02008829 pi->cmds[i].cmd_exitcode = rcode;
8830 if (G.last_bg_pid == pi->cmds[i].pid)
8831 G.last_bg_pid_exitcode = rcode;
8832 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008833 pi->alive_cmds--;
8834 if (!pi->alive_cmds) {
Denys Vlasenko259747c2019-11-28 10:28:14 +01008835# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008836 G.dead_job_exitcode = job_exited_or_stopped(pi);
Denys Vlasenko259747c2019-11-28 10:28:14 +01008837# endif
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008838 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008839 printf(JOB_STATUS_FORMAT, pi->jobid,
8840 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008841 delete_finished_job(pi);
8842 } else {
8843/*
8844 * bash deletes finished jobs from job table only in interactive mode,
8845 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8846 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8847 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8848 * We only retain one "dead" job, if it's the single job on the list.
8849 * This covers most of real-world scenarios where this is useful.
8850 */
8851 if (pi != G.job_list)
8852 delete_finished_job(pi);
8853 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008854 }
8855 } else {
8856 /* child stopped */
8857 pi->stopped_cmds++;
8858 }
8859#endif
8860 return -1; /* this wasn't a process from fg_pipe */
8861}
8862
8863/* Check to see if any processes have exited -- if they have,
8864 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008865 *
8866 * If non-NULL fg_pipe: wait for its completion or stop.
8867 * Return its exitcode or zero if stopped.
8868 *
8869 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8870 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8871 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8872 * or 0 if no children changed status.
8873 *
8874 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8875 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8876 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008877 */
8878static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8879{
8880 int attributes;
8881 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008882 int rcode = 0;
8883
8884 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8885
8886 attributes = WUNTRACED;
8887 if (fg_pipe == NULL)
8888 attributes |= WNOHANG;
8889
8890 errno = 0;
8891#if ENABLE_HUSH_FAST
8892 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8893//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8894//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8895 /* There was neither fork nor SIGCHLD since last waitpid */
8896 /* Avoid doing waitpid syscall if possible */
8897 if (!G.we_have_children) {
8898 errno = ECHILD;
8899 return -1;
8900 }
8901 if (fg_pipe == NULL) { /* is WNOHANG set? */
8902 /* We have children, but they did not exit
8903 * or stop yet (we saw no SIGCHLD) */
8904 return 0;
8905 }
8906 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8907 }
8908#endif
8909
8910/* Do we do this right?
8911 * bash-3.00# sleep 20 | false
8912 * <ctrl-Z pressed>
8913 * [3]+ Stopped sleep 20 | false
8914 * bash-3.00# echo $?
8915 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8916 * [hush 1.14.0: yes we do it right]
8917 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008918 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008919 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008920#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008921 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008922 i = G.count_SIGCHLD;
8923#endif
8924 childpid = waitpid(-1, &status, attributes);
8925 if (childpid <= 0) {
8926 if (childpid && errno != ECHILD)
James Byrne69374872019-07-02 11:35:03 +02008927 bb_simple_perror_msg("waitpid");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008928#if ENABLE_HUSH_FAST
8929 else { /* Until next SIGCHLD, waitpid's are useless */
8930 G.we_have_children = (childpid == 0);
8931 G.handled_SIGCHLD = i;
8932//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8933 }
8934#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008935 /* ECHILD (no children), or 0 (no change in children status) */
8936 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008937 break;
8938 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008939 rcode = process_wait_result(fg_pipe, childpid, status);
8940 if (rcode >= 0) {
8941 /* fg_pipe exited or stopped */
8942 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008943 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008944 if (childpid == waitfor_pid) { /* "wait PID" */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008945 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008946 rcode = WEXITSTATUS(status);
8947 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01008948 rcode = 128 | WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008949 if (WIFSTOPPED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01008950 /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
8951 rcode = 128 | WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008952 rcode++;
8953 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008954 }
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +01008955#if ENABLE_HUSH_BASH_COMPAT
8956 if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
8957 && G.dead_job_exitcode >= 0 /* some job did finish */
8958 ) {
8959 debug_printf_exec("waitfor_pid:-1\n");
8960 rcode = G.dead_job_exitcode + 1;
8961 break;
8962 }
8963#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008964 /* This wasn't one of our processes, or */
8965 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008966 } /* while (waitpid succeeds)... */
8967
8968 return rcode;
8969}
8970
8971#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008972static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008973{
8974 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008975 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008976 if (G_saved_tty_pgrp) {
8977 /* Job finished, move the shell to the foreground */
8978 p = getpgrp(); /* our process group id */
8979 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8980 tcsetpgrp(G_interactive_fd, p);
8981 }
8982 return rcode;
8983}
8984#endif
8985
8986/* Start all the jobs, but don't wait for anything to finish.
8987 * See checkjobs().
8988 *
8989 * Return code is normally -1, when the caller has to wait for children
8990 * to finish to determine the exit status of the pipe. If the pipe
8991 * is a simple builtin command, however, the action is done by the
8992 * time run_pipe returns, and the exit code is provided as the
8993 * return value.
8994 *
8995 * Returns -1 only if started some children. IOW: we have to
8996 * mask out retvals of builtins etc with 0xff!
8997 *
8998 * The only case when we do not need to [v]fork is when the pipe
8999 * is single, non-backgrounded, non-subshell command. Examples:
9000 * cmd ; ... { list } ; ...
9001 * cmd && ... { list } && ...
9002 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01009003 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009004 * or (if SH_STANDALONE) an applet, and we can run the { list }
9005 * with run_list. If it isn't one of these, we fork and exec cmd.
9006 *
9007 * Cases when we must fork:
9008 * non-single: cmd | cmd
9009 * backgrounded: cmd & { list } &
9010 * subshell: ( list ) [&]
9011 */
9012#if !ENABLE_HUSH_MODE_X
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009013#define redirect_and_varexp_helper(command, sqp, argv_expanded) \
9014 redirect_and_varexp_helper(command, sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009015#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009016static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009017 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02009018 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009019 char **argv_expanded)
9020{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009021 /* Assignments occur before redirects. Try:
9022 * a=`sleep 1` sleep 2 3>/qwe/rty
9023 */
9024
9025 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
9026 dump_cmd_in_x_mode(new_env);
9027 dump_cmd_in_x_mode(argv_expanded);
9028 /* this takes ownership of new_env[i] elements, and frees new_env: */
9029 set_vars_and_save_old(new_env);
9030
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009031 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009032}
9033static NOINLINE int run_pipe(struct pipe *pi)
9034{
9035 static const char *const null_ptr = NULL;
9036
9037 int cmd_no;
9038 int next_infd;
9039 struct command *command;
9040 char **argv_expanded;
9041 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02009042 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009043 int rcode;
9044
9045 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
9046 debug_enter();
9047
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009048 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
9049 * Result should be 3 lines: q w e, qwe, q w e
9050 */
Denys Vlasenko96786362018-04-11 16:02:58 +02009051 if (G.ifs_whitespace != G.ifs)
9052 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009053 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02009054 if (G.ifs) {
9055 char *p;
9056 G.ifs_whitespace = (char*)G.ifs;
9057 p = skip_whitespace(G.ifs);
9058 if (*p) {
9059 /* Not all $IFS is whitespace */
9060 char *d;
9061 int len = p - G.ifs;
9062 p = skip_non_whitespace(p);
9063 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
9064 d = mempcpy(G.ifs_whitespace, G.ifs, len);
9065 while (*p) {
9066 if (isspace(*p))
9067 *d++ = *p;
9068 p++;
9069 }
9070 *d = '\0';
9071 }
9072 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009073 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02009074 G.ifs_whitespace = (char*)G.ifs;
9075 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02009076
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009077 IF_HUSH_JOB(pi->pgrp = -1;)
9078 pi->stopped_cmds = 0;
9079 command = &pi->cmds[0];
9080 argv_expanded = NULL;
9081
9082 if (pi->num_cmds != 1
9083 || pi->followup == PIPE_BG
9084 || command->cmd_type == CMD_SUBSHELL
9085 ) {
9086 goto must_fork;
9087 }
9088
9089 pi->alive_cmds = 1;
9090
9091 debug_printf_exec(": group:%p argv:'%s'\n",
9092 command->group, command->argv ? command->argv[0] : "NONE");
9093
9094 if (command->group) {
9095#if ENABLE_HUSH_FUNCTIONS
9096 if (command->cmd_type == CMD_FUNCDEF) {
9097 /* "executing" func () { list } */
9098 struct function *funcp;
9099
9100 funcp = new_function(command->argv[0]);
9101 /* funcp->name is already set to argv[0] */
9102 funcp->body = command->group;
9103# if !BB_MMU
9104 funcp->body_as_string = command->group_as_string;
9105 command->group_as_string = NULL;
9106# endif
9107 command->group = NULL;
9108 command->argv[0] = NULL;
9109 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
9110 funcp->parent_cmd = command;
9111 command->child_func = funcp;
9112
9113 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
9114 debug_leave();
9115 return EXIT_SUCCESS;
9116 }
9117#endif
9118 /* { list } */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +02009119 debug_printf_exec("non-subshell group\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009120 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009121 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009122 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02009123//FIXME: we need to pass squirrel down into run_list()
9124//for SH_STANDALONE case, or else this construct:
9125// { find /proc/self/fd; true; } >FILE; cmd2
9126//has no way of closing saved fd#1 for "find",
9127//and in SH_STANDALONE mode, "find" is not execed,
9128//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009129 rcode = run_list(command->group) & 0xff;
9130 }
9131 restore_redirects(squirrel);
9132 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9133 debug_leave();
9134 debug_printf_exec("run_pipe: return %d\n", rcode);
9135 return rcode;
9136 }
9137
9138 argv = command->argv ? command->argv : (char **) &null_ptr;
9139 {
9140 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009141 IF_HUSH_FUNCTIONS(const struct function *funcp;)
9142 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009143 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009144 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009145
Denys Vlasenko5807e182018-02-08 19:19:04 +01009146#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009147 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009148#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009149
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009150 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009151 /* Assignments, but no command.
9152 * Ensure redirects take effect (that is, create files).
9153 * Try "a=t >file"
9154 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009155 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009156 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009157 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02009158 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009159 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009160
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009161 /* Set shell variables */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009162 i = 0;
9163 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009164 char *p = expand_string_to_string(argv[i],
9165 EXP_FLAG_ESC_GLOB_CHARS,
9166 /*unbackslash:*/ 1
9167 );
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009168#if ENABLE_HUSH_MODE_X
9169 if (G_x_mode) {
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009170 char *eq;
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009171 if (i == 0)
9172 x_mode_prefix();
9173 x_mode_addchr(' ');
Denys Vlasenko4b70c922018-07-27 17:42:38 +02009174 eq = strchrnul(p, '=');
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009175 if (*eq) eq++;
9176 x_mode_addblock(p, (eq - p));
9177 x_mode_print_optionally_squoted(eq);
9178 x_mode_flush();
Denys Vlasenko9dda9272018-07-27 14:12:05 +02009179 }
9180#endif
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009181 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009182 if (set_local_var(p, /*flag:*/ 0)) {
9183 /* assignment to readonly var / putenv error? */
9184 rcode = 1;
9185 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009186 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009187 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009188 /* Redirect error sets $? to 1. Otherwise,
9189 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009190 * Else, clear $?:
9191 * false; q=`exit 2`; echo $? - should print 2
9192 * false; x=1; echo $? - should print 0
9193 * Because of the 2nd case, we can't just use G.last_exitcode.
9194 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009195 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02009196 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009197 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9198 debug_leave();
9199 debug_printf_exec("run_pipe: return %d\n", rcode);
9200 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009201 }
9202
9203 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkod2241f52020-10-31 03:34:07 +01009204#if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
9205 if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
9206 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
9207 else
9208#endif
Denys Vlasenko11752d42018-04-03 08:20:58 +02009209#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009210 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009211 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009212 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009213#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009214 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009215
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009216 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009217 if (!argv_expanded[0]) {
9218 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02009219 /* `false` still has to set exitcode 1 */
9220 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009221 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009222 }
9223
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009224 old_vars = NULL;
9225 sv_shadowed = G.shadowed_vars_pp;
9226
Denys Vlasenko75481d32017-07-31 05:27:09 +02009227 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009228 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
9229 IF_HUSH_FUNCTIONS(x = NULL;)
9230 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02009231 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009232 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009233 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
9234 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009235 /*
9236 * Variable assignments are executed, but then "forgotten":
9237 * a=`sleep 1;echo A` exec 3>&-; echo $a
9238 * sleeps, but prints nothing.
9239 */
9240 enter_var_nest_level();
9241 G.shadowed_vars_pp = &old_vars;
Denys Vlasenko945e9b02018-07-24 18:01:22 +02009242 rcode = redirect_and_varexp_helper(command,
9243 /*squirrel:*/ ERR_PTR,
9244 argv_expanded
9245 );
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009246 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009247 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009248
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009249 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009250 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009251
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009252 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02009253 * a=b true; env | grep ^a=
9254 */
9255 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009256 /* Collect all variables "shadowed" by helper
9257 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
9258 * into old_vars list:
9259 */
9260 G.shadowed_vars_pp = &old_vars;
9261 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009262 if (rcode == 0) {
9263 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009264 /* Do not collect *to old_vars list* vars shadowed
9265 * by e.g. "local VAR" builtin (collect them
9266 * in the previously nested list instead):
9267 * don't want them to be restored immediately
9268 * after "local" completes.
9269 */
9270 G.shadowed_vars_pp = sv_shadowed;
9271
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009272 debug_printf_exec(": builtin '%s' '%s'...\n",
9273 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009274 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009275 rcode = x->b_function(argv_expanded) & 0xff;
9276 fflush_all();
9277 }
9278#if ENABLE_HUSH_FUNCTIONS
9279 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009280 debug_printf_exec(": function '%s' '%s'...\n",
9281 funcp->name, argv_expanded[1]);
9282 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009283 /*
9284 * But do collect *to old_vars list* vars shadowed
9285 * within function execution. To that end, restore
9286 * this pointer _after_ function run:
9287 */
9288 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009289 }
9290#endif
9291 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009292 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009293 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009294 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009295 if (n < 0 || !APPLET_IS_NOFORK(n))
9296 goto must_fork;
9297
9298 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02009299 /* Collect all variables "shadowed" by helper into old_vars list */
9300 G.shadowed_vars_pp = &old_vars;
9301 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
9302 G.shadowed_vars_pp = sv_shadowed;
9303
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009304 if (rcode == 0) {
9305 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
9306 argv_expanded[0], argv_expanded[1]);
9307 /*
9308 * Note: signals (^C) can't interrupt here.
9309 * We remember them and they will be acted upon
9310 * after applet returns.
9311 * This makes applets which can run for a long time
9312 * and/or wait for user input ineligible for NOFORK:
9313 * for example, "yes" or "rm" (rm -i waits for input).
9314 */
9315 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009316 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02009317 } else
9318 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009319
Denys Vlasenko41d8f102018-04-05 14:41:21 +02009320 restore_redirects(squirrel);
9321 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009322 leave_var_nest_level();
9323 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009324
9325 /*
9326 * Try "usleep 99999999" + ^C + "echo $?"
9327 * with FEATURE_SH_NOFORK=y.
9328 */
9329 if (!funcp) {
9330 /* It was builtin or nofork.
9331 * if this would be a real fork/execed program,
9332 * it should have died if a fatal sig was received.
9333 * But OTOH, there was no separate process,
9334 * the sig was sent to _shell_, not to non-existing
9335 * child.
9336 * Let's just handle ^C only, this one is obvious:
9337 * we aren't ok with exitcode 0 when ^C was pressed
9338 * during builtin/nofork.
9339 */
9340 if (sigismember(&G.pending_set, SIGINT))
Denys Vlasenko93e2a222020-12-23 12:23:21 +01009341 rcode = 128 | SIGINT;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009342 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02009343 free(argv_expanded);
9344 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
9345 debug_leave();
9346 debug_printf_exec("run_pipe return %d\n", rcode);
9347 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009348 }
9349
9350 must_fork:
9351 /* NB: argv_expanded may already be created, and that
9352 * might include `cmd` runs! Do not rerun it! We *must*
9353 * use argv_expanded if it's non-NULL */
9354
9355 /* Going to fork a child per each pipe member */
9356 pi->alive_cmds = 0;
9357 next_infd = 0;
9358
9359 cmd_no = 0;
9360 while (cmd_no < pi->num_cmds) {
9361 struct fd_pair pipefds;
9362#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009363 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009364 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009365 nommu_save.old_vars = NULL;
9366 nommu_save.argv = NULL;
9367 nommu_save.argv_from_re_execing = NULL;
9368#endif
9369 command = &pi->cmds[cmd_no];
9370 cmd_no++;
9371 if (command->argv) {
9372 debug_printf_exec(": pipe member '%s' '%s'...\n",
9373 command->argv[0], command->argv[1]);
9374 } else {
9375 debug_printf_exec(": pipe member with no argv\n");
9376 }
9377
9378 /* pipes are inserted between pairs of commands */
9379 pipefds.rd = 0;
9380 pipefds.wr = 1;
9381 if (cmd_no < pi->num_cmds)
9382 xpiped_pair(pipefds);
9383
Denys Vlasenko5807e182018-02-08 19:19:04 +01009384#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko08fb82c2019-05-19 15:26:05 +02009385 G.execute_lineno = command->lineno;
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01009386#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009387
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009388 command->pid = BB_MMU ? fork() : vfork();
9389 if (!command->pid) { /* child */
9390#if ENABLE_HUSH_JOB
9391 disable_restore_tty_pgrp_on_exit();
9392 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
9393
9394 /* Every child adds itself to new process group
9395 * with pgid == pid_of_first_child_in_pipe */
9396 if (G.run_list_level == 1 && G_interactive_fd) {
9397 pid_t pgrp;
9398 pgrp = pi->pgrp;
9399 if (pgrp < 0) /* true for 1st process only */
9400 pgrp = getpid();
9401 if (setpgid(0, pgrp) == 0
9402 && pi->followup != PIPE_BG
9403 && G_saved_tty_pgrp /* we have ctty */
9404 ) {
9405 /* We do it in *every* child, not just first,
9406 * to avoid races */
9407 tcsetpgrp(G_interactive_fd, pgrp);
9408 }
9409 }
9410#endif
9411 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
9412 /* 1st cmd in backgrounded pipe
9413 * should have its stdin /dev/null'ed */
9414 close(0);
9415 if (open(bb_dev_null, O_RDONLY))
9416 xopen("/", O_RDONLY);
9417 } else {
9418 xmove_fd(next_infd, 0);
9419 }
9420 xmove_fd(pipefds.wr, 1);
9421 if (pipefds.rd > 1)
9422 close(pipefds.rd);
9423 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02009424 * and the pipe fd (fd#1) is available for dup'ing:
9425 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
9426 * of cmd1 goes into pipe.
9427 */
9428 if (setup_redirects(command, NULL)) {
9429 /* Happens when redir file can't be opened:
9430 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
9431 * FOO
9432 * hush: can't open '/qwe/rty': No such file or directory
9433 * BAZ
9434 * (echo BAR is not executed, it hits _exit(1) below)
9435 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009436 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02009437 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009438
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009439 /* Stores to nommu_save list of env vars putenv'ed
9440 * (NOMMU, on MMU we don't need that) */
9441 /* cast away volatility... */
9442 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
9443 /* pseudo_exec() does not return */
9444 }
9445
9446 /* parent or error */
9447#if ENABLE_HUSH_FAST
9448 G.count_SIGCHLD++;
9449//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
9450#endif
9451 enable_restore_tty_pgrp_on_exit();
9452#if !BB_MMU
9453 /* Clean up after vforked child */
9454 free(nommu_save.argv);
9455 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02009456 G.var_nest_level = sv_var_nest_level;
9457 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009458 add_vars(nommu_save.old_vars);
9459#endif
9460 free(argv_expanded);
9461 argv_expanded = NULL;
9462 if (command->pid < 0) { /* [v]fork failed */
9463 /* Clearly indicate, was it fork or vfork */
James Byrne69374872019-07-02 11:35:03 +02009464 bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009465 } else {
9466 pi->alive_cmds++;
9467#if ENABLE_HUSH_JOB
9468 /* Second and next children need to know pid of first one */
9469 if (pi->pgrp < 0)
9470 pi->pgrp = command->pid;
9471#endif
9472 }
9473
9474 if (cmd_no > 1)
9475 close(next_infd);
9476 if (cmd_no < pi->num_cmds)
9477 close(pipefds.wr);
9478 /* Pass read (output) pipe end to next iteration */
9479 next_infd = pipefds.rd;
9480 }
9481
9482 if (!pi->alive_cmds) {
9483 debug_leave();
9484 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
9485 return 1;
9486 }
9487
9488 debug_leave();
9489 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
9490 return -1;
9491}
9492
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009493/* NB: called by pseudo_exec, and therefore must not modify any
9494 * global data until exec/_exit (we can be a child after vfork!) */
9495static int run_list(struct pipe *pi)
9496{
9497#if ENABLE_HUSH_CASE
9498 char *case_word = NULL;
9499#endif
9500#if ENABLE_HUSH_LOOPS
9501 struct pipe *loop_top = NULL;
9502 char **for_lcur = NULL;
9503 char **for_list = NULL;
9504#endif
9505 smallint last_followup;
9506 smalluint rcode;
9507#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
9508 smalluint cond_code = 0;
9509#else
9510 enum { cond_code = 0 };
9511#endif
9512#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02009513 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009514 smallint last_rword; /* ditto */
9515#endif
9516
9517 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
9518 debug_enter();
9519
9520#if ENABLE_HUSH_LOOPS
9521 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01009522 {
9523 struct pipe *cpipe;
9524 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
9525 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
9526 continue;
9527 /* current word is FOR or IN (BOLD in comments below) */
9528 if (cpipe->next == NULL) {
9529 syntax_error("malformed for");
9530 debug_leave();
9531 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9532 return 1;
9533 }
9534 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
9535 if (cpipe->next->res_word == RES_DO)
9536 continue;
9537 /* next word is not "do". It must be "in" then ("FOR v in ...") */
9538 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
9539 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
9540 ) {
9541 syntax_error("malformed for");
9542 debug_leave();
9543 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
9544 return 1;
9545 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009546 }
9547 }
9548#endif
9549
9550 /* Past this point, all code paths should jump to ret: label
9551 * in order to return, no direct "return" statements please.
9552 * This helps to ensure that no memory is leaked. */
9553
9554#if ENABLE_HUSH_JOB
9555 G.run_list_level++;
9556#endif
9557
9558#if HAS_KEYWORDS
9559 rword = RES_NONE;
9560 last_rword = RES_XXXX;
9561#endif
9562 last_followup = PIPE_SEQ;
9563 rcode = G.last_exitcode;
9564
9565 /* Go through list of pipes, (maybe) executing them. */
9566 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009567 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009568 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009569
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009570 if (G.flag_SIGINT)
9571 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009572 if (G_flag_return_in_progress == 1)
9573 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009574
9575 IF_HAS_KEYWORDS(rword = pi->res_word;)
9576 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
9577 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009578
9579 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01009580 if (
9581#if ENABLE_HUSH_IF
9582 rword == RES_IF || rword == RES_ELIF ||
9583#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009584 pi->followup != PIPE_SEQ
9585 ) {
9586 G.errexit_depth++;
9587 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009588#if ENABLE_HUSH_LOOPS
9589 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
9590 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
9591 ) {
9592 /* start of a loop: remember where loop starts */
9593 loop_top = pi;
9594 G.depth_of_loop++;
9595 }
9596#endif
9597 /* Still in the same "if...", "then..." or "do..." branch? */
9598 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
9599 if ((rcode == 0 && last_followup == PIPE_OR)
9600 || (rcode != 0 && last_followup == PIPE_AND)
9601 ) {
9602 /* It is "<true> || CMD" or "<false> && CMD"
9603 * and we should not execute CMD */
9604 debug_printf_exec("skipped cmd because of || or &&\n");
9605 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02009606 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009607 }
9608 }
9609 last_followup = pi->followup;
9610 IF_HAS_KEYWORDS(last_rword = rword;)
9611#if ENABLE_HUSH_IF
9612 if (cond_code) {
9613 if (rword == RES_THEN) {
9614 /* if false; then ... fi has exitcode 0! */
9615 G.last_exitcode = rcode = EXIT_SUCCESS;
9616 /* "if <false> THEN cmd": skip cmd */
9617 continue;
9618 }
9619 } else {
9620 if (rword == RES_ELSE || rword == RES_ELIF) {
9621 /* "if <true> then ... ELSE/ELIF cmd":
9622 * skip cmd and all following ones */
9623 break;
9624 }
9625 }
9626#endif
9627#if ENABLE_HUSH_LOOPS
9628 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9629 if (!for_lcur) {
9630 /* first loop through for */
9631
9632 static const char encoded_dollar_at[] ALIGN1 = {
9633 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9634 }; /* encoded representation of "$@" */
9635 static const char *const encoded_dollar_at_argv[] = {
9636 encoded_dollar_at, NULL
9637 }; /* argv list with one element: "$@" */
9638 char **vals;
9639
Denys Vlasenkoa5db1d72018-07-28 12:42:08 +02009640 G.last_exitcode = rcode = EXIT_SUCCESS;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009641 vals = (char**)encoded_dollar_at_argv;
9642 if (pi->next->res_word == RES_IN) {
9643 /* if no variable values after "in" we skip "for" */
9644 if (!pi->next->cmds[0].argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009645 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9646 break;
9647 }
9648 vals = pi->next->cmds[0].argv;
9649 } /* else: "for var; do..." -> assume "$@" list */
9650 /* create list of variable values */
9651 debug_print_strings("for_list made from", vals);
9652 for_list = expand_strvec_to_strvec(vals);
9653 for_lcur = for_list;
9654 debug_print_strings("for_list", for_list);
9655 }
9656 if (!*for_lcur) {
9657 /* "for" loop is over, clean up */
9658 free(for_list);
9659 for_list = NULL;
9660 for_lcur = NULL;
9661 break;
9662 }
9663 /* Insert next value from for_lcur */
9664 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009665 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009666 continue;
9667 }
9668 if (rword == RES_IN) {
9669 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9670 }
9671 if (rword == RES_DONE) {
9672 continue; /* "done" has no cmds too */
9673 }
9674#endif
9675#if ENABLE_HUSH_CASE
9676 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009677 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009678 case_word = expand_string_to_string(pi->cmds->argv[0],
9679 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009680 debug_printf_exec("CASE word1:'%s'\n", case_word);
9681 //unbackslash(case_word);
9682 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009683 continue;
9684 }
9685 if (rword == RES_MATCH) {
9686 char **argv;
9687
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009688 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009689 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9690 break;
9691 /* all prev words didn't match, does this one match? */
9692 argv = pi->cmds->argv;
9693 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009694 char *pattern;
9695 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9696 pattern = expand_string_to_string(*argv,
9697 EXP_FLAG_ESC_GLOB_CHARS,
9698 /*unbackslash:*/ 0
9699 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009700 /* TODO: which FNM_xxx flags to use? */
9701 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009702 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9703 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009704 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009705 if (cond_code == 0) {
9706 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009707 free(case_word);
9708 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009709 break;
9710 }
9711 argv++;
9712 }
9713 continue;
9714 }
9715 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009716 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009717 if (cond_code != 0)
9718 continue; /* not matched yet, skip this pipe */
9719 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009720 if (rword == RES_ESAC) {
9721 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9722 if (case_word) {
9723 /* "case" did not match anything: still set $? (to 0) */
9724 G.last_exitcode = rcode = EXIT_SUCCESS;
9725 }
9726 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009727#endif
9728 /* Just pressing <enter> in shell should check for jobs.
9729 * OTOH, in non-interactive shell this is useless
9730 * and only leads to extra job checks */
9731 if (pi->num_cmds == 0) {
9732 if (G_interactive_fd)
9733 goto check_jobs_and_continue;
9734 continue;
9735 }
9736
9737 /* After analyzing all keywords and conditions, we decided
9738 * to execute this pipe. NB: have to do checkjobs(NULL)
9739 * after run_pipe to collect any background children,
9740 * even if list execution is to be stopped. */
9741 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009742#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009743 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009744#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009745 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9746 if (r != -1) {
9747 /* We ran a builtin, function, or group.
9748 * rcode is already known
9749 * and we don't need to wait for anything. */
9750 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9751 G.last_exitcode = rcode;
9752 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009753#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9754 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9755#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009756#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009757 /* Was it "break" or "continue"? */
9758 if (G.flag_break_continue) {
9759 smallint fbc = G.flag_break_continue;
9760 /* We might fall into outer *loop*,
9761 * don't want to break it too */
9762 if (loop_top) {
9763 G.depth_break_continue--;
9764 if (G.depth_break_continue == 0)
9765 G.flag_break_continue = 0;
9766 /* else: e.g. "continue 2" should *break* once, *then* continue */
9767 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9768 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009769 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009770 break;
9771 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009772 /* "continue": simulate end of loop */
9773 rword = RES_DONE;
9774 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009775 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009776#endif
9777 if (G_flag_return_in_progress == 1) {
9778 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9779 break;
9780 }
9781 } else if (pi->followup == PIPE_BG) {
9782 /* What does bash do with attempts to background builtins? */
9783 /* even bash 3.2 doesn't do that well with nested bg:
9784 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9785 * I'm NOT treating inner &'s as jobs */
9786#if ENABLE_HUSH_JOB
9787 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009788 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009789#endif
9790 /* Last command's pid goes to $! */
9791 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009792 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009793 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009794/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009795 rcode = EXIT_SUCCESS;
9796 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009797 } else {
9798#if ENABLE_HUSH_JOB
9799 if (G.run_list_level == 1 && G_interactive_fd) {
9800 /* Waits for completion, then fg's main shell */
9801 rcode = checkjobs_and_fg_shell(pi);
9802 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009803 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009804 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009805#endif
9806 /* This one just waits for completion */
9807 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9808 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9809 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009810 G.last_exitcode = rcode;
9811 check_and_run_traps();
Denys Vlasenkobb095f42020-02-20 16:37:59 +01009812#if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
9813 rcode = G.last_exitcode; /* "return" in trap can change it, read back */
9814#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009815 }
9816
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009817 /* Handle "set -e" */
9818 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9819 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9820 if (G.errexit_depth == 0)
9821 hush_exit(rcode);
9822 }
9823 G.errexit_depth = sv_errexit_depth;
9824
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009825 /* Analyze how result affects subsequent commands */
9826#if ENABLE_HUSH_IF
9827 if (rword == RES_IF || rword == RES_ELIF)
9828 cond_code = rcode;
9829#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009830 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009831 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009832 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009833#if ENABLE_HUSH_LOOPS
9834 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009835 if (pi->next
9836 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009837 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009838 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009839 if (rword == RES_WHILE) {
9840 if (rcode) {
9841 /* "while false; do...done" - exitcode 0 */
9842 G.last_exitcode = rcode = EXIT_SUCCESS;
9843 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009844 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009845 }
9846 }
9847 if (rword == RES_UNTIL) {
9848 if (!rcode) {
9849 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009850 break;
9851 }
9852 }
9853 }
9854#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009855 } /* for (pi) */
9856
9857#if ENABLE_HUSH_JOB
9858 G.run_list_level--;
9859#endif
9860#if ENABLE_HUSH_LOOPS
9861 if (loop_top)
9862 G.depth_of_loop--;
9863 free(for_list);
9864#endif
9865#if ENABLE_HUSH_CASE
9866 free(case_word);
9867#endif
9868 debug_leave();
9869 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9870 return rcode;
9871}
9872
9873/* Select which version we will use */
9874static int run_and_free_list(struct pipe *pi)
9875{
9876 int rcode = 0;
9877 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009878 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009879 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9880 rcode = run_list(pi);
9881 }
9882 /* free_pipe_list has the side effect of clearing memory.
9883 * In the long run that function can be merged with run_list,
9884 * but doing that now would hobble the debugging effort. */
9885 free_pipe_list(pi);
9886 debug_printf_exec("run_and_free_list return %d\n", rcode);
9887 return rcode;
9888}
9889
9890
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009891static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009892{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009893 sighandler_t old_handler;
9894 unsigned sig = 0;
9895 while ((mask >>= 1) != 0) {
9896 sig++;
9897 if (!(mask & 1))
9898 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009899 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009900 /* POSIX allows shell to re-enable SIGCHLD
9901 * even if it was SIG_IGN on entry.
9902 * Therefore we skip IGN check for it:
9903 */
9904 if (sig == SIGCHLD)
9905 continue;
Denys Vlasenko23bc5622020-02-18 16:46:01 +01009906 /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
9907 * Try:
9908 * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
9909 * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009910 */
Denys Vlasenko23bc5622020-02-18 16:46:01 +01009911 if (sig == SIGHUP && G_interactive_fd)
9912 continue;
9913 /* Unless one of the above signals, is it SIG_IGN? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009914 if (old_handler == SIG_IGN) {
9915 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009916 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009917#if ENABLE_HUSH_TRAP
9918 if (!G_traps)
9919 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9920 free(G_traps[sig]);
9921 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9922#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009923 }
9924 }
9925}
9926
9927/* Called a few times only (or even once if "sh -c") */
9928static void install_special_sighandlers(void)
9929{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009930 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009931
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009932 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009933 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009934 if (G_interactive_fd) {
9935 mask |= SPECIAL_INTERACTIVE_SIGS;
9936 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009937 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009938 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009939 /* Careful, do not re-install handlers we already installed */
9940 if (G.special_sig_mask != mask) {
9941 unsigned diff = mask & ~G.special_sig_mask;
9942 G.special_sig_mask = mask;
9943 install_sighandlers(diff);
9944 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009945}
9946
9947#if ENABLE_HUSH_JOB
9948/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009949/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009950static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009951{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009952 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009953
9954 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009955 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009956 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9957 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009958 + (1 << SIGBUS ) * HUSH_DEBUG
9959 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009960 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009961 + (1 << SIGABRT)
9962 /* bash 3.2 seems to handle these just like 'fatal' ones */
9963 + (1 << SIGPIPE)
9964 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009965 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009966 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009967 * we never want to restore pgrp on exit, and this fn is not called
9968 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009969 /*+ (1 << SIGHUP )*/
9970 /*+ (1 << SIGTERM)*/
9971 /*+ (1 << SIGINT )*/
9972 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009973 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009974
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009975 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009976}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009977#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009978
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009979static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009980{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009981 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009982 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009983 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009984 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009985 break;
9986 case 'x':
9987 IF_HUSH_MODE_X(G_x_mode = state;)
Denys Vlasenkoaa449c92018-07-28 12:13:58 +02009988 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 +01009989 break;
Denys Vlasenko18a90ec2019-09-05 14:07:14 +02009990 case 'e':
9991 G.o_opt[OPT_O_ERREXIT] = state;
9992 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009993 case 'o':
9994 if (!o_opt) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +02009995 /* "set -o" or "set +o" without parameter.
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009996 * in bash, set -o produces this output:
9997 * pipefail off
9998 * and set +o:
9999 * set +o pipefail
10000 * We always use the second form.
10001 */
10002 const char *p = o_opt_strings;
10003 idx = 0;
10004 while (*p) {
10005 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
10006 idx++;
10007 p += strlen(p) + 1;
10008 }
10009 break;
10010 }
10011 idx = index_in_strings(o_opt_strings, o_opt);
10012 if (idx >= 0) {
10013 G.o_opt[idx] = state;
10014 break;
10015 }
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020010016 /* fall through to error */
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010017 default:
10018 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +000010019 }
10020 return EXIT_SUCCESS;
10021}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010022
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000010023int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +000010024int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +000010025{
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010026 pid_t cached_getpid;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010027 enum {
10028 OPT_login = (1 << 0),
10029 };
10030 unsigned flags;
Denys Vlasenko63139b52020-12-13 22:00:56 +010010031#if !BB_MMU
10032 unsigned builtin_argc = 0;
10033#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010034 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010035 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010036 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +000010037
Denis Vlasenko574f2f42008-02-27 18:41:59 +000010038 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +020010039 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010040 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010041#if ENABLE_HUSH_TRAP
10042# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010043 G.return_exitcode = -1;
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010044# endif
10045 G.pre_trap_exitcode = -1;
Denys Vlasenkobb095f42020-02-20 16:37:59 +010010046#endif
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010047
Denys Vlasenko10c01312011-05-11 11:49:21 +020010048#if ENABLE_HUSH_FAST
10049 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
10050#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010051#if !BB_MMU
10052 G.argv0_for_re_execing = argv[0];
10053#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010054
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010055 cached_getpid = getpid(); /* for tcsetpgrp() during init */
Denys Vlasenko46a71dc2020-12-25 18:49:29 +010010056 G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
10057 G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010058
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010059 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010060 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
10061 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010062 shell_ver = xzalloc(sizeof(*shell_ver));
10063 shell_ver->flg_export = 1;
10064 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +020010065 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +020010066 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010067 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +010010068
Denys Vlasenko605067b2010-09-06 12:10:51 +020010069 /* Create shell local variables from the values
10070 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010071 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010072 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +000010073 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010074 if (e) while (*e) {
10075 char *value = strchr(*e, '=');
10076 if (value) { /* paranoia */
10077 cur_var->next = xzalloc(sizeof(*cur_var));
10078 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +000010079 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010080 cur_var->max_len = strlen(*e);
10081 cur_var->flg_export = 1;
10082 }
10083 e++;
10084 }
Denys Vlasenko605067b2010-09-06 12:10:51 +020010085 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +010010086 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
10087 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +020010088
10089 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010090 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010091
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010092#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020010093 /* Set (but not export) HOSTNAME unless already set */
10094 if (!get_local_var_value("HOSTNAME")) {
10095 struct utsname uts;
10096 uname(&uts);
10097 set_local_var_from_halves("HOSTNAME", uts.nodename);
10098 }
Denys Vlasenkofd6f2952018-08-05 15:13:08 +020010099#endif
10100 /* IFS is not inherited from the parent environment */
10101 set_local_var_from_halves("IFS", defifs);
10102
Denys Vlasenkoef8985c2019-05-19 16:29:09 +020010103 if (!get_local_var_value("PATH"))
10104 set_local_var_from_halves("PATH", bb_default_root_path);
10105
Denys Vlasenko0c360192019-05-19 15:37:50 +020010106 /* PS1/PS2 are set later, if we determine that we are interactive */
10107
Denys Vlasenko6db47842009-09-05 20:15:17 +020010108 /* bash also exports SHLVL and _,
10109 * and sets (but doesn't export) the following variables:
10110 * BASH=/bin/bash
10111 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
10112 * BASH_VERSION='3.2.0(1)-release'
10113 * HOSTTYPE=i386
10114 * MACHTYPE=i386-pc-linux-gnu
10115 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +020010116 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +020010117 * EUID=<NNNNN>
10118 * UID=<NNNNN>
10119 * GROUPS=()
10120 * LINES=<NNN>
10121 * COLUMNS=<NNN>
10122 * BASH_ARGC=()
10123 * BASH_ARGV=()
10124 * BASH_LINENO=()
10125 * BASH_SOURCE=()
10126 * DIRSTACK=()
10127 * PIPESTATUS=([0]="0")
10128 * HISTFILE=/<xxx>/.bash_history
10129 * HISTFILESIZE=500
10130 * HISTSIZE=500
10131 * MAILCHECK=60
10132 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
10133 * SHELL=/bin/bash
10134 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
10135 * TERM=dumb
10136 * OPTERR=1
10137 * OPTIND=1
Denys Vlasenko6db47842009-09-05 20:15:17 +020010138 * PS4='+ '
10139 */
10140
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010141#if NUM_SCRIPTS > 0
10142 if (argc < 0) {
10143 char *script = get_script_content(-argc - 1);
10144 G.global_argv = argv;
10145 G.global_argc = string_array_len(argv);
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010146 //install_special_sighandlers(); - needed?
10147 parse_and_run_string(script);
10148 goto final_return;
10149 }
10150#endif
10151
Eric Andersen94ac2442001-05-22 19:05:18 +000010152 /* Initialize some more globals to non-zero values */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +020010153 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +000010154
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010155 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010156 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010157 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010158 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010159 * in order to intercept (more) signals.
10160 */
10161
10162 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010163 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010164 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010165 while (1) {
Denys Vlasenko3b053052021-01-04 03:05:34 +010010166 int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
10167 "cexinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010168#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +000010169 "<:$:R:V:"
10170# if ENABLE_HUSH_FUNCTIONS
10171 "F:"
10172# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010173#endif
10174 );
10175 if (opt <= 0)
10176 break;
Eric Andersen25f27032001-04-26 23:22:31 +000010177 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010178 case 'c':
Denys Vlasenko0ab2dd42020-12-23 02:22:08 +010010179 /* Note: -c is not an option with param!
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010180 * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010181 */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010182 G.opt_c = 1;
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010183 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010184 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +000010185 /* Well, we cannot just declare interactiveness,
10186 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010187 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010188 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010189 case 's':
Denys Vlasenkof3634582019-06-03 12:21:04 +020010190 G.opt_s = 1;
Mike Frysinger19a7ea12009-03-28 13:02:11 +000010191 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010192 case 'l':
10193 flags |= OPT_login;
10194 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010195#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010196 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +020010197 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000010198 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010199 case '$': {
10200 unsigned long long empty_trap_mask;
10201
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010202 G.root_pid = bb_strtou(optarg, &optarg, 16);
10203 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +020010204 G.root_ppid = bb_strtou(optarg, &optarg, 16);
10205 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010206 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
10207 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010208 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010209 optarg++;
10210 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010211 optarg++;
10212 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
10213 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010214 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010215 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010216# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010217 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010218 for (sig = 1; sig < NSIG; sig++) {
10219 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010220 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +020010221 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010222 }
10223 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +020010224# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010225 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010226# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010227 optarg++;
10228 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010229# endif
Denys Vlasenko49142d42020-12-13 18:44:07 +010010230 /* Suppress "killed by signal" message, -$ hack is used
10231 * for subshells: echo `sh -c 'kill -9 $$'`
10232 * should be silent.
10233 */
10234 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenkoeb0de052018-04-09 17:54:07 +020010235# if ENABLE_HUSH_FUNCTIONS
10236 /* nommu uses re-exec trick for "... | func | ...",
10237 * should allow "return".
10238 * This accidentally allows returns in subshells.
10239 */
10240 G_flag_return_in_progress = -1;
10241# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +000010242 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010243 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010244 case 'R':
10245 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010246 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010247 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +000010248# if ENABLE_HUSH_FUNCTIONS
10249 case 'F': {
10250 struct function *funcp = new_function(optarg);
10251 /* funcp->name is already set to optarg */
10252 /* funcp->body is set to NULL. It's a special case. */
10253 funcp->body_as_string = argv[optind];
10254 optind++;
10255 break;
10256 }
10257# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +000010258#endif
Denys Vlasenko3b053052021-01-04 03:05:34 +010010259 /*case '?': invalid option encountered (set_mode('?') will fail) */
10260 /*case 'n':*/
10261 /*case 'x':*/
10262 /*case 'e':*/
10263 default:
Denys Vlasenko6696eac2010-11-14 02:01:50 +010010264 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +000010265 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +000010266 bb_show_usage();
Eric Andersen25f27032001-04-26 23:22:31 +000010267 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010268 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010269
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010270 /* Skip options. Try "hush -l": $1 should not be "-l"! */
10271 G.global_argc = argc - (optind - 1);
10272 G.global_argv = argv + (optind - 1);
10273 G.global_argv[0] = argv[0];
10274
Denis Vlasenkof9375282009-04-05 19:13:39 +000010275 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010276 if (flags & OPT_login) {
Denys Vlasenko63139b52020-12-13 22:00:56 +010010277 const char *hp = NULL;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010278 HFILE *input;
Denys Vlasenko63139b52020-12-13 22:00:56 +010010279
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010280 debug_printf("sourcing /etc/profile\n");
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010281 input = hfopen("/etc/profile");
Denys Vlasenko63139b52020-12-13 22:00:56 +010010282 run_profile:
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010283 if (input != NULL) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010284 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010285 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010286 hfclose(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010287 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010288 /* bash: after sourcing /etc/profile,
10289 * tries to source (in the given order):
10290 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010291 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010292 * bash also sources ~/.bash_logout on exit.
10293 * If called as sh, skips .bash_XXX files.
10294 */
Denys Vlasenko63139b52020-12-13 22:00:56 +010010295 if (!hp) { /* unless we looped on the "goto" already */
10296 hp = get_local_var_value("HOME");
10297 if (hp && hp[0]) {
10298 debug_printf("sourcing ~/.profile\n");
10299 hp = concat_path_file(hp, ".profile");
10300 input = hfopen(hp);
10301 free((char*)hp);
10302 goto run_profile;
10303 }
10304 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +000010305 }
10306
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010307 /* -c takes effect *after* -l */
10308 if (G.opt_c) {
10309 /* Possibilities:
10310 * sh ... -c 'script'
10311 * sh ... -c 'script' ARG0 [ARG1...]
10312 * On NOMMU, if builtin_argc != 0,
10313 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
10314 * "" needs to be replaced with NULL
10315 * and BARGV vector fed to builtin function.
10316 * Note: the form without ARG0 never happens:
10317 * sh ... -c 'builtin' BARGV... ""
10318 */
10319 char *script;
10320
10321 install_special_sighandlers();
10322
10323 G.global_argc--;
10324 G.global_argv++;
Denys Vlasenko49142d42020-12-13 18:44:07 +010010325#if !BB_MMU
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010326 if (builtin_argc) {
10327 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
10328 const struct built_in_command *x;
10329 x = find_builtin(G.global_argv[0]);
10330 if (x) { /* paranoia */
10331 argv = G.global_argv;
10332 G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
10333 G.global_argv += builtin_argc + 1;
10334 G.global_argv[-1] = NULL; /* replace "" */
10335 G.last_exitcode = x->b_function(argv);
10336 }
10337 goto final_return;
10338 }
Denys Vlasenko49142d42020-12-13 18:44:07 +010010339#endif
Denys Vlasenko9cabd172020-12-13 18:24:11 +010010340
10341 script = G.global_argv[0];
10342 if (!script)
10343 bb_error_msg_and_die(bb_msg_requires_arg, "-c");
10344 if (!G.global_argv[1]) {
10345 /* -c 'script' (no params): prevent empty $0 */
10346 G.global_argv[0] = argv[0];
10347 } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
10348 G.global_argc--;
10349 G.global_argv++;
10350 }
10351 parse_and_run_string(script);
10352 goto final_return;
10353 }
10354
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +020010355 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
Denys Vlasenkof3634582019-06-03 12:21:04 +020010356 if (!G.opt_s && G.global_argv[1]) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010357 HFILE *input;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010358 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +000010359 * "bash <script>" (which is never interactive (unless -i?))
10360 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +000010361 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +020010362 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +000010363 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010364 G.global_argc--;
10365 G.global_argv++;
10366 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010367 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010368 input = hfopen(G.global_argv[0]);
10369 if (!input) {
10370 bb_simple_perror_msg_and_die(G.global_argv[0]);
10371 }
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +020010372 xfunc_error_retval = 1;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010373 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010374 parse_and_run_file(input);
10375#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010376 hfclose(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010377#endif
10378 goto final_return;
10379 }
Denys Vlasenkof3634582019-06-03 12:21:04 +020010380 /* "implicit" -s: bare interactive hush shows 's' in $- */
Denys Vlasenkod8740b22019-05-19 19:11:21 +020010381 G.opt_s = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +000010382
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010383 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010384 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +000010385 */
Denis Vlasenkof9375282009-04-05 19:13:39 +000010386
Denys Vlasenko28a105d2009-06-01 11:26:30 +020010387 /* A shell is interactive if the '-i' flag was given,
10388 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +000010389 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +000010390 * no arguments remaining or the -s flag given
10391 * standard input is a terminal
10392 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +000010393 * Refer to Posix.2, the description of the 'sh' utility.
10394 */
10395#if ENABLE_HUSH_JOB
10396 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -040010397 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
10398 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
10399 if (G_saved_tty_pgrp < 0)
10400 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010401
10402 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010403 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010404 if (G_interactive_fd < 0) {
10405 /* try to dup to any fd */
10406 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010407 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010408 /* give up */
10409 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -040010410 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +000010411 }
10412 }
Eric Andersen25f27032001-04-26 23:22:31 +000010413 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010414 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010415 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010416 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010417
Mike Frysinger38478a62009-05-20 04:48:06 -040010418 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010419 /* If we were run as 'hush &', sleep until we are
10420 * in the foreground (tty pgrp == our pgrp).
10421 * If we get started under a job aware app (like bash),
10422 * make sure we are now in charge so we don't fight over
10423 * who gets the foreground */
10424 while (1) {
10425 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -040010426 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
10427 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010428 break;
10429 /* send TTIN to ourself (should stop us) */
10430 kill(- shell_pgrp, SIGTTIN);
10431 }
Denis Vlasenkof9375282009-04-05 19:13:39 +000010432 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010433
Denys Vlasenkof58f7052011-05-12 02:10:33 +020010434 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010435 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010436
Mike Frysinger38478a62009-05-20 04:48:06 -040010437 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010438 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010439 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010440 /* Put ourselves in our own process group
10441 * (bash, too, does this only if ctty is available) */
10442 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
10443 /* Grab control of the terminal */
Denys Vlasenkobb4e32b2020-12-20 16:36:00 +010010444 tcsetpgrp(G_interactive_fd, cached_getpid);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010445 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +020010446 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010447
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010448# if ENABLE_FEATURE_EDITING
10449 G.line_input_state = new_line_input_t(FOR_SHELL);
Ron Yorston9e2a5662020-01-21 16:01:58 +000010450# if EDITING_HAS_get_exe_name
10451 G.line_input_state->get_exe_name = get_builtin_name;
10452# endif
Denys Vlasenko76a4e832019-05-19 18:24:52 +020010453# endif
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010454# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
10455 {
10456 const char *hp = get_local_var_value("HISTFILE");
10457 if (!hp) {
10458 hp = get_local_var_value("HOME");
10459 if (hp)
10460 hp = concat_path_file(hp, ".hush_history");
10461 } else {
10462 hp = xstrdup(hp);
10463 }
10464 if (hp) {
10465 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +020010466 //set_local_var(xasprintf("HISTFILE=%s", ...));
10467 }
10468# if ENABLE_FEATURE_SH_HISTFILESIZE
10469 hp = get_local_var_value("HISTFILESIZE");
10470 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
10471# endif
10472 }
10473# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010474 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010475 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010476 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010477#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +000010478 /* No job control compiled in, only prompt/line editing */
10479 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +020010480 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010481 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010482 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +020010483 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010484 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010485 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010486 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +000010487 }
10488 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010489 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +000010490 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +000010491 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010492 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010493#else
10494 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010495 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +000010496#endif
10497 /* bash:
10498 * if interactive but not a login shell, sources ~/.bashrc
10499 * (--norc turns this off, --rcfile <file> overrides)
10500 */
10501
Denys Vlasenko0c360192019-05-19 15:37:50 +020010502 if (G_interactive_fd) {
10503#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
10504 /* Set (but not export) PS1/2 unless already set */
10505 if (!get_local_var_value("PS1"))
10506 set_local_var_from_halves("PS1", "\\w \\$ ");
10507 if (!get_local_var_value("PS2"))
10508 set_local_var_from_halves("PS2", "> ");
10509#endif
10510 if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
10511 /* note: ash and hush share this string */
10512 printf("\n\n%s %s\n"
10513 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
10514 "\n",
10515 bb_banner,
10516 "hush - the humble shell"
10517 );
10518 }
Mike Frysingerb2705e12009-03-23 08:44:02 +000010519 }
10520
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020010521 parse_and_run_file(hfopen(NULL)); /* stdin */
Eric Andersen25f27032001-04-26 23:22:31 +000010522
Denis Vlasenkod76c0492007-05-25 02:16:25 +000010523 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010524 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +000010525}
Denis Vlasenko96702ca2007-11-23 23:28:55 +000010526
10527
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010528/*
10529 * Built-ins
10530 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010531static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010532{
10533 return 0;
10534}
10535
Denys Vlasenko265062d2017-01-10 15:13:30 +010010536#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenkoa8e19602020-12-14 03:52:54 +010010537static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010538{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010539 int argc = string_array_len(argv);
10540 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -040010541}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010542#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +010010543#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -040010544static int FAST_FUNC builtin_test(char **argv)
10545{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010546 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010547}
Denys Vlasenko265062d2017-01-10 15:13:30 +010010548#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010549#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010550static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010551{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010552 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010553}
Denys Vlasenko1cc68042017-01-09 17:10:04 +010010554#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010555#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010556static int FAST_FUNC builtin_printf(char **argv)
10557{
Denys Vlasenkoc0836532009-10-19 13:13:06 +020010558 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -040010559}
10560#endif
10561
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010562#if ENABLE_HUSH_HELP
10563static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
10564{
10565 const struct built_in_command *x;
10566
10567 printf(
10568 "Built-in commands:\n"
10569 "------------------\n");
10570 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
10571 if (x->b_descr)
10572 printf("%-10s%s\n", x->b_cmd, x->b_descr);
10573 }
10574 return EXIT_SUCCESS;
10575}
10576#endif
10577
10578#if MAX_HISTORY && ENABLE_FEATURE_EDITING
10579static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
10580{
Ron Yorston9f3b4102019-12-16 09:31:10 +000010581 show_history(G.line_input_state);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010582 return EXIT_SUCCESS;
10583}
10584#endif
10585
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010586static char **skip_dash_dash(char **argv)
10587{
10588 argv++;
10589 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
10590 argv++;
10591 return argv;
10592}
10593
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010594static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010595{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010596 const char *newdir;
10597
10598 argv = skip_dash_dash(argv);
10599 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010600 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010601 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010602 * bash says "bash: cd: HOME not set" and does nothing
10603 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +000010604 */
Denys Vlasenko90a99042009-09-06 02:36:23 +020010605 const char *home = get_local_var_value("HOME");
10606 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +000010607 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010608 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +000010609 /* Mimic bash message exactly */
10610 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010611 return EXIT_FAILURE;
10612 }
Denys Vlasenko6db47842009-09-05 20:15:17 +020010613 /* Read current dir (get_cwd(1) is inside) and set PWD.
10614 * Note: do not enforce exporting. If PWD was unset or unexported,
10615 * set it again, but do not export. bash does the same.
10616 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010617 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010618 return EXIT_SUCCESS;
10619}
10620
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010621static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
10622{
10623 puts(get_cwd(0));
10624 return EXIT_SUCCESS;
10625}
10626
10627static int FAST_FUNC builtin_eval(char **argv)
10628{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010629 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +010010630
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010631 if (!argv[0])
10632 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +010010633
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010634 IF_HUSH_MODE_X(G.x_mode_depth++;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010635 //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010636 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010637 /* bash:
10638 * eval "echo Hi; done" ("done" is syntax error):
10639 * "echo Hi" will not execute too.
10640 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010641 parse_and_run_string(argv[0]);
10642 } else {
10643 /* "The eval utility shall construct a command by
10644 * concatenating arguments together, separating
10645 * each with a <space> character."
10646 */
10647 char *str, *p;
10648 unsigned len = 0;
10649 char **pp = argv;
10650 do
10651 len += strlen(*pp) + 1;
10652 while (*++pp);
10653 str = p = xmalloc(len);
10654 pp = argv;
10655 for (;;) {
10656 p = stpcpy(p, *pp);
10657 pp++;
10658 if (!*pp)
10659 break;
10660 *p++ = ' ';
10661 }
10662 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010663 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010664 }
Denys Vlasenko7c5f18a2018-07-26 15:21:50 +020010665 IF_HUSH_MODE_X(G.x_mode_depth--;)
Denys Vlasenko9dda9272018-07-27 14:12:05 +020010666 //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
Denys Vlasenkob0441a72018-07-15 18:03:56 +020010667 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010668}
10669
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010670static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010671{
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010672 argv = skip_dash_dash(argv);
10673 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010674 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010675
Denys Vlasenkof37eb392009-10-18 11:46:35 +020010676 /* Careful: we can end up here after [v]fork. Do not restore
10677 * tty pgrp then, only top-level shell process does that */
10678 if (G_saved_tty_pgrp && getpid() == G.root_pid)
10679 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
10680
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +020010681 /* Saved-redirect fds, script fds and G_interactive_fd are still
10682 * open here. However, they are all CLOEXEC, and execv below
10683 * closes them. Try interactive "exec ls -l /proc/self/fd",
10684 * it should show no extra open fds in the "ls" process.
10685 * If we'd try to run builtins/NOEXECs, this would need improving.
10686 */
10687 //close_saved_fds_and_FILE_fds();
10688
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010689 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010690 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010691 * and tcsetpgrp, and this is inherently racy.
10692 */
10693 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010694}
10695
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010696static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010697{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010698 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010699
10700 /* interactive bash:
10701 * # trap "echo EEE" EXIT
10702 * # exit
10703 * exit
10704 * There are stopped jobs.
10705 * (if there are _stopped_ jobs, running ones don't count)
10706 * # exit
10707 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010708 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010709 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010710 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010711 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010712
10713 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010714 argv = skip_dash_dash(argv);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010715 if (argv[0] == NULL) {
10716#if ENABLE_HUSH_TRAP
10717 if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
10718 hush_exit(G.pre_trap_exitcode);
10719#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010720 hush_exit(G.last_exitcode);
Denys Vlasenkocc9ecd92020-02-21 02:18:06 +010010721 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010722 /* mimic bash: exit 123abc == exit 255 + error msg */
10723 xfunc_error_retval = 255;
10724 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010725 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010726}
10727
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010728#if ENABLE_HUSH_TYPE
10729/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10730static int FAST_FUNC builtin_type(char **argv)
10731{
10732 int ret = EXIT_SUCCESS;
10733
10734 while (*++argv) {
10735 const char *type;
10736 char *path = NULL;
10737
10738 if (0) {} /* make conditional compile easier below */
10739 /*else if (find_alias(*argv))
10740 type = "an alias";*/
Denys Vlasenko259747c2019-11-28 10:28:14 +010010741# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010742 else if (find_function(*argv))
10743 type = "a function";
Denys Vlasenko259747c2019-11-28 10:28:14 +010010744# endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010745 else if (find_builtin(*argv))
10746 type = "a shell builtin";
10747 else if ((path = find_in_path(*argv)) != NULL)
10748 type = path;
10749 else {
10750 bb_error_msg("type: %s: not found", *argv);
10751 ret = EXIT_FAILURE;
10752 continue;
10753 }
10754
10755 printf("%s is %s\n", *argv, type);
10756 free(path);
10757 }
10758
10759 return ret;
10760}
10761#endif
10762
10763#if ENABLE_HUSH_READ
10764/* Interruptibility of read builtin in bash
10765 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10766 *
10767 * Empty trap makes read ignore corresponding signal, for any signal.
10768 *
10769 * SIGINT:
10770 * - terminates non-interactive shell;
10771 * - interrupts read in interactive shell;
10772 * if it has non-empty trap:
10773 * - executes trap and returns to command prompt in interactive shell;
10774 * - executes trap and returns to read in non-interactive shell;
10775 * SIGTERM:
10776 * - is ignored (does not interrupt) read in interactive shell;
10777 * - terminates non-interactive shell;
10778 * if it has non-empty trap:
10779 * - executes trap and returns to read;
10780 * SIGHUP:
10781 * - terminates shell (regardless of interactivity);
10782 * if it has non-empty trap:
10783 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010784 * SIGCHLD from children:
10785 * - does not interrupt read regardless of interactivity:
10786 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010787 */
10788static int FAST_FUNC builtin_read(char **argv)
10789{
10790 const char *r;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010791 struct builtin_read_params params;
10792
10793 memset(&params, 0, sizeof(params));
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010794
10795 /* "!": do not abort on errors.
10796 * Option string must start with "sr" to match BUILTIN_READ_xxx
10797 */
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010798 params.read_flags = getopt32(argv,
Denys Vlasenko259747c2019-11-28 10:28:14 +010010799# if BASH_READ_D
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010800 "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
Denys Vlasenko259747c2019-11-28 10:28:14 +010010801# else
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010802 "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
Denys Vlasenko259747c2019-11-28 10:28:14 +010010803# endif
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010804 );
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010805 if ((uint32_t)params.read_flags == (uint32_t)-1)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010806 return EXIT_FAILURE;
10807 argv += optind;
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010808 params.argv = argv;
10809 params.setvar = set_local_var_from_halves;
10810 params.ifs = get_local_var_value("IFS"); /* can be NULL */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010811
10812 again:
Denys Vlasenko19358cc2018-08-05 15:42:29 +020010813 r = shell_builtin_read(&params);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010814
10815 if ((uintptr_t)r == 1 && errno == EINTR) {
10816 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010817 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010818 goto again;
10819 }
10820
10821 if ((uintptr_t)r > 1) {
James Byrne69374872019-07-02 11:35:03 +020010822 bb_simple_error_msg(r);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010823 r = (char*)(uintptr_t)1;
10824 }
10825
10826 return (uintptr_t)r;
10827}
10828#endif
10829
10830#if ENABLE_HUSH_UMASK
10831static int FAST_FUNC builtin_umask(char **argv)
10832{
10833 int rc;
10834 mode_t mask;
10835
10836 rc = 1;
10837 mask = umask(0);
10838 argv = skip_dash_dash(argv);
10839 if (argv[0]) {
10840 mode_t old_mask = mask;
10841
10842 /* numeric umasks are taken as-is */
10843 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10844 if (!isdigit(argv[0][0]))
10845 mask ^= 0777;
10846 mask = bb_parse_mode(argv[0], mask);
10847 if (!isdigit(argv[0][0]))
10848 mask ^= 0777;
10849 if ((unsigned)mask > 0777) {
10850 mask = old_mask;
10851 /* bash messages:
10852 * bash: umask: 'q': invalid symbolic mode operator
10853 * bash: umask: 999: octal number out of range
10854 */
10855 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10856 rc = 0;
10857 }
10858 } else {
10859 /* Mimic bash */
10860 printf("%04o\n", (unsigned) mask);
10861 /* fall through and restore mask which we set to 0 */
10862 }
10863 umask(mask);
10864
10865 return !rc; /* rc != 0 - success */
10866}
10867#endif
10868
Denys Vlasenko41ade052017-01-08 18:56:24 +010010869#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010870static void print_escaped(const char *s)
10871{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010872 if (*s == '\'')
10873 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010874 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010875 const char *p = strchrnul(s, '\'');
10876 /* print 'xxxx', possibly just '' */
10877 printf("'%.*s'", (int)(p - s), s);
10878 if (*p == '\0')
10879 break;
10880 s = p;
10881 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010882 /* s points to '; print "'''...'''" */
10883 putchar('"');
10884 do putchar('\''); while (*++s == '\'');
10885 putchar('"');
10886 } while (*s);
10887}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010888#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010889
Denys Vlasenko1e660422017-07-17 21:10:50 +020010890#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010891static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010892{
10893 do {
10894 char *name = *argv;
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010895 const char *name_end = endofname(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010896
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010897 if (*name_end == '\0') {
10898 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010899
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010900 vpp = get_ptr_to_local_var(name, name_end - name);
10901 var = vpp ? *vpp : NULL;
10902
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010903 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010904 /* export -n NAME (without =VALUE) */
10905 if (var) {
10906 var->flg_export = 0;
10907 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10908 unsetenv(name);
10909 } /* else: export -n NOT_EXISTING_VAR: no-op */
10910 continue;
10911 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010912 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010913 /* export NAME (without =VALUE) */
10914 if (var) {
10915 var->flg_export = 1;
10916 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10917 putenv(var->varstr);
10918 continue;
10919 }
10920 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010921 if (flags & SETFLAG_MAKE_RO) {
10922 /* readonly NAME (without =VALUE) */
10923 if (var) {
10924 var->flg_read_only = 1;
10925 continue;
10926 }
10927 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010928# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010929 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010930 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010931 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10932 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010933 /* "local x=abc; ...; local x" - ignore second local decl */
10934 continue;
10935 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010936 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010937# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010938 /* Exporting non-existing variable.
10939 * bash does not put it in environment,
10940 * but remembers that it is exported,
10941 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010942 * We just set it to "" and export.
10943 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010944 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010945 * bash sets the value to "".
10946 */
10947 /* Or, it's "readonly NAME" (without =VALUE).
10948 * bash remembers NAME and disallows its creation
10949 * in the future.
10950 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010951 name = xasprintf("%s=", name);
10952 } else {
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010953 if (*name_end != '=') {
10954 bb_error_msg("'%s': bad variable name", name);
10955 /* do not parse following argv[]s: */
10956 return 1;
10957 }
Denys Vlasenko295fef82009-06-03 12:47:26 +020010958 /* (Un)exporting/making local NAME=VALUE */
10959 name = xstrdup(name);
Denys Vlasenkod8bd7012019-05-14 18:53:24 +020010960 /* Testcase: export PS1='\w \$ ' */
10961 unbackslash(name);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010962 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010963 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010964 if (set_local_var(name, flags))
10965 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010966 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010967 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010968}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010969#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010970
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010971#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010972static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010973{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010974 unsigned opt_unexport;
10975
Denys Vlasenko259747c2019-11-28 10:28:14 +010010976# if ENABLE_HUSH_EXPORT_N
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010977 /* "!": do not abort on errors */
10978 opt_unexport = getopt32(argv, "!n");
10979 if (opt_unexport == (uint32_t)-1)
10980 return EXIT_FAILURE;
10981 argv += optind;
Denys Vlasenko259747c2019-11-28 10:28:14 +010010982# else
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010983 opt_unexport = 0;
10984 argv++;
Denys Vlasenko259747c2019-11-28 10:28:14 +010010985# endif
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010986
10987 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010988 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010989 if (e) {
10990 while (*e) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010010991# if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010992 puts(*e++);
Denys Vlasenko259747c2019-11-28 10:28:14 +010010993# else
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010994 /* ash emits: export VAR='VAL'
10995 * bash: declare -x VAR="VAL"
10996 * we follow ash example */
10997 const char *s = *e++;
10998 const char *p = strchr(s, '=');
10999
11000 if (!p) /* wtf? take next variable */
11001 continue;
11002 /* export var= */
11003 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011004 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011005 putchar('\n');
Denys Vlasenko259747c2019-11-28 10:28:14 +010011006# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011007 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011008 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000011009 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011010 return EXIT_SUCCESS;
11011 }
11012
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011013 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011014}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010011015#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011016
Denys Vlasenko295fef82009-06-03 12:47:26 +020011017#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011018static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020011019{
11020 if (G.func_nest_level == 0) {
11021 bb_error_msg("%s: not in a function", argv[0]);
11022 return EXIT_FAILURE; /* bash compat */
11023 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020011024 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020011025 /* Since all builtins run in a nested variable level,
11026 * need to use level - 1 here. Or else the variable will be removed at once
11027 * after builtin returns.
11028 */
11029 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020011030}
11031#endif
11032
Denys Vlasenko1e660422017-07-17 21:10:50 +020011033#if ENABLE_HUSH_READONLY
11034static int FAST_FUNC builtin_readonly(char **argv)
11035{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011036 argv++;
11037 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020011038 /* bash: readonly [-p]: list all readonly VARs
11039 * (-p has no effect in bash)
11040 */
11041 struct variable *e;
11042 for (e = G.top_var; e; e = e->next) {
11043 if (e->flg_read_only) {
11044//TODO: quote value: readonly VAR='VAL'
11045 printf("readonly %s\n", e->varstr);
11046 }
11047 }
11048 return EXIT_SUCCESS;
11049 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020011050 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020011051}
11052#endif
11053
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011054#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011055/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
11056static int FAST_FUNC builtin_unset(char **argv)
11057{
11058 int ret;
11059 unsigned opts;
11060
11061 /* "!": do not abort on errors */
11062 /* "+": stop at 1st non-option */
11063 opts = getopt32(argv, "!+vf");
11064 if (opts == (unsigned)-1)
11065 return EXIT_FAILURE;
11066 if (opts == 3) {
James Byrne69374872019-07-02 11:35:03 +020011067 bb_simple_error_msg("unset: -v and -f are exclusive");
Denys Vlasenko61508d92016-10-02 21:12:02 +020011068 return EXIT_FAILURE;
11069 }
11070 argv += optind;
11071
11072 ret = EXIT_SUCCESS;
11073 while (*argv) {
11074 if (!(opts & 2)) { /* not -f */
11075 if (unset_local_var(*argv)) {
11076 /* unset <nonexistent_var> doesn't fail.
11077 * Error is when one tries to unset RO var.
11078 * Message was printed by unset_local_var. */
11079 ret = EXIT_FAILURE;
11080 }
11081 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011082# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020011083 else {
11084 unset_func(*argv);
11085 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011086# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011087 argv++;
11088 }
11089 return ret;
11090}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011091#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011092
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011093#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020011094/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
11095 * built-in 'set' handler
11096 * SUSv3 says:
11097 * set [-abCefhmnuvx] [-o option] [argument...]
11098 * set [+abCefhmnuvx] [+o option] [argument...]
11099 * set -- [argument...]
11100 * set -o
11101 * set +o
11102 * Implementations shall support the options in both their hyphen and
11103 * plus-sign forms. These options can also be specified as options to sh.
11104 * Examples:
11105 * Write out all variables and their values: set
11106 * Set $1, $2, and $3 and set "$#" to 3: set c a b
11107 * Turn on the -x and -v options: set -xv
11108 * Unset all positional parameters: set --
11109 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
11110 * Set the positional parameters to the expansion of x, even if x expands
11111 * with a leading '-' or '+': set -- $x
11112 *
11113 * So far, we only support "set -- [argument...]" and some of the short names.
11114 */
11115static int FAST_FUNC builtin_set(char **argv)
11116{
11117 int n;
11118 char **pp, **g_argv;
11119 char *arg = *++argv;
11120
11121 if (arg == NULL) {
11122 struct variable *e;
11123 for (e = G.top_var; e; e = e->next)
11124 puts(e->varstr);
11125 return EXIT_SUCCESS;
11126 }
11127
11128 do {
11129 if (strcmp(arg, "--") == 0) {
11130 ++argv;
11131 goto set_argv;
11132 }
11133 if (arg[0] != '+' && arg[0] != '-')
11134 break;
11135 for (n = 1; arg[n]; ++n) {
Denys Vlasenko18a90ec2019-09-05 14:07:14 +020011136 if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
11137 bb_error_msg("%s: %s: invalid option", "set", arg);
11138 return EXIT_FAILURE;
11139 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011140 if (arg[n] == 'o' && argv[1])
11141 argv++;
11142 }
11143 } while ((arg = *++argv) != NULL);
11144 /* Now argv[0] is 1st argument */
11145
11146 if (arg == NULL)
11147 return EXIT_SUCCESS;
11148 set_argv:
11149
11150 /* NB: G.global_argv[0] ($0) is never freed/changed */
11151 g_argv = G.global_argv;
11152 if (G.global_args_malloced) {
11153 pp = g_argv;
11154 while (*++pp)
11155 free(*pp);
11156 g_argv[1] = NULL;
11157 } else {
11158 G.global_args_malloced = 1;
11159 pp = xzalloc(sizeof(pp[0]) * 2);
11160 pp[0] = g_argv[0]; /* retain $0 */
11161 g_argv = pp;
11162 }
11163 /* This realloc's G.global_argv */
11164 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
11165
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020011166 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020011167
11168 return EXIT_SUCCESS;
Denys Vlasenko61508d92016-10-02 21:12:02 +020011169}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010011170#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011171
11172static int FAST_FUNC builtin_shift(char **argv)
11173{
11174 int n = 1;
11175 argv = skip_dash_dash(argv);
11176 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020011177 n = bb_strtou(argv[0], NULL, 10);
11178 if (errno || n < 0) {
11179 /* shared string with ash.c */
11180 bb_error_msg("Illegal number: %s", argv[0]);
11181 /*
11182 * ash aborts in this case.
11183 * bash prints error message and set $? to 1.
11184 * Interestingly, for "shift 99999" bash does not
11185 * print error message, but does set $? to 1
11186 * (and does no shifting at all).
11187 */
11188 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020011189 }
11190 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010011191 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020011192 int m = 1;
11193 while (m <= n)
11194 free(G.global_argv[m++]);
11195 }
11196 G.global_argc -= n;
11197 memmove(&G.global_argv[1], &G.global_argv[n+1],
11198 G.global_argc * sizeof(G.global_argv[0]));
11199 return EXIT_SUCCESS;
11200 }
11201 return EXIT_FAILURE;
11202}
11203
Denys Vlasenko74d40582017-08-11 01:32:46 +020011204#if ENABLE_HUSH_GETOPTS
11205static int FAST_FUNC builtin_getopts(char **argv)
11206{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011207/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
11208
Denys Vlasenko74d40582017-08-11 01:32:46 +020011209TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020011210If a required argument is not found, and getopts is not silent,
11211a question mark (?) is placed in VAR, OPTARG is unset, and a
11212diagnostic message is printed. If getopts is silent, then a
11213colon (:) is placed in VAR and OPTARG is set to the option
11214character found.
11215
11216Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011217
11218"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020011219*/
11220 char cbuf[2];
11221 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020011222 int c, n, exitcode, my_opterr;
11223 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011224
11225 optstring = *++argv;
11226 if (!optstring || !(var = *++argv)) {
James Byrne69374872019-07-02 11:35:03 +020011227 bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
Denys Vlasenko74d40582017-08-11 01:32:46 +020011228 return EXIT_FAILURE;
11229 }
11230
Denys Vlasenko238ff982017-08-29 13:38:30 +020011231 if (argv[1])
11232 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
11233 else
11234 argv = G.global_argv;
11235 cbuf[1] = '\0';
11236
11237 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020011238 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020011239 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020011240 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020011241 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020011242 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020011243
11244 /* getopts stops on first non-option. Add "+" to force that */
11245 /*if (optstring[0] != '+')*/ {
11246 char *s = alloca(strlen(optstring) + 2);
11247 sprintf(s, "+%s", optstring);
11248 optstring = s;
11249 }
11250
Denys Vlasenko238ff982017-08-29 13:38:30 +020011251 /* Naively, now we should just
11252 * cp = get_local_var_value("OPTIND");
11253 * optind = cp ? atoi(cp) : 0;
11254 * optarg = NULL;
11255 * opterr = my_opterr;
11256 * c = getopt(string_array_len(argv), argv, optstring);
11257 * and be done? Not so fast...
11258 * Unlike normal getopt() usage in C programs, here
11259 * each successive call will (usually) have the same argv[] CONTENTS,
11260 * but not the ADDRESSES. Worse yet, it's possible that between
11261 * invocations of "getopts", there will be calls to shell builtins
11262 * which use getopt() internally. Example:
11263 * while getopts "abc" RES -a -bc -abc de; do
11264 * unset -ff func
11265 * done
11266 * This would not work correctly: getopt() call inside "unset"
11267 * modifies internal libc state which is tracking position in
11268 * multi-option strings ("-abc"). At best, it can skip options
11269 * or return the same option infinitely. With glibc implementation
11270 * of getopt(), it would use outright invalid pointers and return
11271 * garbage even _without_ "unset" mangling internal state.
11272 *
11273 * We resort to resetting getopt() state and calling it N times,
11274 * until we get Nth result (or failure).
11275 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
11276 */
Denys Vlasenko60161812017-08-29 14:32:17 +020011277 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020011278 count = 0;
11279 n = string_array_len(argv);
11280 do {
11281 optarg = NULL;
11282 opterr = (count < G.getopt_count) ? 0 : my_opterr;
11283 c = getopt(n, argv, optstring);
11284 if (c < 0)
11285 break;
11286 count++;
11287 } while (count <= G.getopt_count);
11288
11289 /* Set OPTIND. Prevent resetting of the magic counter! */
11290 set_local_var_from_halves("OPTIND", utoa(optind));
11291 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020011292 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020011293
11294 /* Set OPTARG */
11295 /* Always set or unset, never left as-is, even on exit/error:
11296 * "If no option was found, or if the option that was found
11297 * does not have an option-argument, OPTARG shall be unset."
11298 */
11299 cp = optarg;
11300 if (c == '?') {
11301 /* If ":optstring" and unknown option is seen,
11302 * it is stored to OPTARG.
11303 */
11304 if (optstring[1] == ':') {
11305 cbuf[0] = optopt;
11306 cp = cbuf;
11307 }
11308 }
11309 if (cp)
11310 set_local_var_from_halves("OPTARG", cp);
11311 else
11312 unset_local_var("OPTARG");
11313
11314 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011315 exitcode = EXIT_SUCCESS;
11316 if (c < 0) { /* -1: end of options */
11317 exitcode = EXIT_FAILURE;
11318 c = '?';
11319 }
Denys Vlasenko419db032017-08-11 17:21:14 +020011320
Denys Vlasenko238ff982017-08-29 13:38:30 +020011321 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020011322 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020011323 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020011324
Denys Vlasenko74d40582017-08-11 01:32:46 +020011325 return exitcode;
11326}
11327#endif
11328
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011329static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020011330{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011331 char *arg_path, *filename;
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011332 HFILE *input;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011333 save_arg_t sv;
11334 char *args_need_save;
11335#if ENABLE_HUSH_FUNCTIONS
11336 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011337#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020011338
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011339 argv = skip_dash_dash(argv);
11340 filename = argv[0];
11341 if (!filename) {
11342 /* bash says: "bash: .: filename argument required" */
11343 return 2; /* bash compat */
11344 }
11345 arg_path = NULL;
11346 if (!strchr(filename, '/')) {
11347 arg_path = find_in_path(filename);
11348 if (arg_path)
11349 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010011350 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010011351 errno = ENOENT;
11352 bb_simple_perror_msg(filename);
11353 return EXIT_FAILURE;
11354 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011355 }
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011356 input = hfopen(filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011357 free(arg_path);
11358 if (!input) {
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011359 bb_perror_msg("%s", filename);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011360 /* POSIX: non-interactive shell should abort here,
11361 * not merely fail. So far no one complained :)
11362 */
11363 return EXIT_FAILURE;
11364 }
11365
11366#if ENABLE_HUSH_FUNCTIONS
11367 sv_flg = G_flag_return_in_progress;
11368 /* "we are inside sourced file, ok to use return" */
11369 G_flag_return_in_progress = -1;
11370#endif
11371 args_need_save = argv[1]; /* used as a boolean variable */
11372 if (args_need_save)
11373 save_and_replace_G_args(&sv, argv);
11374
11375 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
11376 G.last_exitcode = 0;
11377 parse_and_run_file(input);
Denys Vlasenko41ef41b2018-07-24 16:54:41 +020011378 hfclose(input);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011379
11380 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
11381 restore_G_args(&sv, argv);
11382#if ENABLE_HUSH_FUNCTIONS
11383 G_flag_return_in_progress = sv_flg;
11384#endif
11385
11386 return G.last_exitcode;
11387}
11388
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011389#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011390static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011391{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011392 int sig;
11393 char *new_cmd;
11394
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011395 if (!G_traps)
11396 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011397
11398 argv++;
11399 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000011400 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011401 /* No args: print all trapped */
11402 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011403 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011404 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011405 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020011406 /* note: bash adds "SIG", but only if invoked
11407 * as "bash". If called as "sh", or if set -o posix,
11408 * then it prints short signal names.
11409 * We are printing short names: */
11410 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011411 }
11412 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010011413 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011414 return EXIT_SUCCESS;
11415 }
11416
11417 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011418 /* If first arg is a number: reset all specified signals */
11419 sig = bb_strtou(*argv, NULL, 10);
11420 if (errno == 0) {
11421 int ret;
11422 process_sig_list:
11423 ret = EXIT_SUCCESS;
11424 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011425 sighandler_t handler;
11426
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011427 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020011428 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011429 ret = EXIT_FAILURE;
11430 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020011431 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011432 continue;
11433 }
11434
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011435 free(G_traps[sig]);
11436 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011437
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010011438 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011439 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011440
11441 /* There is no signal for 0 (EXIT) */
11442 if (sig == 0)
11443 continue;
11444
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011445 if (new_cmd)
11446 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
11447 else
11448 /* We are removing trap handler */
11449 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020011450 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011451 }
11452 return ret;
11453 }
11454
11455 if (!argv[1]) { /* no second arg */
James Byrne69374872019-07-02 11:35:03 +020011456 bb_simple_error_msg("trap: invalid arguments");
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011457 return EXIT_FAILURE;
11458 }
11459
11460 /* First arg is "-": reset all specified to default */
11461 /* First arg is "--": skip it, the rest is "handler SIGs..." */
11462 /* Everything else: set arg as signal handler
11463 * (includes "" case, which ignores signal) */
11464 if (argv[0][0] == '-') {
11465 if (argv[0][1] == '\0') { /* "-" */
11466 /* new_cmd remains NULL: "reset these sigs" */
11467 goto reset_traps;
11468 }
11469 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
11470 argv++;
11471 }
11472 /* else: "-something", no special meaning */
11473 }
11474 new_cmd = *argv;
11475 reset_traps:
11476 argv++;
11477 goto process_sig_list;
11478}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010011479#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000011480
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011481#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011482static struct pipe *parse_jobspec(const char *str)
11483{
11484 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011485 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011486
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011487 if (sscanf(str, "%%%u", &jobnum) != 1) {
11488 if (str[0] != '%'
11489 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
11490 ) {
11491 bb_error_msg("bad argument '%s'", str);
11492 return NULL;
11493 }
11494 /* It is "%%", "%+" or "%" - current job */
11495 jobnum = G.last_jobid;
11496 if (jobnum == 0) {
James Byrne69374872019-07-02 11:35:03 +020011497 bb_simple_error_msg("no current job");
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011498 return NULL;
11499 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011500 }
11501 for (pi = G.job_list; pi; pi = pi->next) {
11502 if (pi->jobid == jobnum) {
11503 return pi;
11504 }
11505 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011506 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011507 return NULL;
11508}
11509
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011510static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
11511{
11512 struct pipe *job;
11513 const char *status_string;
11514
11515 checkjobs(NULL, 0 /*(no pid to wait for)*/);
11516 for (job = G.job_list; job; job = job->next) {
11517 if (job->alive_cmds == job->stopped_cmds)
11518 status_string = "Stopped";
11519 else
11520 status_string = "Running";
11521
11522 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
11523 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011524
11525 clean_up_last_dead_job();
11526
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011527 return EXIT_SUCCESS;
11528}
11529
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011530/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011531static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011532{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011533 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011534 struct pipe *pi;
11535
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011536 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011537 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000011538
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011539 /* If they gave us no args, assume they want the last backgrounded task */
11540 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000011541 for (pi = G.job_list; pi; pi = pi->next) {
11542 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011543 goto found;
11544 }
11545 }
11546 bb_error_msg("%s: no current job", argv[0]);
11547 return EXIT_FAILURE;
11548 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010011549
11550 pi = parse_jobspec(argv[1]);
11551 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011552 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011553 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000011554 /* TODO: bash prints a string representation
11555 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040011556 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011557 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000011558 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011559 }
11560
11561 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011562 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
11563 for (i = 0; i < pi->num_cmds; i++) {
11564 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011565 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000011566 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011567
11568 i = kill(- pi->pgrp, SIGCONT);
11569 if (i < 0) {
11570 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020011571 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011572 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011573 }
James Byrne69374872019-07-02 11:35:03 +020011574 bb_simple_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011575 }
11576
Denis Vlasenko34d4d892009-04-04 20:24:37 +000011577 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020011578 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000011579 return checkjobs_and_fg_shell(pi);
11580 }
11581 return EXIT_SUCCESS;
11582}
11583#endif
11584
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011585#if ENABLE_HUSH_KILL
11586static int FAST_FUNC builtin_kill(char **argv)
11587{
11588 int ret = 0;
11589
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011590# if ENABLE_HUSH_JOB
11591 if (argv[1] && strcmp(argv[1], "-l") != 0) {
11592 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011593
11594 do {
11595 struct pipe *pi;
11596 char *dst;
11597 int j, n;
11598
11599 if (argv[i][0] != '%')
11600 continue;
11601 /*
11602 * "kill %N" - job kill
11603 * Converting to pgrp / pid kill
11604 */
11605 pi = parse_jobspec(argv[i]);
11606 if (!pi) {
11607 /* Eat bad jobspec */
11608 j = i;
11609 do {
11610 j++;
11611 argv[j - 1] = argv[j];
11612 } while (argv[j]);
11613 ret = 1;
11614 i--;
11615 continue;
11616 }
11617 /*
11618 * In jobs started under job control, we signal
11619 * entire process group by kill -PGRP_ID.
11620 * This happens, f.e., in interactive shell.
11621 *
11622 * Otherwise, we signal each child via
11623 * kill PID1 PID2 PID3.
11624 * Testcases:
11625 * sh -c 'sleep 1|sleep 1 & kill %1'
11626 * sh -c 'true|sleep 2 & sleep 1; kill %1'
11627 * sh -c 'true|sleep 1 & sleep 2; kill %1'
11628 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010011629 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011630 dst = alloca(n * sizeof(int)*4);
11631 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011632 if (G_interactive_fd)
11633 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011634 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011635 struct command *cmd = &pi->cmds[j];
11636 /* Skip exited members of the job */
11637 if (cmd->pid == 0)
11638 continue;
11639 /*
11640 * kill_main has matching code to expect
11641 * leading space. Needed to not confuse
11642 * negative pids with "kill -SIGNAL_NO" syntax
11643 */
11644 dst += sprintf(dst, " %u", (int)cmd->pid);
11645 }
11646 *dst = '\0';
11647 } while (argv[++i]);
11648 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011649# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011650
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011651 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011652 ret = run_applet_main(argv, kill_main);
11653 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010011654 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011655 return ret;
11656}
11657#endif
11658
11659#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000011660/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011661# if !ENABLE_HUSH_JOB
11662# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
11663# endif
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011664static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020011665{
11666 int ret = 0;
11667 for (;;) {
11668 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011669 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011670
Denys Vlasenko830ea352016-11-08 04:59:11 +010011671 if (!sigisemptyset(&G.pending_set))
11672 goto check_sig;
11673
Denys Vlasenko7e675362016-10-28 21:57:31 +020011674 /* waitpid is not interruptible by SA_RESTARTed
11675 * signals which we use. Thus, this ugly dance:
11676 */
11677
11678 /* Make sure possible SIGCHLD is stored in kernel's
11679 * pending signal mask before we call waitpid.
11680 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011681 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011682 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011683 sigfillset(&oldset); /* block all signals, remember old set */
Denys Vlasenkob437df12018-12-08 15:35:24 +010011684 sigprocmask2(SIG_SETMASK, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011685
11686 if (!sigisemptyset(&G.pending_set)) {
11687 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011688 goto restore;
11689 }
11690
11691 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011692/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011693 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011694 debug_printf_exec("checkjobs:%d\n", ret);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011695# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011696 if (waitfor_pipe) {
11697 int rcode = job_exited_or_stopped(waitfor_pipe);
11698 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11699 if (rcode >= 0) {
11700 ret = rcode;
11701 sigprocmask(SIG_SETMASK, &oldset, NULL);
11702 break;
11703 }
11704 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011705# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011706 /* if ECHILD, there are no children (ret is -1 or 0) */
11707 /* if ret == 0, no children changed state */
11708 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011709 if (errno == ECHILD || ret) {
11710 ret--;
11711 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011712 ret = 0;
Denys Vlasenko259747c2019-11-28 10:28:14 +010011713# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011714 if (waitfor_pid == -1 && errno == ECHILD) {
11715 /* exitcode of "wait -n" with no children is 127, not 0 */
11716 ret = 127;
11717 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011718# endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011719 sigprocmask(SIG_SETMASK, &oldset, NULL);
11720 break;
11721 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011722 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011723 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11724 /* Note: sigsuspend invokes signal handler */
11725 sigsuspend(&oldset);
Denys Vlasenko23bc5622020-02-18 16:46:01 +010011726 /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
11727 * to make sure SIGCHLD is not masked off?
11728 * It was reported that this:
11729 * fn() { : | return; }
11730 * shopt -s lastpipe
11731 * fn
11732 * exec hush SCRIPT
11733 * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
11734 * making "wait" commands in SCRIPT block forever.
11735 */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011736 restore:
11737 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011738 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011739 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011740 sig = check_and_run_traps();
11741 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011742 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko93e2a222020-12-23 12:23:21 +010011743 ret = 128 | sig;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011744 break;
11745 }
11746 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11747 }
11748 return ret;
11749}
11750
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011751static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011752{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011753 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011754 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011755
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011756 argv = skip_dash_dash(argv);
Denys Vlasenko259747c2019-11-28 10:28:14 +010011757# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011758 if (argv[0] && strcmp(argv[0], "-n") == 0) {
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011759 /* wait -n */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011760 /* (bash accepts "wait -n PID" too and ignores PID) */
11761 G.dead_job_exitcode = -1;
11762 return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
Denys Vlasenko4d1c5142019-03-26 18:34:06 +010011763 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011764# endif
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011765 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011766 /* Don't care about wait results */
11767 /* Note 1: must wait until there are no more children */
11768 /* Note 2: must be interruptible */
11769 /* Examples:
11770 * $ sleep 3 & sleep 6 & wait
11771 * [1] 30934 sleep 3
11772 * [2] 30935 sleep 6
11773 * [1] Done sleep 3
11774 * [2] Done sleep 6
11775 * $ sleep 3 & sleep 6 & wait
11776 * [1] 30936 sleep 3
11777 * [2] 30937 sleep 6
11778 * [1] Done sleep 3
11779 * ^C <-- after ~4 sec from keyboard
11780 * $
11781 */
Denys Vlasenkoe6f51ac2019-03-27 18:34:10 +010011782 return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011783 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011784
Denys Vlasenko7e675362016-10-28 21:57:31 +020011785 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011786 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011787 if (errno || pid <= 0) {
Denys Vlasenko259747c2019-11-28 10:28:14 +010011788# if ENABLE_HUSH_JOB
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011789 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011790 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011791 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011792 wait_pipe = parse_jobspec(*argv);
11793 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011794 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011795 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011796 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011797 } else {
11798 /* waiting on "last dead job" removes it */
11799 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011800 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011801 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011802 /* else: parse_jobspec() already emitted error msg */
11803 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011804 }
Denys Vlasenko259747c2019-11-28 10:28:14 +010011805# endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011806 /* mimic bash message */
11807 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011808 ret = EXIT_FAILURE;
11809 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011810 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011811
Denys Vlasenko7e675362016-10-28 21:57:31 +020011812 /* Do we have such child? */
11813 ret = waitpid(pid, &status, WNOHANG);
11814 if (ret < 0) {
11815 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011816 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011817 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011818 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011819 /* "wait $!" but last bg task has already exited. Try:
11820 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11821 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011822 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011823 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011824 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011825 } else {
11826 /* Example: "wait 1". mimic bash message */
Denys Vlasenko259747c2019-11-28 10:28:14 +010011827 bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011828 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011829 } else {
11830 /* ??? */
11831 bb_perror_msg("wait %s", *argv);
11832 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011833 continue; /* bash checks all argv[] */
11834 }
11835 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011836 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011837 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011838 } else {
11839 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011840 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011841 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011842 if (WIFSIGNALED(status))
Denys Vlasenko93e2a222020-12-23 12:23:21 +010011843 ret = 128 | WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011844 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011845 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011846
11847 return ret;
11848}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011849#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011850
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011851#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11852static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11853{
11854 if (argv[1]) {
11855 def = bb_strtou(argv[1], NULL, 10);
11856 if (errno || def < def_min || argv[2]) {
11857 bb_error_msg("%s: bad arguments", argv[0]);
11858 def = UINT_MAX;
11859 }
11860 }
11861 return def;
11862}
11863#endif
11864
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011865#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011866static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011867{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011868 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011869 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011870 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011871 /* if we came from builtin_continue(), need to undo "= 1" */
11872 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011873 return EXIT_SUCCESS; /* bash compat */
11874 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011875 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011876
11877 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11878 if (depth == UINT_MAX)
11879 G.flag_break_continue = BC_BREAK;
11880 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011881 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011882
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011883 return EXIT_SUCCESS;
11884}
11885
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011886static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011887{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011888 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11889 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011890}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011891#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011892
11893#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011894static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011895{
11896 int rc;
11897
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011898 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011899 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11900 return EXIT_FAILURE; /* bash compat */
11901 }
11902
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011903 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011904
11905 /* bash:
11906 * out of range: wraps around at 256, does not error out
11907 * non-numeric param:
11908 * f() { false; return qwe; }; f; echo $?
11909 * bash: return: qwe: numeric argument required <== we do this
11910 * 255 <== we also do this
11911 */
11912 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
Denys Vlasenkobb095f42020-02-20 16:37:59 +010011913# if ENABLE_HUSH_TRAP
11914 if (argv[1]) { /* "return ARG" inside a running trap sets $? */
11915 debug_printf_exec("G.return_exitcode=%d\n", rc);
11916 G.return_exitcode = rc;
11917 }
11918# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011919 return rc;
11920}
11921#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011922
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011923#if ENABLE_HUSH_TIMES
11924static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11925{
11926 static const uint8_t times_tbl[] ALIGN1 = {
11927 ' ', offsetof(struct tms, tms_utime),
11928 '\n', offsetof(struct tms, tms_stime),
11929 ' ', offsetof(struct tms, tms_cutime),
11930 '\n', offsetof(struct tms, tms_cstime),
11931 0
11932 };
11933 const uint8_t *p;
11934 unsigned clk_tck;
11935 struct tms buf;
11936
11937 clk_tck = bb_clk_tck();
11938
11939 times(&buf);
11940 p = times_tbl;
11941 do {
11942 unsigned sec, frac;
11943 unsigned long t;
11944 t = *(clock_t *)(((char *) &buf) + p[1]);
11945 sec = t / clk_tck;
11946 frac = t % clk_tck;
11947 printf("%um%u.%03us%c",
11948 sec / 60, sec % 60,
11949 (frac * 1000) / clk_tck,
11950 p[0]);
11951 p += 2;
11952 } while (*p);
11953
11954 return EXIT_SUCCESS;
11955}
11956#endif
11957
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011958#if ENABLE_HUSH_MEMLEAK
11959static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11960{
11961 void *p;
11962 unsigned long l;
11963
11964# ifdef M_TRIM_THRESHOLD
11965 /* Optional. Reduces probability of false positives */
11966 malloc_trim(0);
11967# endif
11968 /* Crude attempt to find where "free memory" starts,
11969 * sans fragmentation. */
11970 p = malloc(240);
11971 l = (unsigned long)p;
11972 free(p);
11973 p = malloc(3400);
11974 if (l < (unsigned long)p) l = (unsigned long)p;
11975 free(p);
11976
11977
11978# if 0 /* debug */
11979 {
11980 struct mallinfo mi = mallinfo();
11981 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11982 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11983 }
11984# endif
11985
11986 if (!G.memleak_value)
11987 G.memleak_value = l;
11988
11989 l -= G.memleak_value;
11990 if ((long)l < 0)
11991 l = 0;
11992 l /= 1024;
11993 if (l > 127)
11994 l = 127;
11995
11996 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11997 return l;
11998}
11999#endif