blob: b8af1b088ed81a5aee1858549496feec69cfd057 [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)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenko3632cb12018-04-10 15:25:41 +020082 *
83 * Status of [[ support:
84 * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
85 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
Denys Vlasenko89e9d552018-04-11 01:15:33 +020086 * [[ /bin/n* ]]; echo 0:$?
Denys Vlasenko3632cb12018-04-10 15:25:41 +020087 * TODO:
88 * &&/|| are AND/OR ops, -a/-o are not
89 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
90 * = is glob match operator, not equality operator: STR = GLOB
91 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
92 * == same as =
93 * add =~ regex match operator: STR =~ REGEX
Eric Andersen25f27032001-04-26 23:22:31 +000094 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020095//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020096//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config: default y
98//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020099//config: hush is a small shell. It handles the normal flow control
100//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
101//config: case/esac. Redirections, here documents, $((arithmetic))
102//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200104//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It does not handle select, aliases, tilde expansion,
107//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200108//config:
109//config:config HUSH_BASH_COMPAT
110//config: bool "bash-compatible extensions"
111//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100112//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200114//config:config HUSH_BRACE_EXPANSION
115//config: bool "Brace expansion"
116//config: default y
117//config: depends on HUSH_BASH_COMPAT
118//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200119//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100121//config:config HUSH_LINENO_VAR
122//config: bool "$LINENO variable"
123//config: default y
124//config: depends on HUSH_BASH_COMPAT
125//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100126//config:config HUSH_BASH_SOURCE_CURDIR
127//config: bool "'source' and '.' builtins search current directory after $PATH"
128//config: default n # do not encourage non-standard behavior
129//config: depends on HUSH_BASH_COMPAT
130//config: help
131//config: This is not compliant with standards. Avoid if possible.
132//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200133//config:config HUSH_INTERACTIVE
134//config: bool "Interactive mode"
135//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100136//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200138//config: Enable interactive mode (prompt and command editing).
139//config: Without this, hush simply reads and executes commands
140//config: from stdin just like a shell script from a file.
141//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200143//config:config HUSH_SAVEHISTORY
144//config: bool "Save command history to .hush_history"
145//config: default y
146//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200147//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:config HUSH_JOB
149//config: bool "Job control"
150//config: default y
151//config: depends on HUSH_INTERACTIVE
152//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200153//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
154//config: command (not entire shell), fg/bg builtins work. Without this option,
155//config: "cmd &" still works by simply spawning a process and immediately
156//config: prompting for next command (or executing next command in a script),
157//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config:
159//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100160//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100162//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200164//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_IF
167//config: bool "Support if/then/elif/else/fi"
168//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100169//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200170//config:
171//config:config HUSH_LOOPS
172//config: bool "Support for, while and until loops"
173//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100174//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200175//config:
176//config:config HUSH_CASE
177//config: bool "Support case ... esac statement"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200181//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:
183//config:config HUSH_FUNCTIONS
184//config: bool "Support funcname() { commands; } syntax"
185//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100186//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200187//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200188//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
190//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100191//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200192//config: default y
193//config: depends on HUSH_FUNCTIONS
194//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200195//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200196//config:
197//config:config HUSH_RANDOM_SUPPORT
198//config: bool "Pseudorandom generator and $RANDOM variable"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200202//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
203//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100213//config:config HUSH_ECHO
214//config: bool "echo builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100217//config:
218//config:config HUSH_PRINTF
219//config: bool "printf builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100223//config:config HUSH_TEST
224//config: bool "test builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100228//config:config HUSH_HELP
229//config: bool "help builtin"
230//config: default y
231//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100232//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100233//config:config HUSH_EXPORT
234//config: bool "export builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100237//config:
238//config:config HUSH_EXPORT_N
239//config: bool "Support 'export -n' option"
240//config: default y
241//config: depends on HUSH_EXPORT
242//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200243//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100244//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:config HUSH_READONLY
246//config: bool "readonly builtin"
247//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200248//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200249//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200250//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100252//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100253//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config:
257//config:config HUSH_WAIT
258//config: bool "wait builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100261//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100262//config:config HUSH_COMMAND
263//config: bool "command builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100267//config:config HUSH_TRAP
268//config: bool "trap builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:
272//config:config HUSH_TYPE
273//config: bool "type builtin"
274//config: default y
275//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100276//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200277//config:config HUSH_TIMES
278//config: bool "times builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100282//config:config HUSH_READ
283//config: bool "read builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100286//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100287//config:config HUSH_SET
288//config: bool "set builtin"
289//config: default y
290//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100291//config:
292//config:config HUSH_UNSET
293//config: bool "unset builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100296//config:
297//config:config HUSH_ULIMIT
298//config: bool "ulimit builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100301//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100302//config:config HUSH_UMASK
303//config: bool "umask builtin"
304//config: default y
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100306//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200307//config:config HUSH_GETOPTS
308//config: bool "getopts builtin"
309//config: default y
310//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
311//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100312//config:config HUSH_MEMLEAK
313//config: bool "memleak builtin (debugging)"
314//config: default n
315//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200316
Denys Vlasenko20704f02011-03-23 17:59:27 +0100317//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100318// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100319//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100320//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100321
322//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100323//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
324//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100325//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
326
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200327/* -i (interactive) is also accepted,
328 * but does nothing, therefore not shown in help.
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329 * NOMMU-specific options are not meant to be used by users,
330 * therefore we don't show them either.
331 */
332//usage:#define hush_trivial_usage
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +0200333//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100334//usage:#define hush_full_usage "\n\n"
335//usage: "Unix shell interpreter"
336
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
338 || defined(__APPLE__) \
339 )
340# include <malloc.h> /* for malloc_trim */
341#endif
342#include <glob.h>
343/* #include <dmalloc.h> */
344#if ENABLE_HUSH_CASE
345# include <fnmatch.h>
346#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200347#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100348#include <sys/utsname.h> /* for setting $HOSTNAME */
349
350#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
351#include "unicode.h"
352#include "shell_common.h"
353#include "math.h"
354#include "match.h"
355#if ENABLE_HUSH_RANDOM_SUPPORT
356# include "random.h"
357#else
358# define CLEAR_RANDOM_T(rnd) ((void)0)
359#endif
360#ifndef F_DUPFD_CLOEXEC
361# define F_DUPFD_CLOEXEC F_DUPFD
362#endif
363#ifndef PIPE_BUF
364# define PIPE_BUF 4096 /* amount of buffering in a pipe */
365#endif
366
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000367
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100368/* So far, all bash compat is controlled by one config option */
369/* Separate defines document which part of code implements what */
370#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
371#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100372#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
373#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200374#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200375#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100376
377
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200378/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000379#define LEAK_HUNTING 0
380#define BUILD_AS_NOMMU 0
381/* Enable/disable sanity checks. Ok to enable in production,
382 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
383 * Keeping 1 for now even in released versions.
384 */
385#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200386/* Slightly bigger (+200 bytes), but faster hush.
387 * So far it only enables a trick with counting SIGCHLDs and forks,
388 * which allows us to do fewer waitpid's.
389 * (we can detect a case where neither forks were done nor SIGCHLDs happened
390 * and therefore waitpid will return the same result as last time)
391 */
392#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200393/* TODO: implement simplified code for users which do not need ${var%...} ops
394 * So far ${var%...} ops are always enabled:
395 */
396#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000397
398
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000399#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000400# undef BB_MMU
401# undef USE_FOR_NOMMU
402# undef USE_FOR_MMU
403# define BB_MMU 0
404# define USE_FOR_NOMMU(...) __VA_ARGS__
405# define USE_FOR_MMU(...)
406#endif
407
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200408#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100409#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000410/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000411# undef CONFIG_FEATURE_SH_STANDALONE
412# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000413# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100414# undef IF_NOT_FEATURE_SH_STANDALONE
415# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000416# define IF_FEATURE_SH_STANDALONE(...)
417# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000418#endif
419
Denis Vlasenko05743d72008-02-10 12:10:08 +0000420#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000421# undef ENABLE_FEATURE_EDITING
422# define ENABLE_FEATURE_EDITING 0
423# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
424# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200425# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
426# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000427#endif
428
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000429/* Do we support ANY keywords? */
430#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000431# define HAS_KEYWORDS 1
432# define IF_HAS_KEYWORDS(...) __VA_ARGS__
433# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000434#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000435# define HAS_KEYWORDS 0
436# define IF_HAS_KEYWORDS(...)
437# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000438#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000439
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000440/* If you comment out one of these below, it will be #defined later
441 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000442#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000443/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000444#define debug_printf_parse(...) do {} while (0)
445#define debug_print_tree(a, b) do {} while (0)
446#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000447#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000448#define debug_printf_jobs(...) do {} while (0)
449#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200450#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000451#define debug_printf_glob(...) do {} while (0)
Denys Vlasenko2db74612017-07-07 22:07:28 +0200452#define debug_printf_redir(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000453#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000454#define debug_printf_subst(...) do {} while (0)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200455#define debug_printf_prompt(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000456#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000457
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000458#define ERR_PTR ((void*)(long)1)
459
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100460#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000461
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200462#define _SPECIAL_VARS_STR "_*@$!?#"
463#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
464#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100465#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200466/* Support / and // replace ops */
467/* Note that // is stored as \ in "encoded" string representation */
468# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
469# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
470# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
471#else
472# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
473# define VAR_SUBST_OPS "%#:-=+?"
474# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
475#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200476
Denys Vlasenko932b9972018-01-11 12:39:48 +0100477#define SPECIAL_VAR_SYMBOL_STR "\3"
Denys Vlasenko18e8b612018-07-20 14:24:56 +0200478#define SPECIAL_VAR_SYMBOL_CHR '\3'
Denys Vlasenko932b9972018-01-11 12:39:48 +0100479#define SPECIAL_VAR_SYMBOL 3
480/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
481#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000482
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200483struct variable;
484
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000485static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
486
487/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000488 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000489 */
490#if !BB_MMU
491typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200492 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000493 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000494 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000495} nommu_save_t;
496#endif
497
Denys Vlasenko9b782552010-09-08 13:33:26 +0200498enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000499 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000500#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000501 RES_IF ,
502 RES_THEN ,
503 RES_ELIF ,
504 RES_ELSE ,
505 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000506#endif
507#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000508 RES_FOR ,
509 RES_WHILE ,
510 RES_UNTIL ,
511 RES_DO ,
512 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000513#endif
514#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000515 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000516#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000517#if ENABLE_HUSH_CASE
518 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200519 /* three pseudo-keywords support contrived "case" syntax: */
520 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
521 RES_MATCH , /* "word)" */
522 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000523 RES_ESAC ,
524#endif
525 RES_XXXX ,
526 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200527};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000528
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000529typedef struct o_string {
530 char *data;
531 int length; /* position where data is appended */
532 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200533 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000534 /* At least some part of the string was inside '' or "",
535 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200536 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000537 smallint has_empty_slot;
Denys Vlasenko168579a2018-07-19 13:45:54 +0200538 smallint ended_in_ifs;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000539} o_string;
540enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200541 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
542 EXP_FLAG_GLOB = 0x2,
543 /* Protect newly added chars against globbing
544 * by prepending \ to *, ?, [, \ */
545 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
546};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000547/* Used for initialization: o_string foo = NULL_O_STRING; */
548#define NULL_O_STRING { NULL }
549
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200550#ifndef debug_printf_parse
551static const char *const assignment_flag[] = {
552 "MAYBE_ASSIGNMENT",
553 "DEFINITELY_ASSIGNMENT",
554 "NOT_ASSIGNMENT",
555 "WORD_IS_KEYWORD",
556};
557#endif
558
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000559typedef struct in_str {
560 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200561 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200562 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000564} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000565
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200566/* The descrip member of this structure is only used to make
567 * debugging output pretty */
568static const struct {
569 int mode;
570 signed char default_fd;
571 char descrip[3];
572} redir_table[] = {
573 { O_RDONLY, 0, "<" },
574 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
575 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
576 { O_CREAT|O_RDWR, 1, "<>" },
577 { O_RDONLY, 0, "<<" },
578/* Should not be needed. Bogus default_fd helps in debugging */
579/* { O_RDONLY, 77, "<<" }, */
580};
581
Eric Andersen25f27032001-04-26 23:22:31 +0000582struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000583 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000584 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000585 int rd_fd; /* fd to redirect */
586 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
587 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000588 smallint rd_type; /* (enum redir_type) */
589 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000590 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200591 * bit 0: do we need to trim leading tabs?
592 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000593 */
Eric Andersen25f27032001-04-26 23:22:31 +0000594};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000595typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200596 REDIRECT_INPUT = 0,
597 REDIRECT_OVERWRITE = 1,
598 REDIRECT_APPEND = 2,
599 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000600 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200601 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000602
603 REDIRFD_CLOSE = -3,
604 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000605 REDIRFD_TO_FILE = -1,
606 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000607
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000608 HEREDOC_SKIPTABS = 1,
609 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000610} redir_type;
611
Eric Andersen25f27032001-04-26 23:22:31 +0000612
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000613struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000614 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200615 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100616#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100617 unsigned lineno;
618#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200619 smallint cmd_type; /* CMD_xxx */
620#define CMD_NORMAL 0
621#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200622#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
623/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
624 * "export v=t*"
625 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200626# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000627#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200628#if ENABLE_HUSH_FUNCTIONS
629# define CMD_FUNCDEF 3
630#endif
631
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100632 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200633 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
634 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000635#if !BB_MMU
636 char *group_as_string;
637#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000638#if ENABLE_HUSH_FUNCTIONS
639 struct function *child_func;
640/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200641 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000642 * When we execute "f1() {a;}" cmd, we create new function and clear
643 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200644 * When we execute "f1() {b;}", we notice that f1 exists,
645 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000646 * we put those fields back into cmd->xxx
647 * (struct function has ->parent_cmd ptr to facilitate that).
648 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
649 * Without this trick, loop would execute a;b;b;b;...
650 * instead of correct sequence a;b;a;b;...
651 * When command is freed, it severs the link
652 * (sets ->child_func->parent_cmd to NULL).
653 */
654#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000655 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000656/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
657 * and on execution these are substituted with their values.
658 * Substitution can make _several_ words out of one argv[n]!
659 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000660 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000661 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000662 struct redir_struct *redirects; /* I/O redirections */
663};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000664/* Is there anything in this command at all? */
665#define IS_NULL_CMD(cmd) \
666 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
667
Eric Andersen25f27032001-04-26 23:22:31 +0000668struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000669 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000670 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000671 int alive_cmds; /* number of commands running (not exited) */
672 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000673#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100674 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000675 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000676 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000677#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000678 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000679 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000680 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
681 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000682};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000683typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100684 PIPE_SEQ = 0,
685 PIPE_AND = 1,
686 PIPE_OR = 2,
687 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000688} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000689/* Is there anything in this pipe at all? */
690#define IS_NULL_PIPE(pi) \
691 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000692
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000693/* This holds pointers to the various results of parsing */
694struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000695 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000696 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000697 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000698 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000699 /* last command in pipe (being constructed right now) */
700 struct command *command;
701 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000702 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200703 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000704#if !BB_MMU
705 o_string as_string;
706#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200707 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000708#if HAS_KEYWORDS
709 smallint ctx_res_w;
710 smallint ctx_inverted; /* "! cmd | cmd" */
711#if ENABLE_HUSH_CASE
712 smallint ctx_dsemicolon; /* ";;" seen */
713#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000714 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
715 int old_flag;
716 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000717 * example: "if pipe1; pipe2; then pipe3; fi"
718 * when we see "if" or "then", we malloc and copy current context,
719 * and make ->stack point to it. then we parse pipeN.
720 * when closing "then" / fi" / whatever is found,
721 * we move list_head into ->stack->command->group,
722 * copy ->stack into current context, and delete ->stack.
723 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000724 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000725 struct parse_context *stack;
726#endif
727};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200728enum {
729 MAYBE_ASSIGNMENT = 0,
730 DEFINITELY_ASSIGNMENT = 1,
731 NOT_ASSIGNMENT = 2,
732 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
733 WORD_IS_KEYWORD = 3,
734};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000735
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000736/* On program start, environ points to initial environment.
737 * putenv adds new pointers into it, unsetenv removes them.
738 * Neither of these (de)allocates the strings.
739 * setenv allocates new strings in malloc space and does putenv,
740 * and thus setenv is unusable (leaky) for shell's purposes */
741#define setenv(...) setenv_is_leaky_dont_use()
742struct variable {
743 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000744 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000745 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200746 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000747 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000748 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000749};
750
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000751enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000752 BC_BREAK = 1,
753 BC_CONTINUE = 2,
754};
755
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000756#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000757struct function {
758 struct function *next;
759 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000760 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000761 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200762# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000763 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200764# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000765};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000766#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000767
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000768
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100769/* set -/+o OPT support. (TODO: make it optional)
770 * bash supports the following opts:
771 * allexport off
772 * braceexpand on
773 * emacs on
774 * errexit off
775 * errtrace off
776 * functrace off
777 * hashall on
778 * histexpand off
779 * history on
780 * ignoreeof off
781 * interactive-comments on
782 * keyword off
783 * monitor on
784 * noclobber off
785 * noexec off
786 * noglob off
787 * nolog off
788 * notify off
789 * nounset off
790 * onecmd off
791 * physical off
792 * pipefail off
793 * posix off
794 * privileged off
795 * verbose off
796 * vi off
797 * xtrace off
798 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800799static const char o_opt_strings[] ALIGN1 =
800 "pipefail\0"
801 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200802 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800803#if ENABLE_HUSH_MODE_X
804 "xtrace\0"
805#endif
806 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100807enum {
808 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800809 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200810 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800811#if ENABLE_HUSH_MODE_X
812 OPT_O_XTRACE,
813#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100814 NUM_OPT_O
815};
816
817
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200818struct FILE_list {
819 struct FILE_list *next;
820 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200821 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200822};
823
824
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000825/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000826/* Sorted roughly by size (smaller offsets == smaller code) */
827struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000828 /* interactive_fd != 0 means we are an interactive shell.
829 * If we are, then saved_tty_pgrp can also be != 0, meaning
830 * that controlling tty is available. With saved_tty_pgrp == 0,
831 * job control still works, but terminal signals
832 * (^C, ^Z, ^Y, ^\) won't work at all, and background
833 * process groups can only be created with "cmd &".
834 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
835 * to give tty to the foreground process group,
836 * and will take it back when the group is stopped (^Z)
837 * or killed (^C).
838 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000839#if ENABLE_HUSH_INTERACTIVE
840 /* 'interactive_fd' is a fd# open to ctty, if we have one
841 * _AND_ if we decided to act interactively */
842 int interactive_fd;
843 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200844 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000845# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000846#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000847# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000848#endif
849#if ENABLE_FEATURE_EDITING
850 line_input_t *line_input_state;
851#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000852 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200853 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000854 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200855#if ENABLE_HUSH_RANDOM_SUPPORT
856 random_t random_gen;
857#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000858#if ENABLE_HUSH_JOB
859 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100860 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000861 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000862 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400863# define G_saved_tty_pgrp (G.saved_tty_pgrp)
864#else
865# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000866#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200867 /* How deeply are we in context where "set -e" is ignored */
868 int errexit_depth;
869 /* "set -e" rules (do we follow them correctly?):
870 * Exit if pipe, list, or compound command exits with a non-zero status.
871 * Shell does not exit if failed command is part of condition in
872 * if/while, part of && or || list except the last command, any command
873 * in a pipe but the last, or if the command's return value is being
874 * inverted with !. If a compound command other than a subshell returns a
875 * non-zero status because a command failed while -e was being ignored, the
876 * shell does not exit. A trap on ERR, if set, is executed before the shell
877 * exits [ERR is a bashism].
878 *
879 * If a compound command or function executes in a context where -e is
880 * ignored, none of the commands executed within are affected by the -e
881 * setting. If a compound command or function sets -e while executing in a
882 * context where -e is ignored, that setting does not have any effect until
883 * the compound command or the command containing the function call completes.
884 */
885
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100886 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100887#if ENABLE_HUSH_MODE_X
888# define G_x_mode (G.o_opt[OPT_O_XTRACE])
889#else
890# define G_x_mode 0
891#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200892#if ENABLE_HUSH_INTERACTIVE
893 smallint promptmode; /* 0: PS1, 1: PS2 */
894#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000895 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000896#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000897 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000898#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000899#if ENABLE_HUSH_FUNCTIONS
900 /* 0: outside of a function (or sourced file)
901 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000902 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000903 */
904 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200905# define G_flag_return_in_progress (G.flag_return_in_progress)
906#else
907# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000908#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000909 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200910 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000911 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200912 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200913 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100914#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000915 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000916 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100917# define G_global_args_malloced (G.global_args_malloced)
918#else
919# define G_global_args_malloced 0
920#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000921 /* how many non-NULL argv's we have. NB: $# + 1 */
922 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000923 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000924#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000925 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000926#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000927#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000928 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000929 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000930#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200931#if ENABLE_HUSH_GETOPTS
932 unsigned getopt_count;
933#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000934 const char *ifs;
Denys Vlasenko96786362018-04-11 16:02:58 +0200935 char *ifs_whitespace; /* = G.ifs or malloced */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000936 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200937 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200938 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200939 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200940 unsigned var_nest_level;
941#if ENABLE_HUSH_FUNCTIONS
942# if ENABLE_HUSH_LOCAL
943 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200944# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200945 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000946#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000947 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200948#if ENABLE_HUSH_FAST
949 unsigned count_SIGCHLD;
950 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200951 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200952#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100953#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100954 unsigned lineno;
955 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100956#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200957 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200958 /* Which signals have non-DFL handler (even with no traps set)?
959 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200960 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200961 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200962 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200963 * Other than these two times, never modified.
964 */
965 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200966#if ENABLE_HUSH_JOB
967 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100968# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200969#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200970# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200971#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100972#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000973 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100974# define G_traps G.traps
975#else
976# define G_traps ((char**)NULL)
977#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200978 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100979#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000980 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100981#endif
982#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000983 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000984#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200985 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200986#if ENABLE_FEATURE_EDITING
987 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
988#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000989};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000990#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000991/* Not #defining name to G.name - this quickly gets unwieldy
992 * (too many defines). Also, I actually prefer to see when a variable
993 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000994#define INIT_G() do { \
995 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200996 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
997 sigfillset(&G.sa.sa_mask); \
998 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000999} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001000
1001
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001002/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001003static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001004#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001005static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001006#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001007static int builtin_eval(char **argv) FAST_FUNC;
1008static int builtin_exec(char **argv) FAST_FUNC;
1009static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001010#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001011static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001012#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001013#if ENABLE_HUSH_READONLY
1014static int builtin_readonly(char **argv) FAST_FUNC;
1015#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001016#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001017static int builtin_fg_bg(char **argv) FAST_FUNC;
1018static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001019#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001020#if ENABLE_HUSH_GETOPTS
1021static int builtin_getopts(char **argv) FAST_FUNC;
1022#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001023#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001024static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001025#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001026#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001027static int builtin_history(char **argv) FAST_FUNC;
1028#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001029#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001030static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001031#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001032#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001033static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001034#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001035#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001036static int builtin_printf(char **argv) FAST_FUNC;
1037#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001038static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001039#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001040static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001041#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001042#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001043static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001044#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001045static int builtin_shift(char **argv) FAST_FUNC;
1046static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001047#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001048static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001049#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001050#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001051static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001052#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001053#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001055#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001056#if ENABLE_HUSH_TIMES
1057static int builtin_times(char **argv) FAST_FUNC;
1058#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001059static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001060#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001061static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001062#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001063#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001064static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001065#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001066#if ENABLE_HUSH_KILL
1067static int builtin_kill(char **argv) FAST_FUNC;
1068#endif
1069#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001070static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001071#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001072#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001073static int builtin_break(char **argv) FAST_FUNC;
1074static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001075#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001076#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001077static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001078#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001079
1080/* Table of built-in functions. They can be forked or not, depending on
1081 * context: within pipes, they fork. As simple commands, they do not.
1082 * When used in non-forking context, they can change global variables
1083 * in the parent shell process. If forked, of course they cannot.
1084 * For example, 'unset foo | whatever' will parse and run, but foo will
1085 * still be set at the end. */
1086struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001087 const char *b_cmd;
1088 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001089#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001090 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001091# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001092#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001093# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001094#endif
1095};
1096
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001097static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001098 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001099 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001100#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001101 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001102#endif
1103#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001104 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001105#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001106 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001107#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001108 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001109#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001110 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1111 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001112 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001113#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001114 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001115#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001116#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001117 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001118#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001119#if ENABLE_HUSH_GETOPTS
1120 BLTIN("getopts" , builtin_getopts , NULL),
1121#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001122#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001123 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001124#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001125#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001126 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001127#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001128#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001129 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001130#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001131#if ENABLE_HUSH_KILL
1132 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1133#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001134#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001135 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001136#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001137#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001138 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001139#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001140#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001141 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001142#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001143#if ENABLE_HUSH_READONLY
1144 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1145#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001146#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001147 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001148#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001149#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001150 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001151#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001152 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001153#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001154 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001155#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001156#if ENABLE_HUSH_TIMES
1157 BLTIN("times" , builtin_times , NULL),
1158#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001159#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001160 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001161#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001162 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001163#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001164 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001165#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001166#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001167 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001168#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001169#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001171#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001172#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001173 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001174#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001175#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001176 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001177#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001178};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001179/* These builtins won't be used if we are on NOMMU and need to re-exec
1180 * (it's cheaper to run an external program in this case):
1181 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001182static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001183#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001184 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001185#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001186#if BASH_TEST2
1187 BLTIN("[[" , builtin_test , NULL),
1188#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001189#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001190 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001191#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001192#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001193 BLTIN("printf" , builtin_printf , NULL),
1194#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001195 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001196#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001197 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001198#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001199};
1200
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001201
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001202/* Debug printouts.
1203 */
1204#if HUSH_DEBUG
1205/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001206# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001207# define debug_enter() (G.debug_indent++)
1208# define debug_leave() (G.debug_indent--)
1209#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001210# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001211# define debug_enter() ((void)0)
1212# define debug_leave() ((void)0)
1213#endif
1214
1215#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001216# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001217#endif
1218
1219#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001220# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001221#endif
1222
1223#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001224#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001225#endif
1226
1227#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001228# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001229#endif
1230
1231#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001232# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001233# define DEBUG_JOBS 1
1234#else
1235# define DEBUG_JOBS 0
1236#endif
1237
1238#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001239# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001240# define DEBUG_EXPAND 1
1241#else
1242# define DEBUG_EXPAND 0
1243#endif
1244
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001245#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001246# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001247#endif
1248
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001249#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001250# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001251# define DEBUG_GLOB 1
1252#else
1253# define DEBUG_GLOB 0
1254#endif
1255
Denys Vlasenko2db74612017-07-07 22:07:28 +02001256#ifndef debug_printf_redir
1257# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1258#endif
1259
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001260#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001261# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001262#endif
1263
1264#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001265# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001266#endif
1267
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001268#ifndef debug_printf_prompt
1269# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1270#endif
1271
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001272#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001273# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001274# define DEBUG_CLEAN 1
1275#else
1276# define DEBUG_CLEAN 0
1277#endif
1278
1279#if DEBUG_EXPAND
1280static void debug_print_strings(const char *prefix, char **vv)
1281{
1282 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001283 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001284 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001285 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001286}
1287#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001288# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001289#endif
1290
1291
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001292/* Leak hunting. Use hush_leaktool.sh for post-processing.
1293 */
1294#if LEAK_HUNTING
1295static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001296{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001297 void *ptr = xmalloc((size + 0xff) & ~0xff);
1298 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1299 return ptr;
1300}
1301static void *xxrealloc(int lineno, void *ptr, size_t size)
1302{
1303 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1304 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1305 return ptr;
1306}
1307static char *xxstrdup(int lineno, const char *str)
1308{
1309 char *ptr = xstrdup(str);
1310 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1311 return ptr;
1312}
1313static void xxfree(void *ptr)
1314{
1315 fdprintf(2, "free %p\n", ptr);
1316 free(ptr);
1317}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001318# define xmalloc(s) xxmalloc(__LINE__, s)
1319# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1320# define xstrdup(s) xxstrdup(__LINE__, s)
1321# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001322#endif
1323
1324
1325/* Syntax and runtime errors. They always abort scripts.
1326 * In interactive use they usually discard unparsed and/or unexecuted commands
1327 * and return to the prompt.
1328 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1329 */
1330#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001331# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001332# define syntax_error(lineno, msg) syntax_error(msg)
1333# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1334# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1335# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1336# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001337#endif
1338
Denys Vlasenko39701202017-08-02 19:44:05 +02001339static void die_if_script(void)
1340{
1341 if (!G_interactive_fd) {
1342 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1343 xfunc_error_retval = G.last_exitcode;
1344 xfunc_die();
1345 }
1346}
1347
1348static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001349{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001350 va_list p;
1351
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001352#if HUSH_DEBUG >= 2
1353 bb_error_msg("hush.c:%u", lineno);
1354#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001355 va_start(p, fmt);
1356 bb_verror_msg(fmt, p, NULL);
1357 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001358 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001359}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001360
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001361static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001362{
1363 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001364 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001365 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001366 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001367 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001368}
1369
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001370static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001371{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001372 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001373 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001374}
1375
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001376static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001377{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001378 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001379//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1380// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001381}
1382
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001383static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001384{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001385 char msg[2] = { ch, '\0' };
1386 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001387}
1388
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001389static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001390{
1391 char msg[2];
1392 msg[0] = ch;
1393 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001394#if HUSH_DEBUG >= 2
1395 bb_error_msg("hush.c:%u", lineno);
1396#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001397 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001398 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001399}
1400
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001401#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001402# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001403# undef syntax_error
1404# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001405# undef syntax_error_unterm_ch
1406# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001407# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001408#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001409# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001410# define syntax_error(msg) syntax_error(__LINE__, msg)
1411# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1412# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1413# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1414# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001415#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001416
Denis Vlasenko552433b2009-04-04 19:29:21 +00001417
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001418#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001419static void cmdedit_update_prompt(void);
1420#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001421# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001422#endif
1423
1424
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001425/* Utility functions
1426 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001427/* Replace each \x with x in place, return ptr past NUL. */
1428static char *unbackslash(char *src)
1429{
Denys Vlasenko71885402009-09-24 01:44:13 +02001430 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001431 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001432 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001433 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001434 if (*src != '\0') {
1435 /* \x -> x */
1436 *dst++ = *src++;
1437 continue;
1438 }
1439 /* else: "\<nul>". Do not delete this backslash.
1440 * Testcase: eval 'echo ok\'
1441 */
1442 *dst++ = '\\';
1443 /* fallthrough */
1444 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001445 if ((*dst++ = *src++) == '\0')
1446 break;
1447 }
1448 return dst;
1449}
1450
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001451static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001452{
1453 int i;
1454 unsigned count1;
1455 unsigned count2;
1456 char **v;
1457
1458 v = strings;
1459 count1 = 0;
1460 if (v) {
1461 while (*v) {
1462 count1++;
1463 v++;
1464 }
1465 }
1466 count2 = 0;
1467 v = add;
1468 while (*v) {
1469 count2++;
1470 v++;
1471 }
1472 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1473 v[count1 + count2] = NULL;
1474 i = count2;
1475 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001476 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001477 return v;
1478}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001479#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001480static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1481{
1482 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1483 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1484 return ptr;
1485}
1486#define add_strings_to_strings(strings, add, need_to_dup) \
1487 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1488#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001489
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001490/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001491static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001492{
1493 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001494 v[0] = add;
1495 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001496 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001497}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001498#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001499static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1500{
1501 char **ptr = add_string_to_strings(strings, add);
1502 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1503 return ptr;
1504}
1505#define add_string_to_strings(strings, add) \
1506 xx_add_string_to_strings(__LINE__, strings, add)
1507#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001508
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001509static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001510{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001511 char **v;
1512
1513 if (!strings)
1514 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001515 v = strings;
1516 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001517 free(*v);
1518 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001519 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001520 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001521}
1522
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001523static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001524{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001525 int newfd;
1526 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001527 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1528 if (newfd >= 0) {
1529 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1530 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1531 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001532 if (errno == EBUSY)
1533 goto repeat;
1534 if (errno == EINTR)
1535 goto repeat;
1536 }
1537 return newfd;
1538}
1539
Denys Vlasenko657e9002017-07-30 23:34:04 +02001540static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001541{
1542 int newfd;
1543 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001544 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001545 if (newfd < 0) {
1546 if (errno == EBUSY)
1547 goto repeat;
1548 if (errno == EINTR)
1549 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001550 /* fd was not open? */
1551 if (errno == EBADF)
1552 return fd;
1553 xfunc_die();
1554 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001555 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1556 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001557 close(fd);
1558 return newfd;
1559}
1560
1561
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001562/* Manipulating the list of open FILEs */
1563static FILE *remember_FILE(FILE *fp)
1564{
1565 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001566 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001567 n->next = G.FILE_list;
1568 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001569 n->fp = fp;
1570 n->fd = fileno(fp);
1571 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001572 }
1573 return fp;
1574}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001575static void fclose_and_forget(FILE *fp)
1576{
1577 struct FILE_list **pp = &G.FILE_list;
1578 while (*pp) {
1579 struct FILE_list *cur = *pp;
1580 if (cur->fp == fp) {
1581 *pp = cur->next;
1582 free(cur);
1583 break;
1584 }
1585 pp = &cur->next;
1586 }
1587 fclose(fp);
1588}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001589static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001590{
1591 struct FILE_list *fl = G.FILE_list;
1592 while (fl) {
1593 if (fd == fl->fd) {
1594 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001595 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001596 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001597 return 1;
1598 }
1599 fl = fl->next;
1600 }
1601 return 0;
1602}
1603static void restore_redirected_FILEs(void)
1604{
1605 struct FILE_list *fl = G.FILE_list;
1606 while (fl) {
1607 int should_be = fileno(fl->fp);
1608 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001609 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001610 xmove_fd(fl->fd, should_be);
1611 fl->fd = should_be;
1612 }
1613 fl = fl->next;
1614 }
1615}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001616#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001617static void close_all_FILE_list(void)
1618{
1619 struct FILE_list *fl = G.FILE_list;
1620 while (fl) {
1621 /* fclose would also free FILE object.
1622 * It is disastrous if we share memory with a vforked parent.
1623 * I'm not sure we never come here after vfork.
1624 * Therefore just close fd, nothing more.
1625 */
1626 /*fclose(fl->fp); - unsafe */
1627 close(fl->fd);
1628 fl = fl->next;
1629 }
1630}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001631#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001632static int fd_in_FILEs(int fd)
1633{
1634 struct FILE_list *fl = G.FILE_list;
1635 while (fl) {
1636 if (fl->fd == fd)
1637 return 1;
1638 fl = fl->next;
1639 }
1640 return 0;
1641}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001642
1643
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001644/* Helpers for setting new $n and restoring them back
1645 */
1646typedef struct save_arg_t {
1647 char *sv_argv0;
1648 char **sv_g_argv;
1649 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001650 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001651} save_arg_t;
1652
1653static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1654{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001655 sv->sv_argv0 = argv[0];
1656 sv->sv_g_argv = G.global_argv;
1657 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001658 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001659
1660 argv[0] = G.global_argv[0]; /* retain $0 */
1661 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001662 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001663
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001664 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001665}
1666
1667static void restore_G_args(save_arg_t *sv, char **argv)
1668{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001669#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001670 if (G.global_args_malloced) {
1671 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001672 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001673 while (*++pp) /* note: does not free $0 */
1674 free(*pp);
1675 free(G.global_argv);
1676 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001677#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001678 argv[0] = sv->sv_argv0;
1679 G.global_argv = sv->sv_g_argv;
1680 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001681 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001682}
1683
1684
Denis Vlasenkod5762932009-03-31 11:22:57 +00001685/* Basic theory of signal handling in shell
1686 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001687 * This does not describe what hush does, rather, it is current understanding
1688 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001689 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1690 *
1691 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1692 * is finished or backgrounded. It is the same in interactive and
1693 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001694 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001695 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001696 * backgrounds (i.e. stops) or kills all members of currently running
1697 * pipe.
1698 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001699 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001700 * or by SIGINT in interactive shell.
1701 *
1702 * Trap handlers will execute even within trap handlers. (right?)
1703 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001704 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1705 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001706 *
1707 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001708 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001709 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001710 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001711 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001712 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001713 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001714 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001715 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001716 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001717 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001718 *
1719 * SIGQUIT: ignore
1720 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001721 * SIGHUP (interactive):
1722 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001723 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001724 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1725 * that all pipe members are stopped. Try this in bash:
1726 * while :; do :; done - ^Z does not background it
1727 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001728 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001729 * of the command line, show prompt. NB: ^C does not send SIGINT
1730 * to interactive shell while shell is waiting for a pipe,
1731 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001732 * Example 1: this waits 5 sec, but does not execute ls:
1733 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1734 * Example 2: this does not wait and does not execute ls:
1735 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1736 * Example 3: this does not wait 5 sec, but executes ls:
1737 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001738 * Example 4: this does not wait and does not execute ls:
1739 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001740 *
1741 * (What happens to signals which are IGN on shell start?)
1742 * (What happens with signal mask on shell start?)
1743 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001744 * Old implementation
1745 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001746 * We use in-kernel pending signal mask to determine which signals were sent.
1747 * We block all signals which we don't want to take action immediately,
1748 * i.e. we block all signals which need to have special handling as described
1749 * above, and all signals which have traps set.
1750 * After each pipe execution, we extract any pending signals via sigtimedwait()
1751 * and act on them.
1752 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001753 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001754 * sigset_t blocked_set: current blocked signal set
1755 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001756 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001757 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001758 * "trap 'cmd' SIGxxx":
1759 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001760 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001761 * unblock signals with special interactive handling
1762 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001763 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001764 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001765 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001766 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001767 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001768 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001769 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001770 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001771 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001772 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001773 * Standard says "When a subshell is entered, traps that are not being ignored
1774 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001775 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001776 *
1777 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001778 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001779 * masked signals are not visible!
1780 *
1781 * New implementation
1782 * ==================
1783 * We record each signal we are interested in by installing signal handler
1784 * for them - a bit like emulating kernel pending signal mask in userspace.
1785 * We are interested in: signals which need to have special handling
1786 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001787 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001788 * After each pipe execution, we extract any pending signals
1789 * and act on them.
1790 *
1791 * unsigned special_sig_mask: a mask of shell-special signals.
1792 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1793 * char *traps[sig] if trap for sig is set (even if it's '').
1794 * sigset_t pending_set: set of sigs we received.
1795 *
1796 * "trap - SIGxxx":
1797 * if sig is in special_sig_mask, set handler back to:
1798 * record_pending_signo, or to IGN if it's a tty stop signal
1799 * if sig is in fatal_sig_mask, set handler back to sigexit.
1800 * else: set handler back to SIG_DFL
1801 * "trap 'cmd' SIGxxx":
1802 * set handler to record_pending_signo.
1803 * "trap '' SIGxxx":
1804 * set handler to SIG_IGN.
1805 * after [v]fork, if we plan to be a shell:
1806 * set signals with special interactive handling to SIG_DFL
1807 * (because child shell is not interactive),
1808 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1809 * after [v]fork, if we plan to exec:
1810 * POSIX says fork clears pending signal mask in child - no need to clear it.
1811 *
1812 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1813 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1814 *
1815 * Note (compat):
1816 * Standard says "When a subshell is entered, traps that are not being ignored
1817 * are set to the default actions". bash interprets it so that traps which
1818 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001819 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001820enum {
1821 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001822 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001823 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001824 | (1 << SIGHUP)
1825 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001826 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001827#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001828 | (1 << SIGTTIN)
1829 | (1 << SIGTTOU)
1830 | (1 << SIGTSTP)
1831#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001832 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001833};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001834
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001835static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001836{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001837 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001838#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001839 if (sig == SIGCHLD) {
1840 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001841//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 +02001842 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001843#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001844}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001845
Denys Vlasenko0806e402011-05-12 23:06:20 +02001846static sighandler_t install_sighandler(int sig, sighandler_t handler)
1847{
1848 struct sigaction old_sa;
1849
1850 /* We could use signal() to install handlers... almost:
1851 * except that we need to mask ALL signals while handlers run.
1852 * I saw signal nesting in strace, race window isn't small.
1853 * SA_RESTART is also needed, but in Linux, signal()
1854 * sets SA_RESTART too.
1855 */
1856 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1857 /* sigfillset(&G.sa.sa_mask); - already done */
1858 /* G.sa.sa_flags = SA_RESTART; - already done */
1859 G.sa.sa_handler = handler;
1860 sigaction(sig, &G.sa, &old_sa);
1861 return old_sa.sa_handler;
1862}
1863
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001864static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001865
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001866static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001867static void restore_ttypgrp_and__exit(void)
1868{
1869 /* xfunc has failed! die die die */
1870 /* no EXIT traps, this is an escape hatch! */
1871 G.exiting = 1;
1872 hush_exit(xfunc_error_retval);
1873}
1874
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001875#if ENABLE_HUSH_JOB
1876
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001877/* Needed only on some libc:
1878 * It was observed that on exit(), fgetc'ed buffered data
1879 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1880 * With the net effect that even after fork(), not vfork(),
1881 * exit() in NOEXECed applet in "sh SCRIPT":
1882 * noexec_applet_here
1883 * echo END_OF_SCRIPT
1884 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1885 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001886 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001887 * and in `cmd` handling.
1888 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1889 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001890static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001891static void fflush_and__exit(void)
1892{
1893 fflush_all();
1894 _exit(xfunc_error_retval);
1895}
1896
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001897/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001898# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001899/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001900# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001901
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001902/* Restores tty foreground process group, and exits.
1903 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001904 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001905 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001906 * We also call it if xfunc is exiting.
1907 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001908static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001909static void sigexit(int sig)
1910{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001911 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001912 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001913 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1914 /* Disable all signals: job control, SIGPIPE, etc.
1915 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1916 */
1917 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001918 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001919 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001920
1921 /* Not a signal, just exit */
1922 if (sig <= 0)
1923 _exit(- sig);
1924
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001925 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001926}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001927#else
1928
Denys Vlasenko8391c482010-05-22 17:50:43 +02001929# define disable_restore_tty_pgrp_on_exit() ((void)0)
1930# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001931
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001932#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001933
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001934static sighandler_t pick_sighandler(unsigned sig)
1935{
1936 sighandler_t handler = SIG_DFL;
1937 if (sig < sizeof(unsigned)*8) {
1938 unsigned sigmask = (1 << sig);
1939
1940#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001941 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001942 if (G_fatal_sig_mask & sigmask)
1943 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001944 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001945#endif
1946 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001947 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001948 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001949 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001950 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001951 * in an endless loop when we try to do some
1952 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001953 */
1954 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1955 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001956 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001957 }
1958 return handler;
1959}
1960
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001961/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001962static void hush_exit(int exitcode)
1963{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001964#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1965 save_history(G.line_input_state);
1966#endif
1967
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001968 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001969 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001970 char *argv[3];
1971 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001972 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001973 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001974 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001975 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001976 * "trap" will still show it, if executed
1977 * in the handler */
1978 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001979 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001980
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001981#if ENABLE_FEATURE_CLEAN_UP
1982 {
1983 struct variable *cur_var;
1984 if (G.cwd != bb_msg_unknown)
1985 free((char*)G.cwd);
1986 cur_var = G.top_var;
1987 while (cur_var) {
1988 struct variable *tmp = cur_var;
1989 if (!cur_var->max_len)
1990 free(cur_var->varstr);
1991 cur_var = cur_var->next;
1992 free(tmp);
1993 }
1994 }
1995#endif
1996
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001997 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001998#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001999 sigexit(- (exitcode & 0xff));
2000#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02002001 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002002#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002003}
2004
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002005
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002006//TODO: return a mask of ALL handled sigs?
2007static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002008{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002009 int last_sig = 0;
2010
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002011 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002012 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002013
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002014 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002015 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002016 sig = 0;
2017 do {
2018 sig++;
2019 if (sigismember(&G.pending_set, sig)) {
2020 sigdelset(&G.pending_set, sig);
2021 goto got_sig;
2022 }
2023 } while (sig < NSIG);
2024 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002025 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002026 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002027 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002028 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002029 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002030 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002031 char *argv[3];
2032 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002033 argv[1] = xstrdup(G_traps[sig]);
2034 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002035 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002036 save_rcode = G.last_exitcode;
2037 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002038 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002039//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002040 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002041 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002042 } /* else: "" trap, ignoring signal */
2043 continue;
2044 }
2045 /* not a trap: special action */
2046 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002047 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002048 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002049 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002050 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002051 break;
2052#if ENABLE_HUSH_JOB
2053 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002054//TODO: why are we doing this? ash and dash don't do this,
2055//they have no handler for SIGHUP at all,
2056//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002057 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002058 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002059 /* bash is observed to signal whole process groups,
2060 * not individual processes */
2061 for (job = G.job_list; job; job = job->next) {
2062 if (job->pgrp <= 0)
2063 continue;
2064 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2065 if (kill(- job->pgrp, SIGHUP) == 0)
2066 kill(- job->pgrp, SIGCONT);
2067 }
2068 sigexit(SIGHUP);
2069 }
2070#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002071#if ENABLE_HUSH_FAST
2072 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002073 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002074 G.count_SIGCHLD++;
2075//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2076 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002077 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002078 * This simplifies wait builtin a bit.
2079 */
2080 break;
2081#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002082 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002083 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002084 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002085 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002086 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002087 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002088 * in interactive shell, because TERM is ignored.
2089 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002090 break;
2091 }
2092 }
2093 return last_sig;
2094}
2095
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002096
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002097static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002098{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002099 if (force || G.cwd == NULL) {
2100 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2101 * we must not try to free(bb_msg_unknown) */
2102 if (G.cwd == bb_msg_unknown)
2103 G.cwd = NULL;
2104 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2105 if (!G.cwd)
2106 G.cwd = bb_msg_unknown;
2107 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002108 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002109}
2110
Denis Vlasenko83506862007-11-23 13:11:42 +00002111
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002112/*
2113 * Shell and environment variable support
2114 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002115static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002116{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002117 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002118 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002119
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002120 pp = &G.top_var;
2121 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002122 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002123 return pp;
2124 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002125 }
2126 return NULL;
2127}
2128
Denys Vlasenko03dad222010-01-12 23:29:57 +01002129static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002130{
Denys Vlasenko29082232010-07-16 13:52:32 +02002131 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002132 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002133
2134 if (G.expanded_assignments) {
2135 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002136 while (*cpp) {
2137 char *cp = *cpp;
2138 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2139 return cp + len + 1;
2140 cpp++;
2141 }
2142 }
2143
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002144 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002145 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002146 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002147
Denys Vlasenkodea47882009-10-09 15:40:49 +02002148 if (strcmp(name, "PPID") == 0)
2149 return utoa(G.root_ppid);
2150 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002151#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002152 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002153 return utoa(next_random(&G.random_gen));
2154#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002155 return NULL;
2156}
2157
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002158static void handle_changed_special_names(const char *name, unsigned name_len)
2159{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002160 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2161 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2162 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002163 cmdedit_update_prompt();
2164 return;
2165 }
2166
2167 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2168 && name_len == 6
2169 ) {
2170#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002171 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002172 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002173 return;
2174 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002175#endif
2176#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002177 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002178 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002179 return;
2180 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002181#endif
2182 }
2183}
2184
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002185/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002186 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002187 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002188#define SETFLAG_EXPORT (1 << 0)
2189#define SETFLAG_UNEXPORT (1 << 1)
2190#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002191#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002192static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002193{
Denys Vlasenko61407802018-04-04 21:14:28 +02002194 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002195 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002196 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002197 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002198 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002199 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002200
Denis Vlasenko950bd722009-04-21 11:23:56 +00002201 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002202 if (HUSH_DEBUG && !eq_sign)
2203 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002204
Denis Vlasenko950bd722009-04-21 11:23:56 +00002205 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002206 cur_pp = &G.top_var;
2207 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002208 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002209 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002210 continue;
2211 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002212
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002213 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002214 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002215 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002216 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002217//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2218//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002219 return -1;
2220 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002221 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002222 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2223 *eq_sign = '\0';
2224 unsetenv(str);
2225 *eq_sign = '=';
2226 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002227 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002228 /* bash 3.2.33(1) and exported vars:
2229 * # export z=z
2230 * # f() { local z=a; env | grep ^z; }
2231 * # f
2232 * z=a
2233 * # env | grep ^z
2234 * z=z
2235 */
2236 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002237 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002238 /* New variable is local ("local VAR=VAL" or
2239 * "VAR=VAL cmd")
2240 * and existing one is global, or local
2241 * on a lower level that new one.
2242 * Remove it from global variable list:
2243 */
2244 *cur_pp = cur->next;
2245 if (G.shadowed_vars_pp) {
2246 /* Save in "shadowed" list */
2247 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2248 cur->flg_export ? "exported " : "",
2249 cur->varstr, cur->var_nest_level, str, local_lvl
2250 );
2251 cur->next = *G.shadowed_vars_pp;
2252 *G.shadowed_vars_pp = cur;
2253 } else {
2254 /* Came from pseudo_exec_argv(), no need to save: delete it */
2255 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2256 cur->flg_export ? "exported " : "",
2257 cur->varstr, cur->var_nest_level, str, local_lvl
2258 );
2259 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2260 free_me = cur->varstr; /* then free it later */
2261 free(cur);
2262 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002263 break;
2264 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002265
Denis Vlasenko950bd722009-04-21 11:23:56 +00002266 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002267 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002268 free_and_exp:
2269 free(str);
2270 goto exp;
2271 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002272
2273 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002274 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002275 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002276 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002277 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002278 strcpy(cur->varstr, str);
2279 goto free_and_exp;
2280 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002281 /* Can't reuse */
2282 cur->max_len = 0;
2283 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002284 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002285 /* max_len == 0 signifies "malloced" var, which we can
2286 * (and have to) free. But we can't free(cur->varstr) here:
2287 * if cur->flg_export is 1, it is in the environment.
2288 * We should either unsetenv+free, or wait until putenv,
2289 * then putenv(new)+free(old).
2290 */
2291 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002292 goto set_str_and_exp;
2293 }
2294
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002295 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002296 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002297 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002298 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002299 cur->next = *cur_pp;
2300 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002301
2302 set_str_and_exp:
2303 cur->varstr = str;
2304 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002305#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002306 if (flags & SETFLAG_MAKE_RO) {
2307 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002308 }
2309#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002310 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002311 cur->flg_export = 1;
2312 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002313 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002314 cur->flg_export = 0;
2315 /* unsetenv was already done */
2316 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002317 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002318 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002319 i = putenv(cur->varstr);
2320 /* only now we can free old exported malloced string */
2321 free(free_me);
2322 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002323 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002324 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002325 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002326
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002327 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002328
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002329 return 0;
2330}
2331
Denys Vlasenko6db47842009-09-05 20:15:17 +02002332/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002333static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002334{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002335 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002336}
2337
Denys Vlasenko35a017c2018-06-26 18:27:54 +02002338#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002339static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002340{
2341 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002342 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002343
Denys Vlasenko61407802018-04-04 21:14:28 +02002344 cur_pp = &G.top_var;
2345 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002346 if (strncmp(cur->varstr, name, name_len) == 0
2347 && cur->varstr[name_len] == '='
2348 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002349 if (cur->flg_read_only) {
2350 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002351 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002352 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002353
Denys Vlasenko61407802018-04-04 21:14:28 +02002354 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002355 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2356 bb_unsetenv(cur->varstr);
2357 if (!cur->max_len)
2358 free(cur->varstr);
2359 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002360
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002361 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002362 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002363 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002364 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002365
2366 /* Handle "unset PS1" et al even if did not find the variable to unset */
2367 handle_changed_special_names(name, name_len);
2368
Mike Frysingerd690f682009-03-30 06:50:54 +00002369 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002370}
2371
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002372static int unset_local_var(const char *name)
2373{
2374 return unset_local_var_len(name, strlen(name));
2375}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002376#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002377
Denys Vlasenkob2b14cb2018-06-26 18:09:22 +02002378#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS \
2379 || (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002380static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002381{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002382 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002383 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002384}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002385#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002386
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002387
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002388/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002389 * Helpers for "var1=val1 var2=val2 cmd" feature
2390 */
2391static void add_vars(struct variable *var)
2392{
2393 struct variable *next;
2394
2395 while (var) {
2396 next = var->next;
2397 var->next = G.top_var;
2398 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002399 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002400 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002401 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002402 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002403 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002404 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002405 var = next;
2406 }
2407}
2408
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002409/* We put strings[i] into variable table and possibly putenv them.
2410 * If variable is read only, we can free the strings[i]
2411 * which attempts to overwrite it.
2412 * The strings[] vector itself is freed.
2413 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002414static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002415{
2416 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002417
2418 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002419 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002420
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002421 s = strings;
2422 while (*s) {
2423 struct variable *var_p;
2424 struct variable **var_pp;
2425 char *eq;
2426
2427 eq = strchr(*s, '=');
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002428 if (HUSH_DEBUG && !eq)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002429 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002430 var_pp = get_ptr_to_local_var(*s, eq - *s);
2431 if (var_pp) {
2432 var_p = *var_pp;
2433 if (var_p->flg_read_only) {
2434 char **p;
2435 bb_error_msg("%s: readonly variable", *s);
2436 /*
2437 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2438 * If VAR is readonly, leaving it in the list
2439 * after asssignment error (msg above)
2440 * causes doubled error message later, on unset.
2441 */
2442 debug_printf_env("removing/freeing '%s' element\n", *s);
2443 free(*s);
2444 p = s;
2445 do { *p = p[1]; p++; } while (*p);
2446 goto next;
2447 }
2448 /* below, set_local_var() with nest level will
2449 * "shadow" (remove) this variable from
2450 * global linked list.
2451 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002452 }
Denys Vlasenkoe36a5892018-07-18 16:12:23 +02002453 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
2454 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002455 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002456 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002457 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002458 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002459}
2460
2461
2462/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002463 * Unicode helper
2464 */
2465static void reinit_unicode_for_hush(void)
2466{
2467 /* Unicode support should be activated even if LANG is set
2468 * _during_ shell execution, not only if it was set when
2469 * shell was started. Therefore, re-check LANG every time:
2470 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002471 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2472 || ENABLE_UNICODE_USING_LOCALE
Denys Vlasenko4c201c02018-07-17 15:04:17 +02002473 ) {
Denys Vlasenko841f8332014-08-13 10:09:49 +02002474 const char *s = get_local_var_value("LC_ALL");
2475 if (!s) s = get_local_var_value("LC_CTYPE");
2476 if (!s) s = get_local_var_value("LANG");
2477 reinit_unicode(s);
2478 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002479}
2480
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002481/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002482 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002484
2485#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002486/* To test correct lineedit/interactive behavior, type from command line:
2487 * echo $P\
2488 * \
2489 * AT\
2490 * H\
2491 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002492 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002493 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002494# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002495static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002496{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002497 G.PS1 = get_local_var_value("PS1");
2498 if (G.PS1 == NULL)
2499 G.PS1 = "";
2500 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002501 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002502 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002503}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002504# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002505static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002506{
2507 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002508
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002509 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002510
2511 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2512 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002513 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002514 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2515 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002516 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002517 /* bash uses $PWD value, even if it is set by user.
2518 * It uses current dir only if PWD is unset.
2519 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002520 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002521 }
2522 prompt_str = G.PS1;
2523 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002524 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002525 return prompt_str;
2526}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002527static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002528{
2529 int r;
2530 const char *prompt_str;
2531
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002532 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002533# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002534 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002535 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002536 if (G.flag_SIGINT) {
2537 /* There was ^C'ed, make it look prettier: */
2538 bb_putchar('\n');
2539 G.flag_SIGINT = 0;
2540 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002541 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002542 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002543 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002544 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002545 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002546 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002547 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002548 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002549 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002550 if (r != 0 && !G.flag_SIGINT)
2551 break;
2552 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002553 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2554 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002555 G.last_exitcode = 128 + SIGINT;
2556 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002557 if (r < 0) {
2558 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002559 i->p = NULL;
2560 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002561 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002562 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002563 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002564 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002565# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002566 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002567 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002568 if (i->last_char == '\0' || i->last_char == '\n') {
2569 /* Why check_and_run_traps here? Try this interactively:
2570 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2571 * $ <[enter], repeatedly...>
2572 * Without check_and_run_traps, handler never runs.
2573 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002574 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002575 fputs(prompt_str, stdout);
2576 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002577 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002578//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002579 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002580 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2581 * no ^C masking happens during fgetc, no special code for ^C:
2582 * it generates SIGINT as usual.
2583 */
2584 check_and_run_traps();
2585 if (G.flag_SIGINT)
2586 G.last_exitcode = 128 + SIGINT;
2587 if (r != '\0')
2588 break;
2589 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002590 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002591# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002592}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002593/* This is the magic location that prints prompts
2594 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002595static int fgetc_interactive(struct in_str *i)
2596{
2597 int ch;
2598 /* If it's interactive stdin, get new line. */
2599 if (G_interactive_fd && i->file == stdin) {
2600 /* Returns first char (or EOF), the rest is in i->p[] */
2601 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002602 G.promptmode = 1; /* PS2 */
2603 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002604 } else {
2605 /* Not stdin: script file, sourced file, etc */
2606 do ch = fgetc(i->file); while (ch == '\0');
2607 }
2608 return ch;
2609}
2610#else
2611static inline int fgetc_interactive(struct in_str *i)
2612{
2613 int ch;
2614 do ch = fgetc(i->file); while (ch == '\0');
2615 return ch;
2616}
2617#endif /* INTERACTIVE */
2618
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002619static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002620{
2621 int ch;
2622
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002623 if (!i->file) {
2624 /* string-based in_str */
2625 ch = (unsigned char)*i->p;
2626 if (ch != '\0') {
2627 i->p++;
2628 i->last_char = ch;
2629 return ch;
2630 }
2631 return EOF;
2632 }
2633
2634 /* FILE-based in_str */
2635
Denys Vlasenko4074d492016-09-30 01:49:53 +02002636#if ENABLE_FEATURE_EDITING
2637 /* This can be stdin, check line editing char[] buffer */
2638 if (i->p && *i->p != '\0') {
2639 ch = (unsigned char)*i->p++;
2640 goto out;
2641 }
2642#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002643 /* peek_buf[] is an int array, not char. Can contain EOF. */
2644 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002645 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002646 int ch2 = i->peek_buf[1];
2647 i->peek_buf[0] = ch2;
2648 if (ch2 == 0) /* very likely, avoid redundant write */
2649 goto out;
2650 i->peek_buf[1] = 0;
2651 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002652 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002653
Denys Vlasenko4074d492016-09-30 01:49:53 +02002654 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002655 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002656 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002657 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002658#if ENABLE_HUSH_LINENO_VAR
2659 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002660 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002661 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2662 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002663#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002664 return ch;
2665}
2666
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002667static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002668{
2669 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002670
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002671 if (!i->file) {
2672 /* string-based in_str */
2673 /* Doesn't report EOF on NUL. None of the callers care. */
2674 return (unsigned char)*i->p;
2675 }
2676
2677 /* FILE-based in_str */
2678
Denys Vlasenko4074d492016-09-30 01:49:53 +02002679#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002680 /* This can be stdin, check line editing char[] buffer */
2681 if (i->p && *i->p != '\0')
2682 return (unsigned char)*i->p;
2683#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002684 /* peek_buf[] is an int array, not char. Can contain EOF. */
2685 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002686 if (ch != 0)
2687 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002688
Denys Vlasenko4074d492016-09-30 01:49:53 +02002689 /* Need to get a new char */
2690 ch = fgetc_interactive(i);
2691 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2692
2693 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2694#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2695 if (i->p) {
2696 i->p -= 1;
2697 return ch;
2698 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002699#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002700 i->peek_buf[0] = ch;
2701 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002702 return ch;
2703}
2704
Denys Vlasenko4074d492016-09-30 01:49:53 +02002705/* Only ever called if i_peek() was called, and did not return EOF.
2706 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2707 * not end-of-line. Therefore we never need to read a new editing line here.
2708 */
2709static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002710{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002711 int ch;
2712
2713 /* There are two cases when i->p[] buffer exists.
2714 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002715 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002716 * In both cases, we know that i->p[0] exists and not NUL, and
2717 * the peek2 result is in i->p[1].
2718 */
2719 if (i->p)
2720 return (unsigned char)i->p[1];
2721
2722 /* Now we know it is a file-based in_str. */
2723
2724 /* peek_buf[] is an int array, not char. Can contain EOF. */
2725 /* Is there 2nd char? */
2726 ch = i->peek_buf[1];
2727 if (ch == 0) {
2728 /* We did not read it yet, get it now */
2729 do ch = fgetc(i->file); while (ch == '\0');
2730 i->peek_buf[1] = ch;
2731 }
2732
2733 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2734 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002735}
2736
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002737static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2738{
2739 for (;;) {
2740 int ch, ch2;
2741
2742 ch = i_getch(input);
2743 if (ch != '\\')
2744 return ch;
2745 ch2 = i_peek(input);
2746 if (ch2 != '\n')
2747 return ch;
2748 /* backslash+newline, skip it */
2749 i_getch(input);
2750 }
2751}
2752
2753/* Note: this function _eats_ \<newline> pairs, safe to use plain
2754 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2755 */
2756static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2757{
2758 for (;;) {
2759 int ch, ch2;
2760
2761 ch = i_peek(input);
2762 if (ch != '\\')
2763 return ch;
2764 ch2 = i_peek2(input);
2765 if (ch2 != '\n')
2766 return ch;
2767 /* backslash+newline, skip it */
2768 i_getch(input);
2769 i_getch(input);
2770 }
2771}
2772
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002773static void setup_file_in_str(struct in_str *i, FILE *f)
2774{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002775 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002776 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002777 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002778}
2779
2780static void setup_string_in_str(struct in_str *i, const char *s)
2781{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002782 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002783 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002784 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002785}
2786
2787
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002788/*
2789 * o_string support
2790 */
2791#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002792
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002793static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002794{
2795 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002796 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002797 if (o->data)
2798 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002799}
2800
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002801static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002802{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002803 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002804 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002805}
2806
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002807static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2808{
2809 free(o->data);
2810}
2811
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002812static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002813{
2814 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002815 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002816 o->data = xrealloc(o->data, 1 + o->maxlen);
2817 }
2818}
2819
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002820static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002821{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002822 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002823 if (o->length < o->maxlen) {
2824 /* likely. avoid o_grow_by() call */
2825 add:
2826 o->data[o->length] = ch;
2827 o->length++;
2828 o->data[o->length] = '\0';
2829 return;
2830 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002831 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002832 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002833}
2834
Denys Vlasenko657086a2016-09-29 18:07:42 +02002835#if 0
2836/* Valid only if we know o_string is not empty */
2837static void o_delchr(o_string *o)
2838{
2839 o->length--;
2840 o->data[o->length] = '\0';
2841}
2842#endif
2843
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002844static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002845{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002846 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002847 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002848 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002849}
2850
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002851static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002852{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002853 o_addblock(o, str, strlen(str));
2854}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002855
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002856#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002857static void nommu_addchr(o_string *o, int ch)
2858{
2859 if (o)
2860 o_addchr(o, ch);
2861}
2862#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002863# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002864#endif
2865
2866static void o_addstr_with_NUL(o_string *o, const char *str)
2867{
2868 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002869}
2870
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002871/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002872 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002873 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2874 * Apparently, on unquoted $v bash still does globbing
2875 * ("v='*.txt'; echo $v" prints all .txt files),
2876 * but NOT brace expansion! Thus, there should be TWO independent
2877 * quoting mechanisms on $v expansion side: one protects
2878 * $v from brace expansion, and other additionally protects "$v" against globbing.
2879 * We have only second one.
2880 */
2881
Denys Vlasenko9e800222010-10-03 14:28:04 +02002882#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002883# define MAYBE_BRACES "{}"
2884#else
2885# define MAYBE_BRACES ""
2886#endif
2887
Eric Andersen25f27032001-04-26 23:22:31 +00002888/* My analysis of quoting semantics tells me that state information
2889 * is associated with a destination, not a source.
2890 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002891static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002892{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002893 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002894 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002895 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002896 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002897 o_grow_by(o, sz);
2898 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002899 o->data[o->length] = '\\';
2900 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002901 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002902 o->data[o->length] = ch;
2903 o->length++;
2904 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002905}
2906
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002907static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002908{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002909 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002910 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2911 && strchr("*?[\\" MAYBE_BRACES, ch)
2912 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002913 sz++;
2914 o->data[o->length] = '\\';
2915 o->length++;
2916 }
2917 o_grow_by(o, sz);
2918 o->data[o->length] = ch;
2919 o->length++;
2920 o->data[o->length] = '\0';
2921}
2922
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002923static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002924{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002925 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002926 char ch;
2927 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002928 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002929 if (ordinary_cnt > len) /* paranoia */
2930 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002931 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002932 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002933 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002934 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002935 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002936
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002937 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002938 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002939 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002940 sz++;
2941 o->data[o->length] = '\\';
2942 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002943 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002944 o_grow_by(o, sz);
2945 o->data[o->length] = ch;
2946 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002947 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002948 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002949}
2950
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002951static void o_addQblock(o_string *o, const char *str, int len)
2952{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002953 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002954 o_addblock(o, str, len);
2955 return;
2956 }
2957 o_addqblock(o, str, len);
2958}
2959
Denys Vlasenko38292b62010-09-05 14:49:40 +02002960static void o_addQstr(o_string *o, const char *str)
2961{
2962 o_addQblock(o, str, strlen(str));
2963}
2964
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002965/* A special kind of o_string for $VAR and `cmd` expansion.
2966 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002967 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002968 * list[i] contains an INDEX (int!) into this string data.
2969 * It means that if list[] needs to grow, data needs to be moved higher up
2970 * but list[i]'s need not be modified.
2971 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002972 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002973 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2974 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002975#if DEBUG_EXPAND || DEBUG_GLOB
2976static void debug_print_list(const char *prefix, o_string *o, int n)
2977{
2978 char **list = (char**)o->data;
2979 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2980 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002981
2982 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002983 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 +02002984 prefix, list, n, string_start, o->length, o->maxlen,
2985 !!(o->o_expflags & EXP_FLAG_GLOB),
2986 o->has_quoted_part,
2987 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002988 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002989 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002990 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2991 o->data + (int)(uintptr_t)list[i] + string_start,
2992 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002993 i++;
2994 }
2995 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002996 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002997 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002998 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002999 }
3000}
3001#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003002# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003003#endif
3004
3005/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3006 * in list[n] so that it points past last stored byte so far.
3007 * It returns n+1. */
3008static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003009{
3010 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003011 int string_start;
3012 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003013
3014 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003015 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3016 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003017 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003018 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003019 /* list[n] points to string_start, make space for 16 more pointers */
3020 o->maxlen += 0x10 * sizeof(list[0]);
3021 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003022 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003023 memmove(list + n + 0x10, list + n, string_len);
3024 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003025 } else {
3026 debug_printf_list("list[%d]=%d string_start=%d\n",
3027 n, string_len, string_start);
3028 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003029 } else {
3030 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003031 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3032 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003033 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3034 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003035 o->has_empty_slot = 0;
3036 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003037 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003038 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003039 return n + 1;
3040}
3041
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003042/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003043static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003044{
3045 char **list = (char**)o->data;
3046 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3047
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003048 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003049}
3050
Denys Vlasenko9e800222010-10-03 14:28:04 +02003051#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003052/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3053 * first, it processes even {a} (no commas), second,
3054 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003055 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003056 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003057
3058/* Helper */
3059static int glob_needed(const char *s)
3060{
3061 while (*s) {
3062 if (*s == '\\') {
3063 if (!s[1])
3064 return 0;
3065 s += 2;
3066 continue;
3067 }
3068 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3069 return 1;
3070 s++;
3071 }
3072 return 0;
3073}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003074/* Return pointer to next closing brace or to comma */
3075static const char *next_brace_sub(const char *cp)
3076{
3077 unsigned depth = 0;
3078 cp++;
3079 while (*cp != '\0') {
3080 if (*cp == '\\') {
3081 if (*++cp == '\0')
3082 break;
3083 cp++;
3084 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003085 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003086 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003087 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003088 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003089 depth++;
3090 }
3091
3092 return *cp != '\0' ? cp : NULL;
3093}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003094/* Recursive brace globber. Note: may garble pattern[]. */
3095static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003096{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003097 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003098 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003099 const char *next;
3100 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003101 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003102 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003103
3104 debug_printf_glob("glob_brace('%s')\n", pattern);
3105
3106 begin = pattern;
3107 while (1) {
3108 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003109 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003110 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003111 /* Find the first sub-pattern and at the same time
3112 * find the rest after the closing brace */
3113 next = next_brace_sub(begin);
3114 if (next == NULL) {
3115 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003116 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003117 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003118 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003119 /* "{abc}" with no commas - illegal
3120 * brace expr, disregard and skip it */
3121 begin = next + 1;
3122 continue;
3123 }
3124 break;
3125 }
3126 if (*begin == '\\' && begin[1] != '\0')
3127 begin++;
3128 begin++;
3129 }
3130 debug_printf_glob("begin:%s\n", begin);
3131 debug_printf_glob("next:%s\n", next);
3132
3133 /* Now find the end of the whole brace expression */
3134 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003135 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003136 rest = next_brace_sub(rest);
3137 if (rest == NULL) {
3138 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003139 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003140 }
3141 debug_printf_glob("rest:%s\n", rest);
3142 }
3143 rest_len = strlen(++rest) + 1;
3144
3145 /* We are sure the brace expression is well-formed */
3146
3147 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003148 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003149
3150 /* We have a brace expression. BEGIN points to the opening {,
3151 * NEXT points past the terminator of the first element, and REST
3152 * points past the final }. We will accumulate result names from
3153 * recursive runs for each brace alternative in the buffer using
3154 * GLOB_APPEND. */
3155
3156 p = begin + 1;
3157 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003158 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003159 memcpy(
3160 mempcpy(
3161 mempcpy(new_pattern_buf,
3162 /* We know the prefix for all sub-patterns */
3163 pattern, begin - pattern),
3164 p, next - p),
3165 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003166
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003167 /* Note: glob_brace() may garble new_pattern_buf[].
3168 * That's why we re-copy prefix every time (1st memcpy above).
3169 */
3170 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003171 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003172 /* We saw the last entry */
3173 break;
3174 }
3175 p = next + 1;
3176 next = next_brace_sub(next);
3177 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003178 free(new_pattern_buf);
3179 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003180
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003181 simple_glob:
3182 {
3183 int gr;
3184 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003185
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003186 memset(&globdata, 0, sizeof(globdata));
3187 gr = glob(pattern, 0, NULL, &globdata);
3188 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3189 if (gr != 0) {
3190 if (gr == GLOB_NOMATCH) {
3191 globfree(&globdata);
3192 /* NB: garbles parameter */
3193 unbackslash(pattern);
3194 o_addstr_with_NUL(o, pattern);
3195 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3196 return o_save_ptr_helper(o, n);
3197 }
3198 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003199 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003200 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3201 * but we didn't specify it. Paranoia again. */
3202 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3203 }
3204 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3205 char **argv = globdata.gl_pathv;
3206 while (1) {
3207 o_addstr_with_NUL(o, *argv);
3208 n = o_save_ptr_helper(o, n);
3209 argv++;
3210 if (!*argv)
3211 break;
3212 }
3213 }
3214 globfree(&globdata);
3215 }
3216 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003217}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003218/* Performs globbing on last list[],
3219 * saving each result as a new list[].
3220 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003221static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003222{
3223 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003224
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003225 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003226 if (!o->data)
3227 return o_save_ptr_helper(o, n);
3228 pattern = o->data + o_get_last_ptr(o, n);
3229 debug_printf_glob("glob pattern '%s'\n", pattern);
3230 if (!glob_needed(pattern)) {
3231 /* unbackslash last string in o in place, fix length */
3232 o->length = unbackslash(pattern) - o->data;
3233 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3234 return o_save_ptr_helper(o, n);
3235 }
3236
3237 copy = xstrdup(pattern);
3238 /* "forget" pattern in o */
3239 o->length = pattern - o->data;
3240 n = glob_brace(copy, o, n);
3241 free(copy);
3242 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003243 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003244 return n;
3245}
3246
Denys Vlasenko238081f2010-10-03 14:26:26 +02003247#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003248
3249/* Helper */
3250static int glob_needed(const char *s)
3251{
3252 while (*s) {
3253 if (*s == '\\') {
3254 if (!s[1])
3255 return 0;
3256 s += 2;
3257 continue;
3258 }
3259 if (*s == '*' || *s == '[' || *s == '?')
3260 return 1;
3261 s++;
3262 }
3263 return 0;
3264}
3265/* Performs globbing on last list[],
3266 * saving each result as a new list[].
3267 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003268static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003269{
3270 glob_t globdata;
3271 int gr;
3272 char *pattern;
3273
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003274 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003275 if (!o->data)
3276 return o_save_ptr_helper(o, n);
3277 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003278 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003279 if (!glob_needed(pattern)) {
3280 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003281 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003282 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003283 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003284 return o_save_ptr_helper(o, n);
3285 }
3286
3287 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003288 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3289 * If we glob "*.\*" and don't find anything, we need
3290 * to fall back to using literal "*.*", but GLOB_NOCHECK
3291 * will return "*.\*"!
3292 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003293 gr = glob(pattern, 0, NULL, &globdata);
3294 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003295 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003296 if (gr == GLOB_NOMATCH) {
3297 globfree(&globdata);
3298 goto literal;
3299 }
3300 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003301 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003302 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3303 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003304 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003305 }
3306 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3307 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003308 /* "forget" pattern in o */
3309 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003310 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003311 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003312 n = o_save_ptr_helper(o, n);
3313 argv++;
3314 if (!*argv)
3315 break;
3316 }
3317 }
3318 globfree(&globdata);
3319 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003320 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003321 return n;
3322}
3323
Denys Vlasenko238081f2010-10-03 14:26:26 +02003324#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003325
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003326/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003327 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003328static int o_save_ptr(o_string *o, int n)
3329{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003330 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003331 /* If o->has_empty_slot, list[n] was already globbed
3332 * (if it was requested back then when it was filled)
3333 * so don't do that again! */
3334 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003335 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003336 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003337 return o_save_ptr_helper(o, n);
3338}
3339
3340/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003341static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003342{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003343 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003344 int string_start;
3345
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003346 if (DEBUG_EXPAND)
3347 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003348 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003349 list = (char**)o->data;
3350 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3351 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003352 while (n) {
3353 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003354 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003355 }
3356 return list;
3357}
3358
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003359static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003360
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003361/* Returns pi->next - next pipe in the list */
3362static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003363{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003364 struct pipe *next;
3365 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003366
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003367 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003368 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003369 struct command *command;
3370 struct redir_struct *r, *rnext;
3371
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003372 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003373 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003374 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003375 if (DEBUG_CLEAN) {
3376 int a;
3377 char **p;
3378 for (a = 0, p = command->argv; *p; a++, p++) {
3379 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3380 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003381 }
3382 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003383 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003384 }
3385 /* not "else if": on syntax error, we may have both! */
3386 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003387 debug_printf_clean(" begin group (cmd_type:%d)\n",
3388 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003389 free_pipe_list(command->group);
3390 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003391 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003392 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003393 /* else is crucial here.
3394 * If group != NULL, child_func is meaningless */
3395#if ENABLE_HUSH_FUNCTIONS
3396 else if (command->child_func) {
3397 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3398 command->child_func->parent_cmd = NULL;
3399 }
3400#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003401#if !BB_MMU
3402 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003403 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003404#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003405 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003406 debug_printf_clean(" redirect %d%s",
3407 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003408 /* guard against the case >$FOO, where foo is unset or blank */
3409 if (r->rd_filename) {
3410 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3411 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003412 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003413 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003414 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003415 rnext = r->next;
3416 free(r);
3417 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003418 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003419 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003420 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003421 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003422#if ENABLE_HUSH_JOB
3423 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003424 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003425#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003426
3427 next = pi->next;
3428 free(pi);
3429 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003430}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003431
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003432static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003433{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003434 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003435#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003436 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003437#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003438 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003439 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003440 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003441}
3442
3443
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003444/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003445
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003446#ifndef debug_print_tree
3447static void debug_print_tree(struct pipe *pi, int lvl)
3448{
3449 static const char *const PIPE[] = {
3450 [PIPE_SEQ] = "SEQ",
3451 [PIPE_AND] = "AND",
3452 [PIPE_OR ] = "OR" ,
3453 [PIPE_BG ] = "BG" ,
3454 };
3455 static const char *RES[] = {
3456 [RES_NONE ] = "NONE" ,
3457# if ENABLE_HUSH_IF
3458 [RES_IF ] = "IF" ,
3459 [RES_THEN ] = "THEN" ,
3460 [RES_ELIF ] = "ELIF" ,
3461 [RES_ELSE ] = "ELSE" ,
3462 [RES_FI ] = "FI" ,
3463# endif
3464# if ENABLE_HUSH_LOOPS
3465 [RES_FOR ] = "FOR" ,
3466 [RES_WHILE] = "WHILE",
3467 [RES_UNTIL] = "UNTIL",
3468 [RES_DO ] = "DO" ,
3469 [RES_DONE ] = "DONE" ,
3470# endif
3471# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3472 [RES_IN ] = "IN" ,
3473# endif
3474# if ENABLE_HUSH_CASE
3475 [RES_CASE ] = "CASE" ,
3476 [RES_CASE_IN ] = "CASE_IN" ,
3477 [RES_MATCH] = "MATCH",
3478 [RES_CASE_BODY] = "CASE_BODY",
3479 [RES_ESAC ] = "ESAC" ,
3480# endif
3481 [RES_XXXX ] = "XXXX" ,
3482 [RES_SNTX ] = "SNTX" ,
3483 };
3484 static const char *const CMDTYPE[] = {
3485 "{}",
3486 "()",
3487 "[noglob]",
3488# if ENABLE_HUSH_FUNCTIONS
3489 "func()",
3490# endif
3491 };
3492
3493 int pin, prn;
3494
3495 pin = 0;
3496 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003497 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3498 lvl*2, "",
3499 pin,
3500 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3501 RES[pi->res_word],
3502 pi->followup, PIPE[pi->followup]
3503 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003504 prn = 0;
3505 while (prn < pi->num_cmds) {
3506 struct command *command = &pi->cmds[prn];
3507 char **argv = command->argv;
3508
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003509 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003510 lvl*2, "", prn,
3511 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003512#if ENABLE_HUSH_LINENO_VAR
3513 fdprintf(2, " LINENO:%u", command->lineno);
3514#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003515 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003516 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003517 CMDTYPE[command->cmd_type],
3518 argv
3519# if !BB_MMU
3520 , " group_as_string:", command->group_as_string
3521# else
3522 , "", ""
3523# endif
3524 );
3525 debug_print_tree(command->group, lvl+1);
3526 prn++;
3527 continue;
3528 }
3529 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003530 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003531 argv++;
3532 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003533 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003534 prn++;
3535 }
3536 pi = pi->next;
3537 pin++;
3538 }
3539}
3540#endif /* debug_print_tree */
3541
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003542static struct pipe *new_pipe(void)
3543{
Eric Andersen25f27032001-04-26 23:22:31 +00003544 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003545 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003546 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003547 return pi;
3548}
3549
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003550/* Command (member of a pipe) is complete, or we start a new pipe
3551 * if ctx->command is NULL.
3552 * No errors possible here.
3553 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003554static int done_command(struct parse_context *ctx)
3555{
3556 /* The command is really already in the pipe structure, so
3557 * advance the pipe counter and make a new, null command. */
3558 struct pipe *pi = ctx->pipe;
3559 struct command *command = ctx->command;
3560
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003561#if 0 /* Instead we emit error message at run time */
3562 if (ctx->pending_redirect) {
3563 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003564 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003565 ctx->pending_redirect = NULL;
3566 }
3567#endif
3568
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003569 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003570 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003571 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003572 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003573 }
3574 pi->num_cmds++;
3575 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003576 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003577 } else {
3578 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3579 }
3580
3581 /* Only real trickiness here is that the uncommitted
3582 * command structure is not counted in pi->num_cmds. */
3583 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003584 ctx->command = command = &pi->cmds[pi->num_cmds];
3585 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003586 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003587#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003588 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003589 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003590#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003591 return pi->num_cmds; /* used only for 0/nonzero check */
3592}
3593
3594static void done_pipe(struct parse_context *ctx, pipe_style type)
3595{
3596 int not_null;
3597
3598 debug_printf_parse("done_pipe entered, followup %d\n", type);
3599 /* Close previous command */
3600 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003601#if HAS_KEYWORDS
3602 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3603 ctx->ctx_inverted = 0;
3604 ctx->pipe->res_word = ctx->ctx_res_w;
3605#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003606 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3607 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003608 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3609 * in a backgrounded subshell.
3610 */
3611 struct pipe *pi;
3612 struct command *command;
3613
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003614 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003615 pi = ctx->list_head;
3616 while (pi != ctx->pipe) {
3617 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3618 goto no_conv;
3619 pi = pi->next;
3620 }
3621
3622 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3623 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3624 pi = xzalloc(sizeof(*pi));
3625 pi->followup = PIPE_BG;
3626 pi->num_cmds = 1;
3627 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3628 command = &pi->cmds[0];
3629 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3630 command->cmd_type = CMD_NORMAL;
3631 command->group = ctx->list_head;
3632#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003633 command->group_as_string = xstrndup(
3634 ctx->as_string.data,
3635 ctx->as_string.length - 1 /* do not copy last char, "&" */
3636 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003637#endif
3638 /* Replace all pipes in ctx with one newly created */
3639 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003640 } else {
3641 no_conv:
3642 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003643 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003644
3645 /* Without this check, even just <enter> on command line generates
3646 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003647 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003648 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003649#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003650 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003651#endif
3652#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003653 || ctx->ctx_res_w == RES_DONE
3654 || ctx->ctx_res_w == RES_FOR
3655 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003656#endif
3657#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003658 || ctx->ctx_res_w == RES_ESAC
3659#endif
3660 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003661 struct pipe *new_p;
3662 debug_printf_parse("done_pipe: adding new pipe: "
3663 "not_null:%d ctx->ctx_res_w:%d\n",
3664 not_null, ctx->ctx_res_w);
3665 new_p = new_pipe();
3666 ctx->pipe->next = new_p;
3667 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003668 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003669 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003670 * This is used to control execution.
3671 * RES_FOR and RES_IN are NOT sticky (needed to support
3672 * cases where variable or value happens to match a keyword):
3673 */
3674#if ENABLE_HUSH_LOOPS
3675 if (ctx->ctx_res_w == RES_FOR
3676 || ctx->ctx_res_w == RES_IN)
3677 ctx->ctx_res_w = RES_NONE;
3678#endif
3679#if ENABLE_HUSH_CASE
3680 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003681 ctx->ctx_res_w = RES_CASE_BODY;
3682 if (ctx->ctx_res_w == RES_CASE)
3683 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003684#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003685 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003686 /* Create the memory for command, roughly:
3687 * ctx->pipe->cmds = new struct command;
3688 * ctx->command = &ctx->pipe->cmds[0];
3689 */
3690 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003691 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003692 }
3693 debug_printf_parse("done_pipe return\n");
3694}
3695
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003696static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003697{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003698 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003699 if (MAYBE_ASSIGNMENT != 0)
3700 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003701 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003702 /* Create the memory for command, roughly:
3703 * ctx->pipe->cmds = new struct command;
3704 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003705 */
3706 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003707}
3708
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003709/* If a reserved word is found and processed, parse context is modified
3710 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003711 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003712#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003713struct reserved_combo {
3714 char literal[6];
3715 unsigned char res;
3716 unsigned char assignment_flag;
3717 int flag;
3718};
3719enum {
3720 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003721# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003722 FLAG_IF = (1 << RES_IF ),
3723 FLAG_THEN = (1 << RES_THEN ),
3724 FLAG_ELIF = (1 << RES_ELIF ),
3725 FLAG_ELSE = (1 << RES_ELSE ),
3726 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003727# endif
3728# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003729 FLAG_FOR = (1 << RES_FOR ),
3730 FLAG_WHILE = (1 << RES_WHILE),
3731 FLAG_UNTIL = (1 << RES_UNTIL),
3732 FLAG_DO = (1 << RES_DO ),
3733 FLAG_DONE = (1 << RES_DONE ),
3734 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003735# endif
3736# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003737 FLAG_MATCH = (1 << RES_MATCH),
3738 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003739# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003740 FLAG_START = (1 << RES_XXXX ),
3741};
3742
3743static const struct reserved_combo* match_reserved_word(o_string *word)
3744{
Eric Andersen25f27032001-04-26 23:22:31 +00003745 /* Mostly a list of accepted follow-up reserved words.
3746 * FLAG_END means we are done with the sequence, and are ready
3747 * to turn the compound list into a command.
3748 * FLAG_START means the word must start a new compound list.
3749 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003750 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003751# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003752 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3753 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3754 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3755 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3756 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3757 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003758# endif
3759# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003760 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3761 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3762 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3763 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3764 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3765 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003766# endif
3767# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003768 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3769 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003770# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003771 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003772 const struct reserved_combo *r;
3773
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003774 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003775 if (strcmp(word->data, r->literal) == 0)
3776 return r;
3777 }
3778 return NULL;
3779}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003780/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003781 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003782static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003783{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003784# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003785 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003786 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003787 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003788# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003789 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003790
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003791 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003792 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003793 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003794 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003795 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003796
3797 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003798# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003799 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3800 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003801 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003802 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003803# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003804 if (r->flag == 0) { /* '!' */
3805 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003806 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003807 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003808 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003809 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003810 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003811 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003812 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003813 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003814
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003815 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003816 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003817 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003818 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003819 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003820 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003821 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003822 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003823 } else {
3824 /* "{...} fi" is ok. "{...} if" is not
3825 * Example:
3826 * if { echo foo; } then { echo bar; } fi */
3827 if (ctx->command->group)
3828 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003829 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003830
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003831 ctx->ctx_res_w = r->res;
3832 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003833 ctx->is_assignment = r->assignment_flag;
3834 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003835
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003836 if (ctx->old_flag & FLAG_END) {
3837 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003838
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003839 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003840 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003841 old = ctx->stack;
3842 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003843 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003844# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003845 /* At this point, the compound command's string is in
3846 * ctx->as_string... except for the leading keyword!
3847 * Consider this example: "echo a | if true; then echo a; fi"
3848 * ctx->as_string will contain "true; then echo a; fi",
3849 * with "if " remaining in old->as_string!
3850 */
3851 {
3852 char *str;
3853 int len = old->as_string.length;
3854 /* Concatenate halves */
3855 o_addstr(&old->as_string, ctx->as_string.data);
3856 o_free_unsafe(&ctx->as_string);
3857 /* Find where leading keyword starts in first half */
3858 str = old->as_string.data + len;
3859 if (str > old->as_string.data)
3860 str--; /* skip whitespace after keyword */
3861 while (str > old->as_string.data && isalpha(str[-1]))
3862 str--;
3863 /* Ugh, we're done with this horrid hack */
3864 old->command->group_as_string = xstrdup(str);
3865 debug_printf_parse("pop, remembering as:'%s'\n",
3866 old->command->group_as_string);
3867 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003868# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003869 *ctx = *old; /* physical copy */
3870 free(old);
3871 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003872 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003873}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003874#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003875
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003876/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003877 * Normal return is 0. Syntax errors return 1.
3878 * Note: on return, word is reset, but not o_free'd!
3879 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003880static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003881{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003882 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003883
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003884 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3885 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003886 debug_printf_parse("done_word return 0: true null, ignored\n");
3887 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003888 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003889
Eric Andersen25f27032001-04-26 23:22:31 +00003890 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003891 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3892 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003893 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003894 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003895 * If the redirection operator is "<<" or "<<-", the word
3896 * that follows the redirection operator shall be
3897 * subjected to quote removal; it is unspecified whether
3898 * any of the other expansions occur. For the other
3899 * redirection operators, the word that follows the
3900 * redirection operator shall be subjected to tilde
3901 * expansion, parameter expansion, command substitution,
3902 * arithmetic expansion, and quote removal.
3903 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003904 * on the word by a non-interactive shell; an interactive
3905 * shell may perform it, but shall do so only when
3906 * the expansion would result in one word."
3907 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003908//bash does not do parameter/command substitution or arithmetic expansion
3909//for _heredoc_ redirection word: these constructs look for exact eof marker
3910// as written:
3911// <<EOF$t
3912// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003913// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3914
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003915 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003916 /* Cater for >\file case:
3917 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3918 * Same with heredocs:
3919 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3920 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003921 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3922 unbackslash(ctx->pending_redirect->rd_filename);
3923 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003924 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003925 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3926 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003927 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003928 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003929 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003930 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003931#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003932# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003933 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003934 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003935 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003936 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003937 /* ctx->ctx_res_w = RES_MATCH; */
3938 ctx->ctx_dsemicolon = 0;
3939 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003940# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003941 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003942# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003943 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3944 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003945# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003946# if ENABLE_HUSH_CASE
3947 && ctx->ctx_res_w != RES_CASE
3948# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003949 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003950 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003951 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003952 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003953 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003954# if ENABLE_HUSH_LINENO_VAR
3955/* Case:
3956 * "while ...; do
3957 * cmd ..."
3958 * If we don't close the pipe _now_, immediately after "do", lineno logic
3959 * sees "cmd" as starting at "do" - i.e., at the previous line.
3960 */
3961 if (0
3962 IF_HUSH_IF(|| reserved->res == RES_THEN)
3963 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3964 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3965 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3966 ) {
3967 done_pipe(ctx, PIPE_SEQ);
3968 }
3969# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003970 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003971 debug_printf_parse("done_word return %d\n",
3972 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003973 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003974 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003975# if defined(CMD_SINGLEWORD_NOGLOB)
3976 if (0
3977# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003978 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02003979# endif
3980 /* In bash, local/export/readonly are special, args
3981 * are assignments and therefore expansion of them
3982 * should be "one-word" expansion:
3983 * $ export i=`echo 'a b'` # one arg: "i=a b"
3984 * compare with:
3985 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3986 * ls: cannot access i=a: No such file or directory
3987 * ls: cannot access b: No such file or directory
3988 * Note: bash 3.2.33(1) does this only if export word
3989 * itself is not quoted:
3990 * $ export i=`echo 'aaa bbb'`; echo "$i"
3991 * aaa bbb
3992 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3993 * aaa
3994 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003995 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
3996 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
3997 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02003998 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003999 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4000 }
4001 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004002# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004003 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004004#endif /* HAS_KEYWORDS */
4005
Denis Vlasenkobb929512009-04-16 10:59:40 +00004006 if (command->group) {
4007 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004008 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004009 debug_printf_parse("done_word return 1: syntax error, "
4010 "groups and arglists don't mix\n");
4011 return 1;
4012 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004013
4014 /* If this word wasn't an assignment, next ones definitely
4015 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004016 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4017 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004018 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004019 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004020 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004021 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004022 command->assignment_cnt++;
4023 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4024 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004025 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4026 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004027 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004028 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4029 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004030 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004031 }
Eric Andersen25f27032001-04-26 23:22:31 +00004032
Denis Vlasenko06810332007-05-21 23:30:54 +00004033#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004034 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004035 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004036 || !is_well_formed_var_name(command->argv[0], '\0')
4037 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004038 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004039 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004040 return 1;
4041 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004042 /* Force FOR to have just one word (variable name) */
4043 /* NB: basically, this makes hush see "for v in ..."
4044 * syntax as if it is "for v; in ...". FOR and IN become
4045 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004046 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004047 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004048#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004049#if ENABLE_HUSH_CASE
4050 /* Force CASE to have just one word */
4051 if (ctx->ctx_res_w == RES_CASE) {
4052 done_pipe(ctx, PIPE_SEQ);
4053 }
4054#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004055
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004056 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004057
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004058 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004059 return 0;
4060}
4061
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004062
4063/* Peek ahead in the input to find out if we have a "&n" construct,
4064 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004065 * Return:
4066 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4067 * REDIRFD_SYNTAX_ERR if syntax error,
4068 * REDIRFD_TO_FILE if no & was seen,
4069 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004070 */
4071#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004072#define parse_redir_right_fd(as_string, input) \
4073 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004074#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004075static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004076{
4077 int ch, d, ok;
4078
4079 ch = i_peek(input);
4080 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004081 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004082
4083 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004084 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004085 ch = i_peek(input);
4086 if (ch == '-') {
4087 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004088 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004089 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004090 }
4091 d = 0;
4092 ok = 0;
4093 while (ch != EOF && isdigit(ch)) {
4094 d = d*10 + (ch-'0');
4095 ok = 1;
4096 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004097 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004098 ch = i_peek(input);
4099 }
4100 if (ok) return d;
4101
4102//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4103
4104 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004105 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004106}
4107
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004108/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004109 */
4110static int parse_redirect(struct parse_context *ctx,
4111 int fd,
4112 redir_type style,
4113 struct in_str *input)
4114{
4115 struct command *command = ctx->command;
4116 struct redir_struct *redir;
4117 struct redir_struct **redirp;
4118 int dup_num;
4119
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004120 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004121 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004122 /* Check for a '>&1' type redirect */
4123 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4124 if (dup_num == REDIRFD_SYNTAX_ERR)
4125 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004126 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004127 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004128 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004129 if (dup_num) { /* <<-... */
4130 ch = i_getch(input);
4131 nommu_addchr(&ctx->as_string, ch);
4132 ch = i_peek(input);
4133 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004134 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004135
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004136 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004137 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004138 if (ch == '|') {
4139 /* >|FILE redirect ("clobbering" >).
4140 * Since we do not support "set -o noclobber" yet,
4141 * >| and > are the same for now. Just eat |.
4142 */
4143 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004144 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004145 }
4146 }
4147
4148 /* Create a new redir_struct and append it to the linked list */
4149 redirp = &command->redirects;
4150 while ((redir = *redirp) != NULL) {
4151 redirp = &(redir->next);
4152 }
4153 *redirp = redir = xzalloc(sizeof(*redir));
4154 /* redir->next = NULL; */
4155 /* redir->rd_filename = NULL; */
4156 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004157 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004158
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004159 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4160 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004161
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004162 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004163 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004164 /* Erik had a check here that the file descriptor in question
4165 * is legit; I postpone that to "run time"
4166 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004167 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4168 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004169 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004170#if 0 /* Instead we emit error message at run time */
4171 if (ctx->pending_redirect) {
4172 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004173 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004174 }
4175#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004176 /* Set ctx->pending_redirect, so we know what to do at the
4177 * end of the next parsed word. */
4178 ctx->pending_redirect = redir;
4179 }
4180 return 0;
4181}
4182
Eric Andersen25f27032001-04-26 23:22:31 +00004183/* If a redirect is immediately preceded by a number, that number is
4184 * supposed to tell which file descriptor to redirect. This routine
4185 * looks for such preceding numbers. In an ideal world this routine
4186 * needs to handle all the following classes of redirects...
4187 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4188 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4189 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4190 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004191 *
4192 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4193 * "2.7 Redirection
4194 * ... If n is quoted, the number shall not be recognized as part of
4195 * the redirection expression. For example:
4196 * echo \2>a
4197 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004198 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004199 *
4200 * A -1 return means no valid number was found,
4201 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004202 */
4203static int redirect_opt_num(o_string *o)
4204{
4205 int num;
4206
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004207 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004208 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004209 num = bb_strtou(o->data, NULL, 10);
4210 if (errno || num < 0)
4211 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004212 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004213 return num;
4214}
4215
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004216#if BB_MMU
4217#define fetch_till_str(as_string, input, word, skip_tabs) \
4218 fetch_till_str(input, word, skip_tabs)
4219#endif
4220static char *fetch_till_str(o_string *as_string,
4221 struct in_str *input,
4222 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004223 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004224{
4225 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004226 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004227 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004228 int ch;
4229
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004230 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004231
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004232 while (1) {
4233 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004234 if (ch != EOF)
4235 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004236 if (ch == '\n' || ch == EOF) {
4237 check_heredoc_end:
4238 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4239 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4240 heredoc.data[past_EOL] = '\0';
4241 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4242 return heredoc.data;
4243 }
4244 if (ch == '\n') {
4245 /* This is a new line.
4246 * Remember position and backslash-escaping status.
4247 */
4248 o_addchr(&heredoc, ch);
4249 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004250 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004251 past_EOL = heredoc.length;
4252 /* Get 1st char of next line, possibly skipping leading tabs */
4253 do {
4254 ch = i_getch(input);
4255 if (ch != EOF)
4256 nommu_addchr(as_string, ch);
4257 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4258 /* If this immediately ended the line,
4259 * go back to end-of-line checks.
4260 */
4261 if (ch == '\n')
4262 goto check_heredoc_end;
4263 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004264 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004265 }
4266 if (ch == EOF) {
4267 o_free_unsafe(&heredoc);
4268 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004269 }
4270 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004271 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004272 if (prev == '\\' && ch == '\\')
4273 /* Correctly handle foo\\<eol> (not a line cont.) */
4274 prev = 0; /* not \ */
4275 else
4276 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004277 }
4278}
4279
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004280/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4281 * and load them all. There should be exactly heredoc_cnt of them.
4282 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004283static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4284{
4285 struct pipe *pi = ctx->list_head;
4286
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004287 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004288 int i;
4289 struct command *cmd = pi->cmds;
4290
4291 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4292 pi->num_cmds,
4293 cmd->argv ? cmd->argv[0] : "NONE");
4294 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004295 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004296
4297 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4298 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004299 while (redir) {
4300 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004301 char *p;
4302
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004303 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004304 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004305 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004306 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004307 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004308 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004309 return 1;
4310 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004311 free(redir->rd_filename);
4312 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004313 heredoc_cnt--;
4314 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004315 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004316 }
4317 cmd++;
4318 }
4319 pi = pi->next;
4320 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004321#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004322 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004323 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004324 bb_error_msg_and_die("heredoc BUG 2");
4325#endif
4326 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004327}
4328
4329
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004330static int run_list(struct pipe *pi);
4331#if BB_MMU
4332#define parse_stream(pstring, input, end_trigger) \
4333 parse_stream(input, end_trigger)
4334#endif
4335static struct pipe *parse_stream(char **pstring,
4336 struct in_str *input,
4337 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004338
Eric Andersen25f27032001-04-26 23:22:31 +00004339
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004340static int parse_group(struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004341 struct in_str *input, int ch)
4342{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004343 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004344 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004345 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004346#if BB_MMU
4347# define as_string NULL
4348#else
4349 char *as_string = NULL;
4350#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004351 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004352 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004353 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004354
4355 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004356#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004357 if (ch == '(' && !ctx->word.has_quoted_part) {
4358 if (ctx->word.length)
4359 if (done_word(ctx))
Denis Vlasenkobb929512009-04-16 10:59:40 +00004360 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004361 if (!command->argv)
4362 goto skip; /* (... */
4363 if (command->argv[1]) { /* word word ... (... */
4364 syntax_error_unexpected_ch('(');
4365 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004366 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004367 /* it is "word(..." or "word (..." */
4368 do
4369 ch = i_getch(input);
4370 while (ch == ' ' || ch == '\t');
4371 if (ch != ')') {
4372 syntax_error_unexpected_ch(ch);
4373 return 1;
4374 }
4375 nommu_addchr(&ctx->as_string, ch);
4376 do
4377 ch = i_getch(input);
4378 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004379 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004380 syntax_error_unexpected_ch(ch);
4381 return 1;
4382 }
4383 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004384 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004385 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004386 }
4387#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004388
4389#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004390 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004391 || ctx->word.length /* word{... */
4392 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004393 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004394 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004395 debug_printf_parse("parse_group return 1: "
4396 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004397 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004398 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004399#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004400
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004401 IF_HUSH_FUNCTIONS(skip:)
4402
Denis Vlasenko240c2552009-04-03 03:45:05 +00004403 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004404 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004405 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004406 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4407 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004408 } else {
4409 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004410 ch = i_peek(input);
4411 if (ch != ' ' && ch != '\t' && ch != '\n'
4412 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4413 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004414 syntax_error_unexpected_ch(ch);
4415 return 1;
4416 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004417 if (ch != '(') {
4418 ch = i_getch(input);
4419 nommu_addchr(&ctx->as_string, ch);
4420 }
Eric Andersen25f27032001-04-26 23:22:31 +00004421 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004422
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004423 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004424#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004425 if (as_string)
4426 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004427#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004428
4429 /* empty ()/{} or parse error? */
4430 if (!pipe_list || pipe_list == ERR_PTR) {
4431 /* parse_stream already emitted error msg */
4432 if (!BB_MMU)
4433 free(as_string);
4434 debug_printf_parse("parse_group return 1: "
4435 "parse_stream returned %p\n", pipe_list);
4436 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004437 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004438#if !BB_MMU
4439 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4440 command->group_as_string = as_string;
4441 debug_printf_parse("end of group, remembering as:'%s'\n",
4442 command->group_as_string);
4443#endif
4444
4445#if ENABLE_HUSH_FUNCTIONS
4446 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4447 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4448 struct command *cmd2;
4449
4450 cmd2 = xzalloc(sizeof(*cmd2));
4451 cmd2->cmd_type = CMD_SUBSHELL;
4452 cmd2->group = pipe_list;
4453# if !BB_MMU
4454//UNTESTED!
4455 cmd2->group_as_string = command->group_as_string;
4456 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4457# endif
4458
4459 pipe_list = new_pipe();
4460 pipe_list->cmds = cmd2;
4461 pipe_list->num_cmds = 1;
4462 }
4463#endif
4464
4465 command->group = pipe_list;
4466
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004467 debug_printf_parse("parse_group return 0\n");
4468 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004469 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004470#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004471}
4472
Denys Vlasenko0b883582016-12-23 16:49:07 +01004473#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004474/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004475static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004476/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004477static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004478{
4479 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004480 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004481 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004482 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004483 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004484 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004485 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004486 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004487 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004488 }
4489}
4490/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004491static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004492{
4493 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004494 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004495 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004496 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004497 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004498 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004499 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004500 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004501 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004502 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004503 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004504 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004505 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004506 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004507 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4508 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004509 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004510 continue;
4511 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004512 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004513 }
4514}
4515/* Process `cmd` - copy contents until "`" is seen. Complicated by
4516 * \` quoting.
4517 * "Within the backquoted style of command substitution, backslash
4518 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4519 * The search for the matching backquote shall be satisfied by the first
4520 * backquote found without a preceding backslash; during this search,
4521 * if a non-escaped backquote is encountered within a shell comment,
4522 * a here-document, an embedded command substitution of the $(command)
4523 * form, or a quoted string, undefined results occur. A single-quoted
4524 * or double-quoted string that begins, but does not end, within the
4525 * "`...`" sequence produces undefined results."
4526 * Example Output
4527 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4528 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004529static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004530{
4531 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004532 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004533 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004534 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004535 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004536 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4537 ch = i_getch(input);
4538 if (ch != '`'
4539 && ch != '$'
4540 && ch != '\\'
4541 && (!in_dquote || ch != '"')
4542 ) {
4543 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004544 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004545 }
4546 if (ch == EOF) {
4547 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004548 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004549 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004550 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004551 }
4552}
4553/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4554 * quoting and nested ()s.
4555 * "With the $(command) style of command substitution, all characters
4556 * following the open parenthesis to the matching closing parenthesis
4557 * constitute the command. Any valid shell script can be used for command,
4558 * except a script consisting solely of redirections which produces
4559 * unspecified results."
4560 * Example Output
4561 * echo $(echo '(TEST)' BEST) (TEST) BEST
4562 * echo $(echo 'TEST)' BEST) TEST) BEST
4563 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004564 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004565 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004566 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004567 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4568 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004569 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004570#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004571static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004572{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004573 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004574 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004575# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004576 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004577# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004578 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4579
Denys Vlasenko817a2022018-06-26 15:35:17 +02004580#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004581 G.promptmode = 1; /* PS2 */
Denys Vlasenko817a2022018-06-26 15:35:17 +02004582#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004583 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4584
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004585 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004586 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004587 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004588 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004589 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004590 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004591 if (ch == end_ch
4592# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004593 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004594# endif
4595 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004596 if (!dbl)
4597 break;
4598 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004599 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004600 i_getch(input); /* eat second ')' */
4601 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004602 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004603 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004604 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004605 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004606 if (ch == '(' || ch == '{') {
4607 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004608 if (!add_till_closing_bracket(dest, input, ch))
4609 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004610 o_addchr(dest, ch);
4611 continue;
4612 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004613 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004614 if (!add_till_single_quote(dest, input))
4615 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004616 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004617 continue;
4618 }
4619 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004620 if (!add_till_double_quote(dest, input))
4621 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004622 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004623 continue;
4624 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004625 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004626 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4627 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004628 o_addchr(dest, ch);
4629 continue;
4630 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004631 if (ch == '\\') {
4632 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004633 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004634 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004635 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004636 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004637 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004638#if 0
4639 if (ch == '\n') {
4640 /* "backslash+newline", ignore both */
4641 o_delchr(dest); /* undo insertion of '\' */
4642 continue;
4643 }
4644#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004645 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004646 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004647 continue;
4648 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004649 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004650 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004651 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004652}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004653#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004654
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004655/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004656#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004657#define parse_dollar(as_string, dest, input, quote_mask) \
4658 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004659#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004660#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004661static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004662 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004663 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004664{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004665 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004666
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004667 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004668 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004669 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004670 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004671 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004672 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004673 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004674 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004675 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004676 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004677 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004678 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004679 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004680 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004681 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004682 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004683 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004684 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004685 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004686 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004687 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004688 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004689 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004690 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004691 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004692 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004693 o_addchr(dest, ch | quote_mask);
4694 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004695 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004696 case '$': /* pid */
4697 case '!': /* last bg pid */
4698 case '?': /* last exit code */
4699 case '#': /* number of args */
4700 case '*': /* args */
4701 case '@': /* args */
4702 goto make_one_char_var;
4703 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004704 char len_single_ch;
4705
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004706 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4707
Denys Vlasenko74369502010-05-21 19:52:01 +02004708 ch = i_getch(input); /* eat '{' */
4709 nommu_addchr(as_string, ch);
4710
Denys Vlasenko46e64982016-09-29 19:50:55 +02004711 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004712 /* It should be ${?}, or ${#var},
4713 * or even ${?+subst} - operator acting on a special variable,
4714 * or the beginning of variable name.
4715 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004716 if (ch == EOF
4717 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4718 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004719 bad_dollar_syntax:
4720 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004721 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4722 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004723 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004724 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004725 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004726 ch |= quote_mask;
4727
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004728 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004729 * However, this regresses some of our testsuite cases
4730 * which check invalid constructs like ${%}.
4731 * Oh well... let's check that the var name part is fine... */
4732
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004733 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004734 unsigned pos;
4735
Denys Vlasenko74369502010-05-21 19:52:01 +02004736 o_addchr(dest, ch);
4737 debug_printf_parse(": '%c'\n", ch);
4738
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004739 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004740 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004741 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004742 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004743
Denys Vlasenko74369502010-05-21 19:52:01 +02004744 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004745 unsigned end_ch;
4746 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004747 /* handle parameter expansions
4748 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4749 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004750 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4751 if (len_single_ch != '#'
4752 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4753 || i_peek(input) != '}'
4754 ) {
4755 goto bad_dollar_syntax;
4756 }
4757 /* else: it's "length of C" ${#C} op,
4758 * where C is a single char
4759 * special var name, e.g. ${#!}.
4760 */
4761 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004762 /* Eat everything until closing '}' (or ':') */
4763 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004764 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004765 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004766 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004767 ) {
4768 /* It's ${var:N[:M]} thing */
4769 end_ch = '}' * 0x100 + ':';
4770 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004771 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004772 && ch == '/'
4773 ) {
4774 /* It's ${var/[/]pattern[/repl]} thing */
4775 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4776 i_getch(input);
4777 nommu_addchr(as_string, '/');
4778 ch = '\\';
4779 }
4780 end_ch = '}' * 0x100 + '/';
4781 }
4782 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004783 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004784 if (!BB_MMU)
4785 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004786#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004787 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004788 if (last_ch == 0) /* error? */
4789 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004790#else
4791#error Simple code to only allow ${var} is not implemented
4792#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004793 if (as_string) {
4794 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004795 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004796 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004797
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004798 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4799 && (end_ch & 0xff00)
4800 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004801 /* close the first block: */
4802 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004803 /* while parsing N from ${var:N[:M]}
4804 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004805 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004806 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004807 end_ch = '}';
4808 goto again;
4809 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004810 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004811 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004812 /* it's ${var:N} - emulate :999999999 */
4813 o_addstr(dest, "999999999");
4814 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004815 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004816 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004817 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004818 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004819 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004820 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4821 break;
4822 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004823#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004824 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004825 unsigned pos;
4826
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004827 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004828 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004829# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004830 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004831 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004832 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004833 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4834 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004835 if (!BB_MMU)
4836 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004837 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4838 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004839 if (as_string) {
4840 o_addstr(as_string, dest->data + pos);
4841 o_addchr(as_string, ')');
4842 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004843 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004844 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004845 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004846 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004847# endif
4848# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004849 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4850 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004851 if (!BB_MMU)
4852 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004853 if (!add_till_closing_bracket(dest, input, ')'))
4854 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004855 if (as_string) {
4856 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004857 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004858 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004859 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004860# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004861 break;
4862 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004863#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004864 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004865 goto make_var;
4866#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004867 /* TODO: $_ and $-: */
4868 /* $_ Shell or shell script name; or last argument of last command
4869 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4870 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004871 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004872 ch = i_getch(input);
4873 nommu_addchr(as_string, ch);
4874 ch = i_peek_and_eat_bkslash_nl(input);
4875 if (isalnum(ch)) { /* it's $_name or $_123 */
4876 ch = '_';
4877 goto make_var1;
4878 }
4879 /* else: it's $_ */
4880#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004881 default:
4882 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004883 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004884 debug_printf_parse("parse_dollar return 1 (ok)\n");
4885 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004886#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004887}
4888
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004889#if BB_MMU
Denys Vlasenkob762c782018-07-17 14:21:38 +02004890#define encode_string(as_string, dest, input, dquote_end) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004891 encode_string(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004892#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004893#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004894static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004895 o_string *dest,
4896 struct in_str *input,
Denys Vlasenkob762c782018-07-17 14:21:38 +02004897 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004898{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004899 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004900 int next;
4901
4902 again:
4903 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004904 if (ch != EOF)
4905 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004906 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004907 debug_printf_parse("encode_string return 1 (ok)\n");
4908 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004909 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004910 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004911 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004912 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004913 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004914 }
4915 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004916 if (ch != '\n') {
4917 next = i_peek(input);
4918 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004919 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004920 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob762c782018-07-17 14:21:38 +02004921 if (ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004922 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02004923 /* Testcase: in interactive shell a file with
4924 * echo "unterminated string\<eof>
4925 * is sourced.
4926 */
4927 syntax_error_unterm_ch('"');
4928 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004929 }
4930 /* bash:
4931 * "The backslash retains its special meaning [in "..."]
4932 * only when followed by one of the following characters:
4933 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004934 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004935 * NB: in (unquoted) heredoc, above does not apply to ",
4936 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004937 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004938 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004939 ch = i_getch(input); /* eat next */
4940 if (ch == '\n')
4941 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004942 } /* else: ch remains == '\\', and we double it below: */
4943 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004944 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004945 goto again;
4946 }
4947 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004948 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4949 debug_printf_parse("encode_string return 0: "
4950 "parse_dollar returned 0 (error)\n");
4951 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004952 }
4953 goto again;
4954 }
4955#if ENABLE_HUSH_TICK
4956 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004957 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004958 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4959 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004960 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4961 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004962 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4963 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004964 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004965 }
4966#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004967 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004968 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004969#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004970}
4971
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004972/*
4973 * Scan input until EOF or end_trigger char.
4974 * Return a list of pipes to execute, or NULL on EOF
4975 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004976 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004977 * reset parsing machinery and start parsing anew,
4978 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004979 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004980static struct pipe *parse_stream(char **pstring,
4981 struct in_str *input,
4982 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004983{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004984 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004985 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004986
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004987 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004988 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004989 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004990 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004991 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004992 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004993
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004994 initialize_context(&ctx);
4995
4996 /* If very first arg is "" or '', ctx.word.data may end up NULL.
4997 * Preventing this:
4998 */
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02004999 ctx.word.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005000
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005001 /* We used to separate words on $IFS here. This was wrong.
5002 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005003 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005004 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005005
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005006 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005007 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005008 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005009 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005010 int ch;
5011 int next;
5012 int redir_fd;
5013 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005014
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005015 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005016 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005017 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005018 if (ch == EOF) {
5019 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005020
5021 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005022 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005023 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005024 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005025 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005026 syntax_error_unterm_ch('(');
5027 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005028 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005029 if (end_trigger == '}') {
5030 syntax_error_unterm_ch('{');
5031 goto parse_error;
5032 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005033
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005034 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005035 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005036 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005037 o_free(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005038 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005039 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005040 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005041 /* (this makes bare "&" cmd a no-op.
5042 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005043 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005044 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005045 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005046 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005047 pi = NULL;
5048 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005049#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005050 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005051 if (pstring)
5052 *pstring = ctx.as_string.data;
5053 else
5054 o_free_unsafe(&ctx.as_string);
5055#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005056 debug_leave();
5057 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005058 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005059 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005060
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005061 /* Handle "'" and "\" first, as they won't play nice with
5062 * i_peek_and_eat_bkslash_nl() anyway:
5063 * echo z\\
5064 * and
5065 * echo '\
5066 * '
5067 * would break.
5068 */
Denys Vlasenkof693b602018-04-11 20:00:43 +02005069 if (ch == '\\') {
5070 ch = i_getch(input);
5071 if (ch == '\n')
5072 continue; /* drop \<newline>, get next char */
5073 nommu_addchr(&ctx.as_string, '\\');
5074 o_addchr(&ctx.word, '\\');
5075 if (ch == EOF) {
5076 /* Testcase: eval 'echo Ok\' */
5077 /* bash-4.3.43 was removing backslash,
5078 * but 4.4.19 retains it, most other shells too
5079 */
5080 continue; /* get next char */
5081 }
5082 /* Example: echo Hello \2>file
5083 * we need to know that word 2 is quoted
5084 */
5085 ctx.word.has_quoted_part = 1;
5086 nommu_addchr(&ctx.as_string, ch);
5087 o_addchr(&ctx.word, ch);
5088 continue; /* get next char */
5089 }
5090 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005091 if (ch == '\'') {
5092 ctx.word.has_quoted_part = 1;
5093 next = i_getch(input);
5094 if (next == '\'' && !ctx.pending_redirect)
5095 goto insert_empty_quoted_str_marker;
5096
5097 ch = next;
5098 while (1) {
5099 if (ch == EOF) {
5100 syntax_error_unterm_ch('\'');
5101 goto parse_error;
5102 }
5103 nommu_addchr(&ctx.as_string, ch);
5104 if (ch == '\'')
5105 break;
5106 if (ch == SPECIAL_VAR_SYMBOL) {
5107 /* Convert raw ^C to corresponding special variable reference */
5108 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5109 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5110 }
5111 o_addqchr(&ctx.word, ch);
5112 ch = i_getch(input);
5113 }
5114 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005115 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005116
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005117 next = '\0';
5118 if (ch != '\n')
5119 next = i_peek_and_eat_bkslash_nl(input);
5120
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005121 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005122 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005123 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005124 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005125 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005126 || ctx.word.length /* word{... - non-special */
5127 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005128 || (next != ';' /* }; - special */
5129 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005130 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005131 && next != '&' /* }& and }&& ... - special */
5132 && next != '|' /* }|| ... - special */
5133 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005134 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005135 ) {
5136 /* They are not special, skip "{}" */
5137 is_special += 2;
5138 }
5139 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005140 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005141
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005142 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005143 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005144 o_addQchr(&ctx.word, ch);
5145 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5146 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005147 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005148 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005149 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005150 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5151 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005152 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005153 continue;
5154 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005155
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005156 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005157#if ENABLE_HUSH_LINENO_VAR
5158/* Case:
5159 * "while ...; do<whitespace><newline>
5160 * cmd ..."
5161 * would think that "cmd" starts in <whitespace> -
5162 * i.e., at the previous line.
5163 * We need to skip all whitespace before newlines.
5164 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005165 while (ch != '\n') {
5166 next = i_peek(input);
5167 if (next != ' ' && next != '\t' && next != '\n')
5168 break; /* next char is not ws */
5169 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005170 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005171 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005172#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005173 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005174 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005175 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005176 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005177 /* Is this a case when newline is simply ignored?
5178 * Some examples:
5179 * "cmd | <newline> cmd ..."
5180 * "case ... in <newline> word) ..."
5181 */
5182 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005183 && ctx.word.length == 0 && !ctx.word.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005184 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005185 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005186 * Without check #1, interactive shell
5187 * ignores even bare <newline>,
5188 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005189 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005190 * ps2> _ <=== wrong, should be ps1
5191 * Without check #2, "cmd & <newline>"
5192 * is similarly mistreated.
5193 * (BTW, this makes "cmd & cmd"
5194 * and "cmd && cmd" non-orthogonal.
5195 * Really, ask yourself, why
5196 * "cmd && <newline>" doesn't start
5197 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005198 * The only reason is that it might be
5199 * a "cmd1 && <nl> cmd2 &" construct,
5200 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005201 */
5202 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005203 if (pi->num_cmds != 0 /* check #1 */
5204 && pi->followup != PIPE_BG /* check #2 */
5205 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005206 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005207 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005208 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005209 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005210 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005211 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5212 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005213 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005214 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005215 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005216 heredoc_cnt = 0;
5217 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005218 ctx.is_assignment = MAYBE_ASSIGNMENT;
5219 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005220 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005221 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005222 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005223 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005224 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005225
5226 /* "cmd}" or "cmd }..." without semicolon or &:
5227 * } is an ordinary char in this case, even inside { cmd; }
5228 * Pathological example: { ""}; } should exec "}" cmd
5229 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005230 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005231 if (ctx.word.length != 0 /* word} */
5232 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005233 ) {
5234 goto ordinary_char;
5235 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005236 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5237 /* Generally, there should be semicolon: "cmd; }"
5238 * However, bash allows to omit it if "cmd" is
5239 * a group. Examples:
5240 * { { echo 1; } }
5241 * {(echo 1)}
5242 * { echo 0 >&2 | { echo 1; } }
5243 * { while false; do :; done }
5244 * { case a in b) ;; esac }
5245 */
5246 if (ctx.command->group)
5247 goto term_group;
5248 goto ordinary_char;
5249 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005250 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005251 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005252 goto skip_end_trigger;
5253 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005254 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005255 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005256 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005257 && (ch != ';' || heredoc_cnt == 0)
5258#if ENABLE_HUSH_CASE
5259 && (ch != ')'
5260 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005261 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005262 )
5263#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005264 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005265 if (heredoc_cnt) {
5266 /* This is technically valid:
5267 * { cat <<HERE; }; echo Ok
5268 * heredoc
5269 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005270 * HERE
5271 * but we don't support this.
5272 * We require heredoc to be in enclosing {}/(),
5273 * if any.
5274 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005275 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005276 goto parse_error;
5277 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005278 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005279 goto parse_error;
5280 }
5281 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005282 ctx.is_assignment = MAYBE_ASSIGNMENT;
5283 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005284 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005285 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005286 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005287 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005288 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005289#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005290 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005291 if (pstring)
5292 *pstring = ctx.as_string.data;
5293 else
5294 o_free_unsafe(&ctx.as_string);
5295#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005296 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5297 /* Example: bare "{ }", "()" */
5298 G.last_exitcode = 2; /* bash compat */
5299 syntax_error_unexpected_ch(ch);
5300 goto parse_error2;
5301 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005302 debug_printf_parse("parse_stream return %p: "
5303 "end_trigger char found\n",
5304 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005305 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005306 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005307 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005308 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005309
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005310 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005311 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005312
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005313 /* Catch <, > before deciding whether this word is
5314 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5315 switch (ch) {
5316 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005317 redir_fd = redirect_opt_num(&ctx.word);
5318 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005319 goto parse_error;
5320 }
5321 redir_style = REDIRECT_OVERWRITE;
5322 if (next == '>') {
5323 redir_style = REDIRECT_APPEND;
5324 ch = i_getch(input);
5325 nommu_addchr(&ctx.as_string, ch);
5326 }
5327#if 0
5328 else if (next == '(') {
5329 syntax_error(">(process) not supported");
5330 goto parse_error;
5331 }
5332#endif
5333 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5334 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005335 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005336 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005337 redir_fd = redirect_opt_num(&ctx.word);
5338 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005339 goto parse_error;
5340 }
5341 redir_style = REDIRECT_INPUT;
5342 if (next == '<') {
5343 redir_style = REDIRECT_HEREDOC;
5344 heredoc_cnt++;
5345 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5346 ch = i_getch(input);
5347 nommu_addchr(&ctx.as_string, ch);
5348 } else if (next == '>') {
5349 redir_style = REDIRECT_IO;
5350 ch = i_getch(input);
5351 nommu_addchr(&ctx.as_string, ch);
5352 }
5353#if 0
5354 else if (next == '(') {
5355 syntax_error("<(process) not supported");
5356 goto parse_error;
5357 }
5358#endif
5359 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5360 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005361 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005362 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005363 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005364 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005365 /* note: we do not add it to &ctx.as_string */
5366/* TODO: in bash:
5367 * comment inside $() goes to the next \n, even inside quoted string (!):
5368 * cmd "$(cmd2 #comment)" - syntax error
5369 * cmd "`cmd2 #comment`" - ok
5370 * We accept both (comment ends where command subst ends, in both cases).
5371 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005372 while (1) {
5373 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005374 if (ch == '\n') {
5375 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005376 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005377 }
5378 ch = i_getch(input);
5379 if (ch == EOF)
5380 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005381 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005382 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005383 }
5384 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005385 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005386 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005387
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005388 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005389 /* check that we are not in word in "a=1 2>word b=1": */
5390 && !ctx.pending_redirect
5391 ) {
5392 /* ch is a special char and thus this word
5393 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005394 ctx.is_assignment = NOT_ASSIGNMENT;
5395 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005396 }
5397
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005398 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5399
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005400 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005401 case SPECIAL_VAR_SYMBOL:
5402 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005403 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5404 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005405 /* fall through */
5406 case '#':
5407 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005408 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005409 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005410 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005411 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005412 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005413 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005414 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005415 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005416 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005417 case '"':
5418 ctx.word.has_quoted_part = 1;
5419 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005420 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005421 insert_empty_quoted_str_marker:
5422 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005423 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5424 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005425 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005426 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005427 if (ctx.is_assignment == NOT_ASSIGNMENT)
5428 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005429 if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005430 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005431 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005432 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005433#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005434 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005435 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005436
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005437 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5438 o_addchr(&ctx.word, '`');
5439 USE_FOR_NOMMU(pos = ctx.word.length;)
5440 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005441 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005442# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005443 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005444 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005445# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005446 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5447 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005448 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005449 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005450#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005451 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005452#if ENABLE_HUSH_CASE
5453 case_semi:
5454#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005455 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005456 goto parse_error;
5457 }
5458 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005459#if ENABLE_HUSH_CASE
5460 /* Eat multiple semicolons, detect
5461 * whether it means something special */
5462 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005463 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005464 if (ch != ';')
5465 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005466 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005467 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005468 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005469 ctx.ctx_dsemicolon = 1;
5470 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005471 break;
5472 }
5473 }
5474#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005475 new_cmd:
5476 /* We just finished a cmd. New one may start
5477 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005478 ctx.is_assignment = MAYBE_ASSIGNMENT;
5479 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005480 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005481 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005482 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005483 goto parse_error;
5484 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005485 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005486 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005487 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005488 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005489 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005490 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005491 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005492 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005493 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005494 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005495 goto parse_error;
5496 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005497#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005498 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005499 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005500#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005501 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005502 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005503 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005504 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005505 } else {
5506 /* we could pick up a file descriptor choice here
5507 * with redirect_opt_num(), but bash doesn't do it.
5508 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005509 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005510 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005511 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005512 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005513#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005514 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005515 if (ctx.ctx_res_w == RES_MATCH
5516 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005517 && ctx.word.length == 0 /* not word(... */
5518 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005519 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005520 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005521 }
5522#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005523 case '{':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005524 if (parse_group(&ctx, input, ch) != 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005525 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005526 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005527 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005528 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005529#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005530 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005531 goto case_semi;
5532#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005533 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005534 /* proper use of this character is caught by end_trigger:
5535 * if we see {, we call parse_group(..., end_trigger='}')
5536 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005537 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005538 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005539 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005540 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005541 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005542 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005543 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005544 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005545
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005546 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005547 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005548 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005549 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005550 struct parse_context *pctx;
5551 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005552
5553 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005554 * Sample for finding leaks on syntax error recovery path.
5555 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005556 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005557 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005558 * while if (true | { true;}); then echo ok; fi; do break; done
5559 * 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 +00005560 */
5561 pctx = &ctx;
5562 do {
5563 /* Update pipe/command counts,
5564 * otherwise freeing may miss some */
5565 done_pipe(pctx, PIPE_SEQ);
5566 debug_printf_clean("freeing list %p from ctx %p\n",
5567 pctx->list_head, pctx);
5568 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005569 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005570 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005571#if !BB_MMU
5572 o_free_unsafe(&pctx->as_string);
5573#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005574 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005575 if (pctx != &ctx) {
5576 free(pctx);
5577 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005578 IF_HAS_KEYWORDS(pctx = p2;)
5579 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005580
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005581 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005582#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005583 if (pstring)
5584 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005585#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005586 debug_leave();
5587 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005588 }
Eric Andersen25f27032001-04-26 23:22:31 +00005589}
5590
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005591
5592/*** Execution routines ***/
5593
5594/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005595#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenko34179952018-04-11 13:47:59 +02005596#define expand_string_to_string(str, EXP_flags, do_unbackslash) \
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005597 expand_string_to_string(str)
5598#endif
Denys Vlasenko34179952018-04-11 13:47:59 +02005599static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005600#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005601static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005602#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005603
5604/* expand_strvec_to_strvec() takes a list of strings, expands
5605 * all variable references within and returns a pointer to
5606 * a list of expanded strings, possibly with larger number
5607 * of strings. (Think VAR="a b"; echo $VAR).
5608 * This new list is allocated as a single malloc block.
5609 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005610 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005611 * Caller can deallocate entire list by single free(list). */
5612
Denys Vlasenko238081f2010-10-03 14:26:26 +02005613/* A horde of its helpers come first: */
5614
5615static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5616{
5617 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005618 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005619
Denys Vlasenko9e800222010-10-03 14:28:04 +02005620#if ENABLE_HUSH_BRACE_EXPANSION
5621 if (c == '{' || c == '}') {
5622 /* { -> \{, } -> \} */
5623 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005624 /* And now we want to add { or } and continue:
5625 * o_addchr(o, c);
5626 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005627 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005628 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005629 }
5630#endif
5631 o_addchr(o, c);
5632 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005633 /* \z -> \\\z; \<eol> -> \\<eol> */
5634 o_addchr(o, '\\');
5635 if (len) {
5636 len--;
5637 o_addchr(o, '\\');
5638 o_addchr(o, *str++);
5639 }
5640 }
5641 }
5642}
5643
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005644/* Store given string, finalizing the word and starting new one whenever
5645 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005646 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
Denys Vlasenko168579a2018-07-19 13:45:54 +02005647 * Return in output->ended_in_ifs:
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005648 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5649 */
Denys Vlasenko168579a2018-07-19 13:45:54 +02005650static int expand_on_ifs(o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005651{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005652 int last_is_ifs = 0;
5653
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005654 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005655 int word_len;
5656
5657 if (!*str) /* EOL - do not finalize word */
5658 break;
5659 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005660 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005661 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005662 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005663 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005664 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005665 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005666 * Example: "v='\*'; echo b$v" prints "b\*"
5667 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005668 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005669 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005670 /*/ Why can't we do it easier? */
5671 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5672 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5673 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005674 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005675 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005676 if (!*str) /* EOL - do not finalize word */
5677 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005678 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005679
5680 /* We know str here points to at least one IFS char */
5681 last_is_ifs = 1;
Denys Vlasenko96786362018-04-11 16:02:58 +02005682 str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005683 if (!*str) /* EOL - do not finalize word */
5684 break;
5685
Denys Vlasenko96786362018-04-11 16:02:58 +02005686 if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
5687 && strchr(G.ifs, *str) /* the second check would fail */
5688 ) {
5689 /* This is a non-whitespace $IFS char */
5690 /* Skip it and IFS whitespace chars, start new word */
5691 str++;
5692 str += strspn(str, G.ifs_whitespace);
5693 goto new_word;
5694 }
5695
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005696 /* Start new word... but not always! */
5697 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005698 if (output->has_quoted_part
5699 /* Case "v=' a'; echo $v":
5700 * here nothing precedes the space in $v expansion,
5701 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005702 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005703 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005704 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005705 ) {
Denys Vlasenko96786362018-04-11 16:02:58 +02005706 new_word:
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005707 o_addchr(output, '\0');
5708 debug_print_list("expand_on_ifs", output, n);
5709 n = o_save_ptr(output, n);
5710 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005711 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005712
Denys Vlasenko168579a2018-07-19 13:45:54 +02005713 output->ended_in_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005714 debug_print_list("expand_on_ifs[1]", output, n);
5715 return n;
5716}
5717
5718/* Helper to expand $((...)) and heredoc body. These act as if
5719 * they are in double quotes, with the exception that they are not :).
5720 * Just the rules are similar: "expand only $var and `cmd`"
5721 *
5722 * Returns malloced string.
5723 * As an optimization, we return NULL if expansion is not needed.
5724 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005725static char *encode_then_expand_string(const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005726{
5727 char *exp_str;
5728 struct in_str input;
5729 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005730 const char *cp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005731
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005732 cp = str;
5733 for (;;) {
5734 if (!*cp) return NULL; /* string has no special chars */
5735 if (*cp == '$') break;
5736 if (*cp == '\\') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005737#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005738 if (*cp == '`') break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005739#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005740 cp++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005741 }
5742
5743 /* We need to expand. Example:
5744 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5745 */
5746 setup_string_in_str(&input, str);
Denys Vlasenkob762c782018-07-17 14:21:38 +02005747 encode_string(NULL, &dest, &input, EOF);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005748//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005749 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenko34179952018-04-11 13:47:59 +02005750 exp_str = expand_string_to_string(dest.data,
Denys Vlasenkob762c782018-07-17 14:21:38 +02005751 EXP_FLAG_ESC_GLOB_CHARS,
5752 /*unbackslash:*/ 1
5753 );
5754 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5755 o_free_unsafe(&dest);
5756 return exp_str;
5757}
5758
5759#if !BASH_PATTERN_SUBST
5760#define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
5761 encode_then_expand_vararg(str, handle_squotes)
5762#endif
5763static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
5764{
5765#if !BASH_PATTERN_SUBST
5766 const int do_unbackslash = 0;
5767#endif
5768 char *exp_str;
5769 struct in_str input;
5770 o_string dest = NULL_O_STRING;
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005771 const char *cp;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005772
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005773 cp = str;
5774 for (;;) {
5775 if (!*cp) return NULL; /* string has no special chars */
5776 if (*cp == '$') break;
5777 if (*cp == '\\') break;
5778 if (*cp == '\'') break;
5779 if (*cp == '"') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005780#if ENABLE_HUSH_TICK
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005781 if (*cp == '`') break;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005782#endif
Denys Vlasenko0d2e0de2018-07-17 14:33:19 +02005783 cp++;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005784 }
5785
5786 /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
5787 * These can contain single- and double-quoted strings,
5788 * and treated as if the ARG string is initially unquoted. IOW:
5789 * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
5790 * a dquoted string: "${var#"zz"}"), the difference only comes later
5791 * (word splitting and globbing of the ${var...} result).
5792 */
5793
5794 setup_string_in_str(&input, str);
Denys Vlasenko8b08d5a2018-07-18 15:48:53 +02005795 dest.data = xzalloc(1); /* start as "", not as NULL */
Denys Vlasenkob762c782018-07-17 14:21:38 +02005796 exp_str = NULL;
5797
5798 for (;;) {
5799 int ch;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005800
5801 ch = i_getch(&input);
5802 if (ch == EOF) {
5803 if (dest.o_expflags) { /* EXP_FLAG_ESC_GLOB_CHARS set? */
5804 syntax_error_unterm_ch('"');
5805 goto ret; /* error */
5806 }
5807 break;
5808 }
5809 debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
5810 __func__, ch, ch, !!dest.o_expflags);
5811 if (ch == '\'' && handle_squotes && !dest.o_expflags) {
5812//quoting version of add_till_single_quote() (try to merge?):
5813 for (;;) {
5814 ch = i_getch(&input);
5815 if (ch == EOF) {
5816 syntax_error_unterm_ch('\'');
5817 goto ret; /* error */
5818 }
5819 if (ch == '\'')
5820 break;
5821 o_addqchr(&dest, ch);
5822 }
5823 continue;
5824 }
5825 if (ch == '"') {
5826 dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
5827 continue;
5828 }
5829 if (ch == '\\') {
5830 ch = i_getch(&input);
5831 if (ch == EOF) {
5832//example? error message? syntax_error_unterm_ch('"');
5833 debug_printf_parse("%s: error: \\<eof>\n", __func__);
5834 goto ret;
5835 }
5836 o_addqchr(&dest, ch);
5837 continue;
5838 }
Denys Vlasenkob762c782018-07-17 14:21:38 +02005839 if (ch == '$') {
5840 if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
5841 debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
5842 goto ret;
5843 }
5844 continue;
5845 }
5846#if ENABLE_HUSH_TICK
5847 if (ch == '`') {
5848 //unsigned pos = dest->length;
5849 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5850 o_addchr(&dest, 0x80 | '`');
5851 if (!add_till_backquote(&dest, &input,
5852 /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
5853 )
5854 ) {
5855 goto ret; /* error */
5856 }
5857 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5858 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5859 continue;
5860 }
5861#endif
5862 o_addQchr(&dest, ch);
5863 } /* for (;;) */
5864
5865 debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
5866 exp_str = expand_string_to_string(dest.data,
Denys Vlasenko34179952018-04-11 13:47:59 +02005867 do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
5868 do_unbackslash
5869 );
Denys Vlasenkob762c782018-07-17 14:21:38 +02005870 ret:
5871 debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005872 o_free_unsafe(&dest);
5873 return exp_str;
5874}
5875
Denys Vlasenko0b883582016-12-23 16:49:07 +01005876#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005877static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005878{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005879 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005880 arith_t res;
5881 char *exp_str;
5882
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005883 math_state.lookupvar = get_local_var_value;
5884 math_state.setvar = set_local_var_from_halves;
5885 //math_state.endofname = endofname;
Denys Vlasenkob762c782018-07-17 14:21:38 +02005886 exp_str = encode_then_expand_string(arg);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005887 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005888 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005889 if (errmsg_p)
5890 *errmsg_p = math_state.errmsg;
5891 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005892 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005893 return res;
5894}
5895#endif
5896
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005897#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005898/* ${var/[/]pattern[/repl]} helpers */
5899static char *strstr_pattern(char *val, const char *pattern, int *size)
5900{
5901 while (1) {
5902 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5903 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5904 if (end) {
5905 *size = end - val;
5906 return val;
5907 }
5908 if (*val == '\0')
5909 return NULL;
5910 /* Optimization: if "*pat" did not match the start of "string",
5911 * we know that "tring", "ring" etc will not match too:
5912 */
5913 if (pattern[0] == '*')
5914 return NULL;
5915 val++;
5916 }
5917}
5918static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5919{
5920 char *result = NULL;
5921 unsigned res_len = 0;
5922 unsigned repl_len = strlen(repl);
5923
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005924 /* Null pattern never matches, including if "var" is empty */
5925 if (!pattern[0])
5926 return result; /* NULL, no replaces happened */
5927
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005928 while (1) {
5929 int size;
5930 char *s = strstr_pattern(val, pattern, &size);
5931 if (!s)
5932 break;
5933
5934 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005935 strcpy(mempcpy(result + res_len, val, s - val), repl);
5936 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005937 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5938
5939 val = s + size;
5940 if (exp_op == '/')
5941 break;
5942 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005943 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005944 result = xrealloc(result, res_len + strlen(val) + 1);
5945 strcpy(result + res_len, val);
5946 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5947 }
5948 debug_printf_varexp("result:'%s'\n", result);
5949 return result;
5950}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005951#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005952
Denys Vlasenko168579a2018-07-19 13:45:54 +02005953static int append_str_maybe_ifs_split(o_string *output, int n,
Denys Vlasenko18e8b612018-07-20 14:24:56 +02005954 int first_ch, const char *val)
Denys Vlasenko116b50a2018-07-19 11:16:53 +02005955{
5956 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5957 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5958 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5959 if (val && val[0])
Denys Vlasenko168579a2018-07-19 13:45:54 +02005960 n = expand_on_ifs(output, n, val);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02005961 } else { /* quoted "$VAR" */
5962 output->has_quoted_part = 1;
5963 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5964 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5965 if (val && val[0])
5966 o_addQstr(output, val);
5967 }
5968 return n;
5969}
5970
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005971/* Helper:
5972 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5973 */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02005974static NOINLINE int expand_one_var(o_string *output,
Denys Vlasenko168579a2018-07-19 13:45:54 +02005975 int n, int first_ch, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005976{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005977 const char *val;
5978 char *to_be_freed;
5979 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005980 char *var;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005981 char exp_op;
5982 char exp_save = exp_save; /* for compiler */
5983 char *exp_saveptr; /* points to expansion operator */
5984 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005985 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005986
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005987 val = NULL;
5988 to_be_freed = NULL;
5989 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005990 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005991 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005992 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005993 arg0 = arg[0];
Denys Vlasenkob762c782018-07-17 14:21:38 +02005994 arg[0] = (arg0 & 0x7f);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005995 exp_op = 0;
5996
Denys Vlasenkob762c782018-07-17 14:21:38 +02005997 if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005998 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5999 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
6000 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006001 ) {
6002 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006003 var++;
6004 exp_op = 'L';
6005 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006006 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006007 if (exp_saveptr /* if 2nd char is one of expansion operators */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006008 && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006009 ) {
6010 /* ${?:0}, ${#[:]%0} etc */
6011 exp_saveptr = var + 1;
6012 } else {
6013 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
6014 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
6015 }
6016 exp_op = exp_save = *exp_saveptr;
6017 if (exp_op) {
6018 exp_word = exp_saveptr + 1;
6019 if (exp_op == ':') {
6020 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006021//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006022 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006023 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006024 ) {
6025 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
6026 exp_op = ':';
6027 exp_word--;
6028 }
6029 }
6030 *exp_saveptr = '\0';
6031 } /* else: it's not an expansion op, but bare ${var} */
6032 }
6033
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006034 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006035 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02006036 /* parse_dollar should have vetted var for us */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006037 int nn = xatoi_positive(var);
6038 if (nn < G.global_argc)
6039 val = G.global_argv[nn];
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006040 /* else val remains NULL: $N with too big N */
6041 } else {
6042 switch (var[0]) {
6043 case '$': /* pid */
6044 val = utoa(G.root_pid);
6045 break;
6046 case '!': /* bg pid */
6047 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
6048 break;
6049 case '?': /* exitcode */
6050 val = utoa(G.last_exitcode);
6051 break;
6052 case '#': /* argc */
6053 val = utoa(G.global_argc ? G.global_argc-1 : 0);
6054 break;
6055 default:
6056 val = get_local_var_value(var);
6057 }
6058 }
6059
6060 /* Handle any expansions */
6061 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006062 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006063 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02006064 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006065 debug_printf_expand("%s\n", val);
6066 } else if (exp_op) {
6067 if (exp_op == '%' || exp_op == '#') {
6068 /* Standard-mandated substring removal ops:
6069 * ${parameter%word} - remove smallest suffix pattern
6070 * ${parameter%%word} - remove largest suffix pattern
6071 * ${parameter#word} - remove smallest prefix pattern
6072 * ${parameter##word} - remove largest prefix pattern
6073 *
6074 * Word is expanded to produce a glob pattern.
6075 * Then var's value is matched to it and matching part removed.
6076 */
Denys Vlasenkob762c782018-07-17 14:21:38 +02006077//FIXME: ${x#...${...}...}
6078//should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
6079//inner ${...} may have side effects!
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006080 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006081 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006082 char *exp_exp_word;
6083 char *loc;
6084 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02006085 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006086 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01006087 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkob762c782018-07-17 14:21:38 +02006088 exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006089 if (exp_exp_word)
6090 exp_word = exp_exp_word;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006091 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
6092 /*
6093 * HACK ALERT. We depend here on the fact that
Denys Vlasenko4f870492010-09-10 11:06:01 +02006094 * G.global_argv and results of utoa and get_local_var_value
6095 * are actually in writable memory:
Denys Vlasenkob762c782018-07-17 14:21:38 +02006096 * scan_and_match momentarily stores NULs there.
6097 */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006098 t = (char*)val;
6099 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01006100 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 +02006101 free(exp_exp_word);
6102 if (loc) { /* match was found */
6103 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006104 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006105 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02006106 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006107 }
6108 }
6109 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006110#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006111 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006112 /* It's ${var/[/]pattern[/repl]} thing.
6113 * Note that in encoded form it has TWO parts:
6114 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02006115 * and if // is used, it is encoded as \:
6116 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006117 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006118 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02006119 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006120 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006121 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02006122 * >az >bz
6123 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6124 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6125 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6126 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006127 * (note that a*z _pattern_ is never globbed!)
6128 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006129 char *pattern, *repl, *t;
Denys Vlasenkob762c782018-07-17 14:21:38 +02006130 pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006131 if (!pattern)
6132 pattern = xstrdup(exp_word);
6133 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6134 *p++ = SPECIAL_VAR_SYMBOL;
6135 exp_word = p;
6136 p = strchr(p, SPECIAL_VAR_SYMBOL);
6137 *p = '\0';
Denys Vlasenkob762c782018-07-17 14:21:38 +02006138 repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006139 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6140 /* HACK ALERT. We depend here on the fact that
6141 * G.global_argv and results of utoa and get_local_var_value
6142 * are actually in writable memory:
6143 * replace_pattern momentarily stores NULs there. */
6144 t = (char*)val;
6145 to_be_freed = replace_pattern(t,
6146 pattern,
6147 (repl ? repl : exp_word),
6148 exp_op);
6149 if (to_be_freed) /* at least one replace happened */
6150 val = to_be_freed;
6151 free(pattern);
6152 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006153 } else {
6154 /* Empty variable always gives nothing */
6155 // "v=''; echo ${v/*/w}" prints "", not "w"
6156 /* Just skip "replace" part */
6157 *p++ = SPECIAL_VAR_SYMBOL;
6158 p = strchr(p, SPECIAL_VAR_SYMBOL);
6159 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006160 }
6161 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006162#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006163 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006164#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006165 /* It's ${var:N[:M]} bashism.
6166 * Note that in encoded form it has TWO parts:
6167 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6168 */
6169 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006170 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006171
Denys Vlasenko063847d2010-09-15 13:33:02 +02006172 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6173 if (errmsg)
6174 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006175 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6176 *p++ = SPECIAL_VAR_SYMBOL;
6177 exp_word = p;
6178 p = strchr(p, SPECIAL_VAR_SYMBOL);
6179 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006180 len = expand_and_evaluate_arith(exp_word, &errmsg);
6181 if (errmsg)
6182 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006183 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006184 if (beg < 0) {
6185 /* negative beg counts from the end */
6186 beg = (arith_t)strlen(val) + beg;
6187 if (beg < 0) /* ${v: -999999} is "" */
6188 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006189 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006190 debug_printf_varexp("from val:'%s'\n", val);
6191 if (len < 0) {
6192 /* in bash, len=-n means strlen()-n */
6193 len = (arith_t)strlen(val) - beg + len;
6194 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006195 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006196 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006197 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006198 arith_err:
6199 val = NULL;
6200 } else {
6201 /* Paranoia. What if user entered 9999999999999
6202 * which fits in arith_t but not int? */
6203 if (len >= INT_MAX)
6204 len = INT_MAX;
6205 val = to_be_freed = xstrndup(val + beg, len);
6206 }
6207 debug_printf_varexp("val:'%s'\n", val);
6208#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006209 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006210 val = NULL;
6211#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006212 } else { /* one of "-=+?" */
6213 /* Standard-mandated substitution ops:
6214 * ${var?word} - indicate error if unset
6215 * If var is unset, word (or a message indicating it is unset
6216 * if word is null) is written to standard error
6217 * and the shell exits with a non-zero exit status.
6218 * Otherwise, the value of var is substituted.
6219 * ${var-word} - use default value
6220 * If var is unset, word is substituted.
6221 * ${var=word} - assign and use default value
6222 * If var is unset, word is assigned to var.
6223 * In all cases, final value of var is substituted.
6224 * ${var+word} - use alternative value
6225 * If var is unset, null is substituted.
6226 * Otherwise, word is substituted.
6227 *
6228 * Word is subjected to tilde expansion, parameter expansion,
6229 * command substitution, and arithmetic expansion.
6230 * If word is not needed, it is not expanded.
6231 *
6232 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6233 * but also treat null var as if it is unset.
6234 */
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006235/*
6236 * Word-splitting and squote behavior of bash:
6237 * $ f() { for i; do echo "|$i|"; done; };
6238 *
6239 * $ x=; f ${x:?'x y' z}
Denys Vlasenko168579a2018-07-19 13:45:54 +02006240 * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006241 * $ x=; f "${x:?'x y' z}"
Denys Vlasenko168579a2018-07-19 13:45:54 +02006242 * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006243 *
6244 * $ x=; f ${x:='x y' z}
6245 * |x|
6246 * |y|
6247 * |z|
6248 * $ x=; f "${x:='x y' z}"
6249 * |'x y' z|
6250 *
6251 * $ x=x; f ${x:+'x y' z}
6252 * |x y|
6253 * |z|
6254 * $ x=x; f "${x:+'x y' z}"
6255 * |'x y' z|
6256 *
6257 * $ x=; f ${x:-'x y' z}
6258 * |x y|
6259 * |z|
6260 * $ x=; f "${x:-'x y' z}"
6261 * |'x y' z|
6262 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006263 int use_word = (!val || ((exp_save == ':') && !val[0]));
6264 if (exp_op == '+')
6265 use_word = !use_word;
6266 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6267 (exp_save == ':') ? "true" : "false", use_word);
6268 if (use_word) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02006269//FIXME: unquoted ${x:+"b c" d} and ${x:+'b c' d} should expand to two words
6270//currently it expands to three.
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006271 to_be_freed = encode_then_expand_vararg(exp_word,
6272 /*handle_squotes:*/ !(arg0 & 0x80),
6273 /*unbackslash:*/ 0
6274 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006275 if (to_be_freed)
6276 exp_word = to_be_freed;
6277 if (exp_op == '?') {
6278 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006279 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006280 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02006281 exp_word[0]
6282 ? exp_word
6283 : "parameter null or not set"
6284 /* ash has more specific messages, a-la: */
6285 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006286 );
6287//TODO: how interactive bash aborts expansion mid-command?
Denys Vlasenko168579a2018-07-19 13:45:54 +02006288//It aborts the entire line, returns to prompt:
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006289// $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
6290// bash: x: x y z
6291// $
6292// ("echo YO" is not executed, neither the f function call)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006293 } else {
6294 val = exp_word;
6295 }
6296
6297 if (exp_op == '=') {
6298 /* ${var=[word]} or ${var:=[word]} */
6299 if (isdigit(var[0]) || var[0] == '#') {
6300 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006301 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006302 val = NULL;
6303 } else {
6304 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02006305 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006306 }
6307 }
6308 }
6309 } /* one of "-=+?" */
6310
6311 *exp_saveptr = exp_save;
6312 } /* if (exp_op) */
6313
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006314 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006315 *pp = p;
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006316
Denys Vlasenko168579a2018-07-19 13:45:54 +02006317 n = append_str_maybe_ifs_split(output, n, first_ch, val);
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006318
6319 free(to_be_freed);
6320 return n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006321}
6322
6323/* Expand all variable references in given string, adding words to list[]
6324 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6325 * to be filled). This routine is extremely tricky: has to deal with
6326 * variables/parameters with whitespace, $* and $@, and constructs like
6327 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006328static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006329{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006330 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006331 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006332 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006333 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006334 char *p;
6335
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006336 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6337 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006338 debug_print_list("expand_vars_to_list[0]", output, n);
6339
6340 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6341 char first_ch;
Denys Vlasenko0b883582016-12-23 16:49:07 +01006342#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006343 char arith_buf[sizeof(arith_t)*3 + 2];
6344#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006345
Denys Vlasenko168579a2018-07-19 13:45:54 +02006346 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006347 o_addchr(output, '\0');
6348 n = o_save_ptr(output, n);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006349 output->ended_in_ifs = 0;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006350 }
6351
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006352 o_addblock(output, arg, p - arg);
6353 debug_print_list("expand_vars_to_list[1]", output, n);
6354 arg = ++p;
6355 p = strchr(p, SPECIAL_VAR_SYMBOL);
6356
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006357 /* Fetch special var name (if it is indeed one of them)
6358 * and quote bit, force the bit on if singleword expansion -
6359 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006360 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006361
6362 /* Is this variable quoted and thus expansion can't be null?
6363 * "$@" is special. Even if quoted, it can still
6364 * expand to nothing (not even an empty string),
6365 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006366 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006367 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006368
6369 switch (first_ch & 0x7f) {
6370 /* Highest bit in first_ch indicates that var is double-quoted */
6371 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006372 case '@': {
6373 int i;
6374 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006375 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006376 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006377 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006378 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006379 while (G.global_argv[i]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006380 n = expand_on_ifs(output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006381 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6382 if (G.global_argv[i++][0] && G.global_argv[i]) {
6383 /* this argv[] is not empty and not last:
6384 * put terminating NUL, start new word */
6385 o_addchr(output, '\0');
6386 debug_print_list("expand_vars_to_list[2]", output, n);
6387 n = o_save_ptr(output, n);
6388 debug_print_list("expand_vars_to_list[3]", output, n);
6389 }
6390 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006391 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006392 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006393 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006394 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006395 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006396 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006397 while (1) {
6398 o_addQstr(output, G.global_argv[i]);
6399 if (++i >= G.global_argc)
6400 break;
6401 o_addchr(output, '\0');
6402 debug_print_list("expand_vars_to_list[4]", output, n);
6403 n = o_save_ptr(output, n);
6404 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006405 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006406 while (1) {
6407 o_addQstr(output, G.global_argv[i]);
6408 if (!G.global_argv[++i])
6409 break;
6410 if (G.ifs[0])
6411 o_addchr(output, G.ifs[0]);
6412 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006413 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006414 }
6415 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006416 }
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006417 case SPECIAL_VAR_SYMBOL: {
6418 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006419 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006420 output->has_quoted_part = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006421 cant_be_null = 0x80;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006422 arg++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006423 break;
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006424 }
Denys Vlasenko932b9972018-01-11 12:39:48 +01006425 case SPECIAL_VAR_QUOTED_SVS:
6426 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006427 /* "^C variable", represents literal ^C char (possible in scripts) */
6428 o_addchr(output, SPECIAL_VAR_SYMBOL_CHR);
Denys Vlasenko932b9972018-01-11 12:39:48 +01006429 arg++;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006430 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006431#if ENABLE_HUSH_TICK
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006432 case '`': {
6433 /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006434 o_string subst_result = NULL_O_STRING;
6435
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006436 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006437 arg++;
6438 /* Can't just stuff it into output o_string,
6439 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006440 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006441 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6442 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006443 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006444 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denys Vlasenko168579a2018-07-19 13:45:54 +02006445 n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006446 o_free_unsafe(&subst_result);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006447 break;
Denys Vlasenko116b50a2018-07-19 11:16:53 +02006448 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006449#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006450#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006451 case '+': {
6452 /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006453 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006454
6455 arg++; /* skip '+' */
6456 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6457 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006458 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006459 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6460 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006461 o_addstr(output, arith_buf);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006462 break;
6463 }
6464#endif
Denys Vlasenko8a6a4612018-07-19 12:14:47 +02006465 default:
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006466 /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
Denys Vlasenko168579a2018-07-19 13:45:54 +02006467 n = expand_one_var(output, n, first_ch, arg, &p);
Denys Vlasenko18e8b612018-07-20 14:24:56 +02006468 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006469 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6470
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006471 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6472 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006473 if (*p != SPECIAL_VAR_SYMBOL)
6474 *p = SPECIAL_VAR_SYMBOL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006475 arg = ++p;
6476 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6477
6478 if (arg[0]) {
Denys Vlasenko168579a2018-07-19 13:45:54 +02006479 if (output->ended_in_ifs) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006480 o_addchr(output, '\0');
6481 n = o_save_ptr(output, n);
6482 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006483 debug_print_list("expand_vars_to_list[a]", output, n);
6484 /* this part is literal, and it was already pre-quoted
6485 * if needed (much earlier), do not use o_addQstr here! */
6486 o_addstr_with_NUL(output, arg);
6487 debug_print_list("expand_vars_to_list[b]", output, n);
6488 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006489 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006490 ) {
6491 n--;
6492 /* allow to reuse list[n] later without re-growth */
6493 output->has_empty_slot = 1;
6494 } else {
6495 o_addchr(output, '\0');
6496 }
6497
6498 return n;
6499}
6500
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006501static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006502{
6503 int n;
6504 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006505 o_string output = NULL_O_STRING;
6506
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006507 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006508
6509 n = 0;
Denys Vlasenko57235be2018-07-20 14:45:12 +02006510 for (;;) {
6511 /* go to next list[n] */
6512 output.ended_in_ifs = 0;
6513 n = o_save_ptr(&output, n);
6514
6515 if (!*argv)
6516 break;
6517
6518 /* expand argv[i] */
6519 n = expand_vars_to_list(&output, n, *argv++);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006520 }
6521 debug_print_list("expand_variables", &output, n);
6522
6523 /* output.data (malloced in one block) gets returned in "list" */
6524 list = o_finalize_list(&output, n);
6525 debug_print_strings("expand_variables[1]", list);
6526 return list;
6527}
6528
6529static char **expand_strvec_to_strvec(char **argv)
6530{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006531 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006532}
6533
Denys Vlasenko11752d42018-04-03 08:20:58 +02006534#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006535static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6536{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006537 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006538}
6539#endif
6540
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006541/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006542 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006543 *
6544 * NB: should NOT do globbing!
6545 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6546 */
Denys Vlasenko34179952018-04-11 13:47:59 +02006547static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006548{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006549#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006550 const int do_unbackslash = 1;
Denys Vlasenko34179952018-04-11 13:47:59 +02006551 const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006552#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006553 char *argv[2], **list;
6554
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006555 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006556 /* This is generally an optimization, but it also
6557 * handles "", which otherwise trips over !list[0] check below.
6558 * (is this ever happens that we actually get str="" here?)
6559 */
6560 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6561 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006562 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006563 return xstrdup(str);
6564 }
6565
6566 argv[0] = (char*)str;
6567 argv[1] = NULL;
Denys Vlasenko34179952018-04-11 13:47:59 +02006568 list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
Denys Vlasenko2e711012018-07-18 16:02:25 +02006569 if (!list[0]) {
6570 /* Example where it happens:
6571 * x=; echo ${x:-"$@"}
6572 */
6573 ((char*)list)[0] = '\0';
6574 } else {
6575 if (HUSH_DEBUG)
6576 if (list[1])
6577 bb_error_msg_and_die("BUG in varexp2");
6578 /* actually, just move string 2*sizeof(char*) bytes back */
6579 overlapping_strcpy((char*)list, list[0]);
6580 if (do_unbackslash)
6581 unbackslash((char*)list);
6582 }
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006583 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006584 return (char*)list;
6585}
6586
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006587#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006588static char* expand_strvec_to_string(char **argv)
6589{
6590 char **list;
6591
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006592 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006593 /* Convert all NULs to spaces */
6594 if (list[0]) {
6595 int n = 1;
6596 while (list[n]) {
6597 if (HUSH_DEBUG)
6598 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6599 bb_error_msg_and_die("BUG in varexp3");
6600 /* bash uses ' ' regardless of $IFS contents */
6601 list[n][-1] = ' ';
6602 n++;
6603 }
6604 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006605 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006606 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6607 return (char*)list;
6608}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006609#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006610
6611static char **expand_assignments(char **argv, int count)
6612{
6613 int i;
6614 char **p;
6615
6616 G.expanded_assignments = p = NULL;
6617 /* Expand assignments into one string each */
6618 for (i = 0; i < count; i++) {
Denys Vlasenko34179952018-04-11 13:47:59 +02006619 p = add_string_to_strings(p,
6620 expand_string_to_string(argv[i],
6621 EXP_FLAG_ESC_GLOB_CHARS,
6622 /*unbackslash:*/ 1
6623 )
6624 );
6625 G.expanded_assignments = p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006626 }
6627 G.expanded_assignments = NULL;
6628 return p;
6629}
6630
6631
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006632static void switch_off_special_sigs(unsigned mask)
6633{
6634 unsigned sig = 0;
6635 while ((mask >>= 1) != 0) {
6636 sig++;
6637 if (!(mask & 1))
6638 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006639#if ENABLE_HUSH_TRAP
6640 if (G_traps) {
6641 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006642 /* trap is '', has to remain SIG_IGN */
6643 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006644 free(G_traps[sig]);
6645 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006646 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006647#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006648 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006649 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006650 }
6651}
6652
Denys Vlasenkob347df92011-08-09 22:49:15 +02006653#if BB_MMU
6654/* never called */
6655void re_execute_shell(char ***to_free, const char *s,
6656 char *g_argv0, char **g_argv,
6657 char **builtin_argv) NORETURN;
6658
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006659static void reset_traps_to_defaults(void)
6660{
6661 /* This function is always called in a child shell
6662 * after fork (not vfork, NOMMU doesn't use this function).
6663 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006664 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006665 unsigned mask;
6666
6667 /* Child shells are not interactive.
6668 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6669 * Testcase: (while :; do :; done) + ^Z should background.
6670 * Same goes for SIGTERM, SIGHUP, SIGINT.
6671 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006672 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006673 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006674 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006675
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006676 /* Switch off special sigs */
6677 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006678# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006679 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006680# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006681 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006682 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6683 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006684
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006685# if ENABLE_HUSH_TRAP
6686 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006687 return;
6688
6689 /* Reset all sigs to default except ones with empty traps */
6690 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006691 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006692 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006693 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006694 continue; /* empty trap: has to remain SIG_IGN */
6695 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006696 free(G_traps[sig]);
6697 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006698 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006699 if (sig == 0)
6700 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006701 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006702 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006703# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006704}
6705
6706#else /* !BB_MMU */
6707
6708static void re_execute_shell(char ***to_free, const char *s,
6709 char *g_argv0, char **g_argv,
6710 char **builtin_argv) NORETURN;
6711static void re_execute_shell(char ***to_free, const char *s,
6712 char *g_argv0, char **g_argv,
6713 char **builtin_argv)
6714{
6715# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6716 /* delims + 2 * (number of bytes in printed hex numbers) */
6717 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6718 char *heredoc_argv[4];
6719 struct variable *cur;
6720# if ENABLE_HUSH_FUNCTIONS
6721 struct function *funcp;
6722# endif
6723 char **argv, **pp;
6724 unsigned cnt;
6725 unsigned long long empty_trap_mask;
6726
6727 if (!g_argv0) { /* heredoc */
6728 argv = heredoc_argv;
6729 argv[0] = (char *) G.argv0_for_re_execing;
6730 argv[1] = (char *) "-<";
6731 argv[2] = (char *) s;
6732 argv[3] = NULL;
6733 pp = &argv[3]; /* used as pointer to empty environment */
6734 goto do_exec;
6735 }
6736
6737 cnt = 0;
6738 pp = builtin_argv;
6739 if (pp) while (*pp++)
6740 cnt++;
6741
6742 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006743 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006744 int sig;
6745 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006746 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006747 empty_trap_mask |= 1LL << sig;
6748 }
6749 }
6750
6751 sprintf(param_buf, NOMMU_HACK_FMT
6752 , (unsigned) G.root_pid
6753 , (unsigned) G.root_ppid
6754 , (unsigned) G.last_bg_pid
6755 , (unsigned) G.last_exitcode
6756 , cnt
6757 , empty_trap_mask
6758 IF_HUSH_LOOPS(, G.depth_of_loop)
6759 );
6760# undef NOMMU_HACK_FMT
6761 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6762 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6763 */
6764 cnt += 6;
6765 for (cur = G.top_var; cur; cur = cur->next) {
6766 if (!cur->flg_export || cur->flg_read_only)
6767 cnt += 2;
6768 }
6769# if ENABLE_HUSH_FUNCTIONS
6770 for (funcp = G.top_func; funcp; funcp = funcp->next)
6771 cnt += 3;
6772# endif
6773 pp = g_argv;
6774 while (*pp++)
6775 cnt++;
6776 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6777 *pp++ = (char *) G.argv0_for_re_execing;
6778 *pp++ = param_buf;
6779 for (cur = G.top_var; cur; cur = cur->next) {
6780 if (strcmp(cur->varstr, hush_version_str) == 0)
6781 continue;
6782 if (cur->flg_read_only) {
6783 *pp++ = (char *) "-R";
6784 *pp++ = cur->varstr;
6785 } else if (!cur->flg_export) {
6786 *pp++ = (char *) "-V";
6787 *pp++ = cur->varstr;
6788 }
6789 }
6790# if ENABLE_HUSH_FUNCTIONS
6791 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6792 *pp++ = (char *) "-F";
6793 *pp++ = funcp->name;
6794 *pp++ = funcp->body_as_string;
6795 }
6796# endif
6797 /* We can pass activated traps here. Say, -Tnn:trap_string
6798 *
6799 * However, POSIX says that subshells reset signals with traps
6800 * to SIG_DFL.
6801 * I tested bash-3.2 and it not only does that with true subshells
6802 * of the form ( list ), but with any forked children shells.
6803 * I set trap "echo W" WINCH; and then tried:
6804 *
6805 * { echo 1; sleep 20; echo 2; } &
6806 * while true; do echo 1; sleep 20; echo 2; break; done &
6807 * true | { echo 1; sleep 20; echo 2; } | cat
6808 *
6809 * In all these cases sending SIGWINCH to the child shell
6810 * did not run the trap. If I add trap "echo V" WINCH;
6811 * _inside_ group (just before echo 1), it works.
6812 *
6813 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006814 */
6815 *pp++ = (char *) "-c";
6816 *pp++ = (char *) s;
6817 if (builtin_argv) {
6818 while (*++builtin_argv)
6819 *pp++ = *builtin_argv;
6820 *pp++ = (char *) "";
6821 }
6822 *pp++ = g_argv0;
6823 while (*g_argv)
6824 *pp++ = *g_argv++;
6825 /* *pp = NULL; - is already there */
6826 pp = environ;
6827
6828 do_exec:
6829 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006830 /* Don't propagate SIG_IGN to the child */
6831 if (SPECIAL_JOBSTOP_SIGS != 0)
6832 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006833 execve(bb_busybox_exec_path, argv, pp);
6834 /* Fallback. Useful for init=/bin/hush usage etc */
6835 if (argv[0][0] == '/')
6836 execve(argv[0], argv, pp);
6837 xfunc_error_retval = 127;
6838 bb_error_msg_and_die("can't re-execute the shell");
6839}
6840#endif /* !BB_MMU */
6841
6842
6843static int run_and_free_list(struct pipe *pi);
6844
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006845/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006846 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6847 * end_trigger controls how often we stop parsing
6848 * NUL: parse all, execute, return
6849 * ';': parse till ';' or newline, execute, repeat till EOF
6850 */
6851static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006852{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006853 /* Why we need empty flag?
6854 * An obscure corner case "false; ``; echo $?":
6855 * empty command in `` should still set $? to 0.
6856 * But we can't just set $? to 0 at the start,
6857 * this breaks "false; echo `echo $?`" case.
6858 */
6859 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006860 while (1) {
6861 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006862
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006863#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02006864 if (end_trigger == ';') {
6865 G.promptmode = 0; /* PS1 */
6866 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
6867 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006868#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006869 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006870 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6871 /* If we are in "big" script
6872 * (not in `cmd` or something similar)...
6873 */
6874 if (pipe_list == ERR_PTR && end_trigger == ';') {
6875 /* Discard cached input (rest of line) */
6876 int ch = inp->last_char;
6877 while (ch != EOF && ch != '\n') {
6878 //bb_error_msg("Discarded:'%c'", ch);
6879 ch = i_getch(inp);
6880 }
6881 /* Force prompt */
6882 inp->p = NULL;
6883 /* This stream isn't empty */
6884 empty = 0;
6885 continue;
6886 }
6887 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006888 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006889 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006890 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006891 debug_print_tree(pipe_list, 0);
6892 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6893 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006894 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006895 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006896 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006897 }
Eric Andersen25f27032001-04-26 23:22:31 +00006898}
6899
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006900static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006901{
6902 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006903 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6904
Eric Andersen25f27032001-04-26 23:22:31 +00006905 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006906 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006907 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006908}
6909
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006910static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006911{
Eric Andersen25f27032001-04-26 23:22:31 +00006912 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006913 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01006914
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006915 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01006916 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006917 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006918 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006919}
6920
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006921#if ENABLE_HUSH_TICK
6922static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6923{
6924 pid_t pid;
6925 int channel[2];
6926# if !BB_MMU
6927 char **to_free = NULL;
6928# endif
6929
6930 xpipe(channel);
6931 pid = BB_MMU ? xfork() : xvfork();
6932 if (pid == 0) { /* child */
6933 disable_restore_tty_pgrp_on_exit();
6934 /* Process substitution is not considered to be usual
6935 * 'command execution'.
6936 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6937 */
6938 bb_signals(0
6939 + (1 << SIGTSTP)
6940 + (1 << SIGTTIN)
6941 + (1 << SIGTTOU)
6942 , SIG_IGN);
6943 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6944 close(channel[0]); /* NB: close _first_, then move fd! */
6945 xmove_fd(channel[1], 1);
6946 /* Prevent it from trying to handle ctrl-z etc */
6947 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006948# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006949 /* Awful hack for `trap` or $(trap).
6950 *
6951 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6952 * contains an example where "trap" is executed in a subshell:
6953 *
6954 * save_traps=$(trap)
6955 * ...
6956 * eval "$save_traps"
6957 *
6958 * Standard does not say that "trap" in subshell shall print
6959 * parent shell's traps. It only says that its output
6960 * must have suitable form, but then, in the above example
6961 * (which is not supposed to be normative), it implies that.
6962 *
6963 * bash (and probably other shell) does implement it
6964 * (traps are reset to defaults, but "trap" still shows them),
6965 * but as a result, "trap" logic is hopelessly messed up:
6966 *
6967 * # trap
6968 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6969 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6970 * # true | trap <--- trap is in subshell - no output (ditto)
6971 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6972 * trap -- 'echo Ho' SIGWINCH
6973 * # echo `(trap)` <--- in subshell in subshell - output
6974 * trap -- 'echo Ho' SIGWINCH
6975 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6976 * trap -- 'echo Ho' SIGWINCH
6977 *
6978 * The rules when to forget and when to not forget traps
6979 * get really complex and nonsensical.
6980 *
6981 * Our solution: ONLY bare $(trap) or `trap` is special.
6982 */
6983 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006984 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006985 && skip_whitespace(s + 4)[0] == '\0'
6986 ) {
6987 static const char *const argv[] = { NULL, NULL };
6988 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006989 fflush_all(); /* important */
6990 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006991 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006992# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006993# if BB_MMU
6994 reset_traps_to_defaults();
6995 parse_and_run_string(s);
6996 _exit(G.last_exitcode);
6997# else
6998 /* We re-execute after vfork on NOMMU. This makes this script safe:
6999 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
7000 * huge=`cat BIG` # was blocking here forever
7001 * echo OK
7002 */
7003 re_execute_shell(&to_free,
7004 s,
7005 G.global_argv[0],
7006 G.global_argv + 1,
7007 NULL);
7008# endif
7009 }
7010
7011 /* parent */
7012 *pid_p = pid;
7013# if ENABLE_HUSH_FAST
7014 G.count_SIGCHLD++;
7015//bb_error_msg("[%d] fork in generate_stream_from_string:"
7016// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
7017// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7018# endif
7019 enable_restore_tty_pgrp_on_exit();
7020# if !BB_MMU
7021 free(to_free);
7022# endif
7023 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007024 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007025}
7026
7027/* Return code is exit status of the process that is run. */
7028static int process_command_subs(o_string *dest, const char *s)
7029{
7030 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007031 pid_t pid;
7032 int status, ch, eol_cnt;
7033
7034 fp = generate_stream_from_string(s, &pid);
7035
7036 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007037 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01007038 while ((ch = getc(fp)) != EOF) {
7039 if (ch == '\0')
7040 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007041 if (ch == '\n') {
7042 eol_cnt++;
7043 continue;
7044 }
7045 while (eol_cnt) {
7046 o_addchr(dest, '\n');
7047 eol_cnt--;
7048 }
7049 o_addQchr(dest, ch);
7050 }
7051
7052 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007053 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007054 /* We need to extract exitcode. Test case
7055 * "true; echo `sleep 1; false` $?"
7056 * should print 1 */
7057 safe_waitpid(pid, &status, 0);
7058 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
7059 return WEXITSTATUS(status);
7060}
7061#endif /* ENABLE_HUSH_TICK */
7062
7063
7064static void setup_heredoc(struct redir_struct *redir)
7065{
7066 struct fd_pair pair;
7067 pid_t pid;
7068 int len, written;
7069 /* the _body_ of heredoc (misleading field name) */
7070 const char *heredoc = redir->rd_filename;
7071 char *expanded;
7072#if !BB_MMU
7073 char **to_free;
7074#endif
7075
7076 expanded = NULL;
7077 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkob762c782018-07-17 14:21:38 +02007078 expanded = encode_then_expand_string(heredoc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007079 if (expanded)
7080 heredoc = expanded;
7081 }
7082 len = strlen(heredoc);
7083
7084 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
7085 xpiped_pair(pair);
7086 xmove_fd(pair.rd, redir->rd_fd);
7087
7088 /* Try writing without forking. Newer kernels have
7089 * dynamically growing pipes. Must use non-blocking write! */
7090 ndelay_on(pair.wr);
7091 while (1) {
7092 written = write(pair.wr, heredoc, len);
7093 if (written <= 0)
7094 break;
7095 len -= written;
7096 if (len == 0) {
7097 close(pair.wr);
7098 free(expanded);
7099 return;
7100 }
7101 heredoc += written;
7102 }
7103 ndelay_off(pair.wr);
7104
7105 /* Okay, pipe buffer was not big enough */
7106 /* Note: we must not create a stray child (bastard? :)
7107 * for the unsuspecting parent process. Child creates a grandchild
7108 * and exits before parent execs the process which consumes heredoc
7109 * (that exec happens after we return from this function) */
7110#if !BB_MMU
7111 to_free = NULL;
7112#endif
7113 pid = xvfork();
7114 if (pid == 0) {
7115 /* child */
7116 disable_restore_tty_pgrp_on_exit();
7117 pid = BB_MMU ? xfork() : xvfork();
7118 if (pid != 0)
7119 _exit(0);
7120 /* grandchild */
7121 close(redir->rd_fd); /* read side of the pipe */
7122#if BB_MMU
7123 full_write(pair.wr, heredoc, len); /* may loop or block */
7124 _exit(0);
7125#else
7126 /* Delegate blocking writes to another process */
7127 xmove_fd(pair.wr, STDOUT_FILENO);
7128 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
7129#endif
7130 }
7131 /* parent */
7132#if ENABLE_HUSH_FAST
7133 G.count_SIGCHLD++;
7134//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7135#endif
7136 enable_restore_tty_pgrp_on_exit();
7137#if !BB_MMU
7138 free(to_free);
7139#endif
7140 close(pair.wr);
7141 free(expanded);
7142 wait(NULL); /* wait till child has died */
7143}
7144
Denys Vlasenko2db74612017-07-07 22:07:28 +02007145struct squirrel {
7146 int orig_fd;
7147 int moved_to;
7148 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
7149 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
7150};
7151
Denys Vlasenko621fc502017-07-24 12:42:17 +02007152static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
7153{
7154 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
7155 sq[i].orig_fd = orig;
7156 sq[i].moved_to = moved;
7157 sq[i+1].orig_fd = -1; /* end marker */
7158 return sq;
7159}
7160
Denys Vlasenko2db74612017-07-07 22:07:28 +02007161static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7162{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007163 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007164 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007165
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007166 i = 0;
7167 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007168 /* If we collide with an already moved fd... */
7169 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007170 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007171 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7172 if (sq[i].moved_to < 0) /* what? */
7173 xfunc_die();
7174 return sq;
7175 }
7176 if (fd == sq[i].orig_fd) {
7177 /* Example: echo Hello >/dev/null 1>&2 */
7178 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7179 return sq;
7180 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007181 }
7182
Denys Vlasenko2db74612017-07-07 22:07:28 +02007183 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007184 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007185 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7186 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007187 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007188 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007189}
7190
Denys Vlasenko657e9002017-07-30 23:34:04 +02007191static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7192{
7193 int i;
7194
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007195 i = 0;
7196 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007197 /* If we collide with an already moved fd... */
7198 if (fd == sq[i].orig_fd) {
7199 /* Examples:
7200 * "echo 3>FILE 3>&- 3>FILE"
7201 * "echo 3>&- 3>FILE"
7202 * No need for last redirect to insert
7203 * another "need to close 3" indicator.
7204 */
7205 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7206 return sq;
7207 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007208 }
7209
7210 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7211 return append_squirrel(sq, i, fd, -1);
7212}
7213
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007214/* fd: redirect wants this fd to be used (e.g. 3>file).
7215 * Move all conflicting internally used fds,
7216 * and remember them so that we can restore them later.
7217 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007218static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007219{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007220 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7221 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007222
7223#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007224 if (fd == G.interactive_fd) {
7225 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007226 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007227 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7228 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007229 }
7230#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007231 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7232 * (1) Redirect in a forked child. No need to save FILEs' fds,
7233 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007234 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7235 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007236 * "fileno(fd) = new_fd" can't be done.
7237 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007238 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007239 return 0;
7240
Denys Vlasenko2db74612017-07-07 22:07:28 +02007241 /* If this one of script's fds? */
7242 if (save_FILEs_on_redirect(fd, avoid_fd))
7243 return 1; /* yes. "we closed fd" */
7244
7245 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7246 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7247 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007248}
7249
Denys Vlasenko2db74612017-07-07 22:07:28 +02007250static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007251{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007252 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007253 int i;
7254 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007255 if (sq[i].moved_to >= 0) {
7256 /* We simply die on error */
7257 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7258 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7259 } else {
7260 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7261 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7262 close(sq[i].orig_fd);
7263 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007264 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007265 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007266 }
7267
Denys Vlasenko2db74612017-07-07 22:07:28 +02007268 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007269
7270 restore_redirected_FILEs();
7271}
7272
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007273#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007274static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007275{
7276 if (G_interactive_fd)
7277 close(G_interactive_fd);
7278 close_all_FILE_list();
7279}
7280#endif
7281
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007282static int internally_opened_fd(int fd, struct squirrel *sq)
7283{
7284 int i;
7285
7286#if ENABLE_HUSH_INTERACTIVE
7287 if (fd == G.interactive_fd)
7288 return 1;
7289#endif
7290 /* If this one of script's fds? */
7291 if (fd_in_FILEs(fd))
7292 return 1;
7293
7294 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7295 if (fd == sq[i].moved_to)
7296 return 1;
7297 }
7298 return 0;
7299}
7300
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007301/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7302 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007303static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007304{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007305 struct redir_struct *redir;
7306
7307 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007308 int newfd;
7309 int closed;
7310
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007311 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007312 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007313 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007314 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7315 * of the heredoc */
7316 debug_printf_parse("set heredoc '%s'\n",
7317 redir->rd_filename);
7318 setup_heredoc(redir);
7319 continue;
7320 }
7321
7322 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007323 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007324 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007325 int mode;
7326
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007327 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007328 /*
7329 * Examples:
7330 * "cmd >" (no filename)
7331 * "cmd > <file" (2nd redirect starts too early)
7332 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007333 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007334 continue;
7335 }
7336 mode = redir_table[redir->rd_type].mode;
Denys Vlasenko34179952018-04-11 13:47:59 +02007337 p = expand_string_to_string(redir->rd_filename,
7338 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007339 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007340 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007341 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007342 /* Error message from open_or_warn can be lost
7343 * if stderr has been redirected, but bash
7344 * and ash both lose it as well
7345 * (though zsh doesn't!)
7346 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007347 return 1;
7348 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007349 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007350 /* open() gave us precisely the fd we wanted.
7351 * This means that this fd was not busy
7352 * (not opened to anywhere).
7353 * Remember to close it on restore:
7354 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007355 *sqp = add_squirrel_closed(*sqp, newfd);
7356 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007357 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007358 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007359 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7360 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007361 }
7362
Denys Vlasenko657e9002017-07-30 23:34:04 +02007363 if (newfd == redir->rd_fd)
7364 continue;
7365
7366 /* if "N>FILE": move newfd to redir->rd_fd */
7367 /* if "N>&M": dup newfd to redir->rd_fd */
7368 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7369
7370 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7371 if (newfd == REDIRFD_CLOSE) {
7372 /* "N>&-" means "close me" */
7373 if (!closed) {
7374 /* ^^^ optimization: saving may already
7375 * have closed it. If not... */
7376 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007377 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007378 /* Sometimes we do another close on restore, getting EBADF.
7379 * Consider "echo 3>FILE 3>&-"
7380 * first redirect remembers "need to close 3",
7381 * and second redirect closes 3! Restore code then closes 3 again.
7382 */
7383 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007384 /* if newfd is a script fd or saved fd, simulate EBADF */
7385 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7386 //errno = EBADF;
7387 //bb_perror_msg_and_die("can't duplicate file descriptor");
7388 newfd = -1; /* same effect as code above */
7389 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007390 xdup2(newfd, redir->rd_fd);
7391 if (redir->rd_dup == REDIRFD_TO_FILE)
7392 /* "rd_fd > FILE" */
7393 close(newfd);
7394 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007395 }
7396 }
7397 return 0;
7398}
7399
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007400static char *find_in_path(const char *arg)
7401{
7402 char *ret = NULL;
7403 const char *PATH = get_local_var_value("PATH");
7404
7405 if (!PATH)
7406 return NULL;
7407
7408 while (1) {
7409 const char *end = strchrnul(PATH, ':');
7410 int sz = end - PATH; /* must be int! */
7411
7412 free(ret);
7413 if (sz != 0) {
7414 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7415 } else {
7416 /* We have xxx::yyyy in $PATH,
7417 * it means "use current dir" */
7418 ret = xstrdup(arg);
7419 }
7420 if (access(ret, F_OK) == 0)
7421 break;
7422
7423 if (*end == '\0') {
7424 free(ret);
7425 return NULL;
7426 }
7427 PATH = end + 1;
7428 }
7429
7430 return ret;
7431}
7432
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007433static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007434 const struct built_in_command *x,
7435 const struct built_in_command *end)
7436{
7437 while (x != end) {
7438 if (strcmp(name, x->b_cmd) != 0) {
7439 x++;
7440 continue;
7441 }
7442 debug_printf_exec("found builtin '%s'\n", name);
7443 return x;
7444 }
7445 return NULL;
7446}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007447static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007448{
7449 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7450}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007451static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007452{
7453 const struct built_in_command *x = find_builtin1(name);
7454 if (x)
7455 return x;
7456 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7457}
7458
Denys Vlasenko99496dc2018-06-26 15:36:58 +02007459static void remove_nested_vars(void)
7460{
7461 struct variable *cur;
7462 struct variable **cur_pp;
7463
7464 cur_pp = &G.top_var;
7465 while ((cur = *cur_pp) != NULL) {
7466 if (cur->var_nest_level <= G.var_nest_level) {
7467 cur_pp = &cur->next;
7468 continue;
7469 }
7470 /* Unexport */
7471 if (cur->flg_export) {
7472 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7473 bb_unsetenv(cur->varstr);
7474 }
7475 /* Remove from global list */
7476 *cur_pp = cur->next;
7477 /* Free */
7478 if (!cur->max_len) {
7479 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7480 free(cur->varstr);
7481 }
7482 free(cur);
7483 }
7484}
7485
7486static void enter_var_nest_level(void)
7487{
7488 G.var_nest_level++;
7489 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7490
7491 /* Try: f() { echo -n .; f; }; f
7492 * struct variable::var_nest_level is uint16_t,
7493 * thus limiting recursion to < 2^16.
7494 * In any case, with 8 Mbyte stack SEGV happens
7495 * not too long after 2^16 recursions anyway.
7496 */
7497 if (G.var_nest_level > 0xff00)
7498 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7499}
7500
7501static void leave_var_nest_level(void)
7502{
7503 G.var_nest_level--;
7504 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7505 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7506 bb_error_msg_and_die("BUG: nesting underflow");
7507
7508 remove_nested_vars();
7509}
7510
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007511#if ENABLE_HUSH_FUNCTIONS
7512static struct function **find_function_slot(const char *name)
7513{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007514 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007515 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007516
7517 while ((funcp = *funcpp) != NULL) {
7518 if (strcmp(name, funcp->name) == 0) {
7519 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007520 break;
7521 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007522 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007523 }
7524 return funcpp;
7525}
7526
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007527static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007528{
7529 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007530 return funcp;
7531}
7532
7533/* Note: takes ownership on name ptr */
7534static struct function *new_function(char *name)
7535{
7536 struct function **funcpp = find_function_slot(name);
7537 struct function *funcp = *funcpp;
7538
7539 if (funcp != NULL) {
7540 struct command *cmd = funcp->parent_cmd;
7541 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7542 if (!cmd) {
7543 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7544 free(funcp->name);
7545 /* Note: if !funcp->body, do not free body_as_string!
7546 * This is a special case of "-F name body" function:
7547 * body_as_string was not malloced! */
7548 if (funcp->body) {
7549 free_pipe_list(funcp->body);
7550# if !BB_MMU
7551 free(funcp->body_as_string);
7552# endif
7553 }
7554 } else {
7555 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7556 cmd->argv[0] = funcp->name;
7557 cmd->group = funcp->body;
7558# if !BB_MMU
7559 cmd->group_as_string = funcp->body_as_string;
7560# endif
7561 }
7562 } else {
7563 debug_printf_exec("remembering new function '%s'\n", name);
7564 funcp = *funcpp = xzalloc(sizeof(*funcp));
7565 /*funcp->next = NULL;*/
7566 }
7567
7568 funcp->name = name;
7569 return funcp;
7570}
7571
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007572# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007573static void unset_func(const char *name)
7574{
7575 struct function **funcpp = find_function_slot(name);
7576 struct function *funcp = *funcpp;
7577
7578 if (funcp != NULL) {
7579 debug_printf_exec("freeing function '%s'\n", funcp->name);
7580 *funcpp = funcp->next;
7581 /* funcp is unlinked now, deleting it.
7582 * Note: if !funcp->body, the function was created by
7583 * "-F name body", do not free ->body_as_string
7584 * and ->name as they were not malloced. */
7585 if (funcp->body) {
7586 free_pipe_list(funcp->body);
7587 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007588# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007589 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007590# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007591 }
7592 free(funcp);
7593 }
7594}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007595# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007596
7597# if BB_MMU
7598#define exec_function(to_free, funcp, argv) \
7599 exec_function(funcp, argv)
7600# endif
7601static void exec_function(char ***to_free,
7602 const struct function *funcp,
7603 char **argv) NORETURN;
7604static void exec_function(char ***to_free,
7605 const struct function *funcp,
7606 char **argv)
7607{
7608# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007609 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007610
7611 argv[0] = G.global_argv[0];
7612 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007613 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007614
7615// Example when we are here: "cmd | func"
7616// func will run with saved-redirect fds open.
7617// $ f() { echo /proc/self/fd/*; }
7618// $ true | f
7619// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7620// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7621// Same in script:
7622// $ . ./SCRIPT
7623// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7624// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7625// They are CLOEXEC so external programs won't see them, but
7626// for "more correctness" we might want to close those extra fds here:
7627//? close_saved_fds_and_FILE_fds();
7628
Denys Vlasenko332e4112018-04-04 22:32:59 +02007629 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007630 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007631 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007632 IF_HUSH_LOCAL(G.func_nest_level++;)
7633
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007634 /* On MMU, funcp->body is always non-NULL */
7635 n = run_list(funcp->body);
7636 fflush_all();
7637 _exit(n);
7638# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007639//? close_saved_fds_and_FILE_fds();
7640
7641//TODO: check whether "true | func_with_return" works
7642
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007643 re_execute_shell(to_free,
7644 funcp->body_as_string,
7645 G.global_argv[0],
7646 argv + 1,
7647 NULL);
7648# endif
7649}
7650
7651static int run_function(const struct function *funcp, char **argv)
7652{
7653 int rc;
7654 save_arg_t sv;
7655 smallint sv_flg;
7656
7657 save_and_replace_G_args(&sv, argv);
7658
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007659 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007660 sv_flg = G_flag_return_in_progress;
7661 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007662
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007663 /* Make "local" variables properly shadow previous ones */
7664 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007665 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007666
7667 /* On MMU, funcp->body is always non-NULL */
7668# if !BB_MMU
7669 if (!funcp->body) {
7670 /* Function defined by -F */
7671 parse_and_run_string(funcp->body_as_string);
7672 rc = G.last_exitcode;
7673 } else
7674# endif
7675 {
7676 rc = run_list(funcp->body);
7677 }
7678
Denys Vlasenko332e4112018-04-04 22:32:59 +02007679 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007680 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007681
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007682 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007683
7684 restore_G_args(&sv, argv);
7685
7686 return rc;
7687}
7688#endif /* ENABLE_HUSH_FUNCTIONS */
7689
7690
7691#if BB_MMU
7692#define exec_builtin(to_free, x, argv) \
7693 exec_builtin(x, argv)
7694#else
7695#define exec_builtin(to_free, x, argv) \
7696 exec_builtin(to_free, argv)
7697#endif
7698static void exec_builtin(char ***to_free,
7699 const struct built_in_command *x,
7700 char **argv) NORETURN;
7701static void exec_builtin(char ***to_free,
7702 const struct built_in_command *x,
7703 char **argv)
7704{
7705#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007706 int rcode;
7707 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007708//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007709 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007710 fflush_all();
7711 _exit(rcode);
7712#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007713 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007714 /* On NOMMU, we must never block!
7715 * Example: { sleep 99 | read line; } & echo Ok
7716 */
7717 re_execute_shell(to_free,
7718 argv[0],
7719 G.global_argv[0],
7720 G.global_argv + 1,
7721 argv);
7722#endif
7723}
7724
7725
7726static void execvp_or_die(char **argv) NORETURN;
7727static void execvp_or_die(char **argv)
7728{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007729 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007730 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007731 /* Don't propagate SIG_IGN to the child */
7732 if (SPECIAL_JOBSTOP_SIGS != 0)
7733 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007734 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007735 e = 2;
7736 if (errno == EACCES) e = 126;
7737 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007738 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007739 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007740}
7741
7742#if ENABLE_HUSH_MODE_X
7743static void dump_cmd_in_x_mode(char **argv)
7744{
7745 if (G_x_mode && argv) {
7746 /* We want to output the line in one write op */
7747 char *buf, *p;
7748 int len;
7749 int n;
7750
7751 len = 3;
7752 n = 0;
7753 while (argv[n])
7754 len += strlen(argv[n++]) + 1;
7755 buf = xmalloc(len);
7756 buf[0] = '+';
7757 p = buf + 1;
7758 n = 0;
7759 while (argv[n])
7760 p += sprintf(p, " %s", argv[n++]);
7761 *p++ = '\n';
7762 *p = '\0';
7763 fputs(buf, stderr);
7764 free(buf);
7765 }
7766}
7767#else
7768# define dump_cmd_in_x_mode(argv) ((void)0)
7769#endif
7770
Denys Vlasenko57000292018-01-12 14:41:45 +01007771#if ENABLE_HUSH_COMMAND
7772static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7773{
7774 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007775
Denys Vlasenko57000292018-01-12 14:41:45 +01007776 if (!opt_vV)
7777 return;
7778
7779 to_free = NULL;
7780 if (!explanation) {
7781 char *path = getenv("PATH");
7782 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007783 if (!explanation)
7784 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007785 if (opt_vV != 'V')
7786 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7787 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007788 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007789 free(to_free);
7790 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007791 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007792}
7793#else
7794# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7795#endif
7796
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007797#if BB_MMU
7798#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7799 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7800#define pseudo_exec(nommu_save, command, argv_expanded) \
7801 pseudo_exec(command, argv_expanded)
7802#endif
7803
7804/* Called after [v]fork() in run_pipe, or from builtin_exec.
7805 * Never returns.
7806 * Don't exit() here. If you don't exec, use _exit instead.
7807 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007808 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007809 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007810static void pseudo_exec_argv(nommu_save_t *nommu_save,
7811 char **argv, int assignment_cnt,
7812 char **argv_expanded) NORETURN;
7813static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7814 char **argv, int assignment_cnt,
7815 char **argv_expanded)
7816{
Denys Vlasenko57000292018-01-12 14:41:45 +01007817 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007818 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007819 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007820 IF_HUSH_COMMAND(char opt_vV = 0;)
7821 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007822
7823 new_env = expand_assignments(argv, assignment_cnt);
7824 dump_cmd_in_x_mode(new_env);
7825
7826 if (!argv[assignment_cnt]) {
7827 /* Case when we are here: ... | var=val | ...
7828 * (note that we do not exit early, i.e., do not optimize out
7829 * expand_assignments(): think about ... | var=`sleep 1` | ...
7830 */
7831 free_strings(new_env);
7832 _exit(EXIT_SUCCESS);
7833 }
7834
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007835 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007836#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007837 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007838#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007839 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007840 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007841#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007842 set_vars_and_save_old(new_env);
7843 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007844
7845 if (argv_expanded) {
7846 argv = argv_expanded;
7847 } else {
7848 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7849#if !BB_MMU
7850 nommu_save->argv = argv;
7851#endif
7852 }
7853 dump_cmd_in_x_mode(argv);
7854
7855#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7856 if (strchr(argv[0], '/') != NULL)
7857 goto skip;
7858#endif
7859
Denys Vlasenko75481d32017-07-31 05:27:09 +02007860#if ENABLE_HUSH_FUNCTIONS
7861 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007862 funcp = find_function(argv[0]);
7863 if (funcp)
7864 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02007865#endif
7866
Denys Vlasenko57000292018-01-12 14:41:45 +01007867#if ENABLE_HUSH_COMMAND
7868 /* "command BAR": run BAR without looking it up among functions
7869 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7870 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7871 */
7872 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7873 char *p;
7874
7875 argv++;
7876 p = *argv;
7877 if (p[0] != '-' || !p[1])
7878 continue; /* bash allows "command command command [-OPT] BAR" */
7879
7880 for (;;) {
7881 p++;
7882 switch (*p) {
7883 case '\0':
7884 argv++;
7885 p = *argv;
7886 if (p[0] != '-' || !p[1])
7887 goto after_opts;
7888 continue; /* next arg is also -opts, process it too */
7889 case 'v':
7890 case 'V':
7891 opt_vV = *p;
7892 continue;
7893 default:
7894 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7895 }
7896 }
7897 }
7898 after_opts:
7899# if ENABLE_HUSH_FUNCTIONS
7900 if (opt_vV && find_function(argv[0]))
7901 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7902# endif
7903#endif
7904
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007905 /* Check if the command matches any of the builtins.
7906 * Depending on context, this might be redundant. But it's
7907 * easier to waste a few CPU cycles than it is to figure out
7908 * if this is one of those cases.
7909 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007910 /* Why "BB_MMU ? :" difference in logic? -
7911 * On NOMMU, it is more expensive to re-execute shell
7912 * just in order to run echo or test builtin.
7913 * It's better to skip it here and run corresponding
7914 * non-builtin later. */
7915 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7916 if (x) {
7917 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7918 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007919 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007920
7921#if ENABLE_FEATURE_SH_STANDALONE
7922 /* Check if the command matches any busybox applets */
7923 {
7924 int a = find_applet_by_name(argv[0]);
7925 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007926 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007927# if BB_MMU /* see above why on NOMMU it is not allowed */
7928 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007929 /* Do not leak open fds from opened script files etc.
7930 * Testcase: interactive "ls -l /proc/self/fd"
7931 * should not show tty fd open.
7932 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007933 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007934//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007935//This casuses test failures in
7936//redir_children_should_not_see_saved_fd_2.tests
7937//redir_children_should_not_see_saved_fd_3.tests
7938//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007939 /* Without this, "rm -i FILE" can't be ^C'ed: */
7940 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007941 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007942 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007943 }
7944# endif
7945 /* Re-exec ourselves */
7946 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007947 /* Don't propagate SIG_IGN to the child */
7948 if (SPECIAL_JOBSTOP_SIGS != 0)
7949 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007950 execv(bb_busybox_exec_path, argv);
7951 /* If they called chroot or otherwise made the binary no longer
7952 * executable, fall through */
7953 }
7954 }
7955#endif
7956
7957#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7958 skip:
7959#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007960 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007961 execvp_or_die(argv);
7962}
7963
7964/* Called after [v]fork() in run_pipe
7965 */
7966static void pseudo_exec(nommu_save_t *nommu_save,
7967 struct command *command,
7968 char **argv_expanded) NORETURN;
7969static void pseudo_exec(nommu_save_t *nommu_save,
7970 struct command *command,
7971 char **argv_expanded)
7972{
Denys Vlasenko49015a62018-04-03 13:02:43 +02007973#if ENABLE_HUSH_FUNCTIONS
7974 if (command->cmd_type == CMD_FUNCDEF) {
7975 /* Ignore funcdefs in pipes:
7976 * true | f() { cmd }
7977 */
7978 _exit(0);
7979 }
7980#endif
7981
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007982 if (command->argv) {
7983 pseudo_exec_argv(nommu_save, command->argv,
7984 command->assignment_cnt, argv_expanded);
7985 }
7986
7987 if (command->group) {
7988 /* Cases when we are here:
7989 * ( list )
7990 * { list } &
7991 * ... | ( list ) | ...
7992 * ... | { list } | ...
7993 */
7994#if BB_MMU
7995 int rcode;
7996 debug_printf_exec("pseudo_exec: run_list\n");
7997 reset_traps_to_defaults();
7998 rcode = run_list(command->group);
7999 /* OK to leak memory by not calling free_pipe_list,
8000 * since this process is about to exit */
8001 _exit(rcode);
8002#else
8003 re_execute_shell(&nommu_save->argv_from_re_execing,
8004 command->group_as_string,
8005 G.global_argv[0],
8006 G.global_argv + 1,
8007 NULL);
8008#endif
8009 }
8010
8011 /* Case when we are here: ... | >file */
8012 debug_printf_exec("pseudo_exec'ed null command\n");
8013 _exit(EXIT_SUCCESS);
8014}
8015
8016#if ENABLE_HUSH_JOB
8017static const char *get_cmdtext(struct pipe *pi)
8018{
8019 char **argv;
8020 char *p;
8021 int len;
8022
8023 /* This is subtle. ->cmdtext is created only on first backgrounding.
8024 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
8025 * On subsequent bg argv is trashed, but we won't use it */
8026 if (pi->cmdtext)
8027 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008028
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008029 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008030 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008031 pi->cmdtext = xzalloc(1);
8032 return pi->cmdtext;
8033 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008034 len = 0;
8035 do {
8036 len += strlen(*argv) + 1;
8037 } while (*++argv);
8038 p = xmalloc(len);
8039 pi->cmdtext = p;
8040 argv = pi->cmds[0].argv;
8041 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01008042 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008043 *p++ = ' ';
8044 } while (*++argv);
8045 p[-1] = '\0';
8046 return pi->cmdtext;
8047}
8048
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008049static void remove_job_from_table(struct pipe *pi)
8050{
8051 struct pipe *prev_pipe;
8052
8053 if (pi == G.job_list) {
8054 G.job_list = pi->next;
8055 } else {
8056 prev_pipe = G.job_list;
8057 while (prev_pipe->next != pi)
8058 prev_pipe = prev_pipe->next;
8059 prev_pipe->next = pi->next;
8060 }
8061 G.last_jobid = 0;
8062 if (G.job_list)
8063 G.last_jobid = G.job_list->jobid;
8064}
8065
8066static void delete_finished_job(struct pipe *pi)
8067{
8068 remove_job_from_table(pi);
8069 free_pipe(pi);
8070}
8071
8072static void clean_up_last_dead_job(void)
8073{
8074 if (G.job_list && !G.job_list->alive_cmds)
8075 delete_finished_job(G.job_list);
8076}
8077
Denys Vlasenko16096292017-07-10 10:00:28 +02008078static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008079{
8080 struct pipe *job, **jobp;
8081 int i;
8082
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008083 clean_up_last_dead_job();
8084
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008085 /* Find the end of the list, and find next job ID to use */
8086 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008087 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008088 while ((job = *jobp) != NULL) {
8089 if (job->jobid > i)
8090 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008091 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008092 }
8093 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008094
Denys Vlasenko9e55a152017-07-10 10:01:12 +02008095 /* Create a new job struct at the end */
8096 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008097 job->next = NULL;
8098 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
8099 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
8100 for (i = 0; i < pi->num_cmds; i++) {
8101 job->cmds[i].pid = pi->cmds[i].pid;
8102 /* all other fields are not used and stay zero */
8103 }
8104 job->cmdtext = xstrdup(get_cmdtext(pi));
8105
8106 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01008107 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008108 G.last_jobid = job->jobid;
8109}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008110#endif /* JOB */
8111
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008112static int job_exited_or_stopped(struct pipe *pi)
8113{
8114 int rcode, i;
8115
8116 if (pi->alive_cmds != pi->stopped_cmds)
8117 return -1;
8118
8119 /* All processes in fg pipe have exited or stopped */
8120 rcode = 0;
8121 i = pi->num_cmds;
8122 while (--i >= 0) {
8123 rcode = pi->cmds[i].cmd_exitcode;
8124 /* usually last process gives overall exitstatus,
8125 * but with "set -o pipefail", last *failed* process does */
8126 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
8127 break;
8128 }
8129 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8130 return rcode;
8131}
8132
Denys Vlasenko7e675362016-10-28 21:57:31 +02008133static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008134{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008135#if ENABLE_HUSH_JOB
8136 struct pipe *pi;
8137#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008138 int i, dead;
8139
8140 dead = WIFEXITED(status) || WIFSIGNALED(status);
8141
8142#if DEBUG_JOBS
8143 if (WIFSTOPPED(status))
8144 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
8145 childpid, WSTOPSIG(status), WEXITSTATUS(status));
8146 if (WIFSIGNALED(status))
8147 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
8148 childpid, WTERMSIG(status), WEXITSTATUS(status));
8149 if (WIFEXITED(status))
8150 debug_printf_jobs("pid %d exited, exitcode %d\n",
8151 childpid, WEXITSTATUS(status));
8152#endif
8153 /* Were we asked to wait for a fg pipe? */
8154 if (fg_pipe) {
8155 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008156
Denys Vlasenko7e675362016-10-28 21:57:31 +02008157 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008158 int rcode;
8159
Denys Vlasenko7e675362016-10-28 21:57:31 +02008160 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
8161 if (fg_pipe->cmds[i].pid != childpid)
8162 continue;
8163 if (dead) {
8164 int ex;
8165 fg_pipe->cmds[i].pid = 0;
8166 fg_pipe->alive_cmds--;
8167 ex = WEXITSTATUS(status);
8168 /* bash prints killer signal's name for *last*
8169 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8170 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8171 */
8172 if (WIFSIGNALED(status)) {
8173 int sig = WTERMSIG(status);
8174 if (i == fg_pipe->num_cmds-1)
8175 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8176 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8177 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8178 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8179 * Maybe we need to use sig | 128? */
8180 ex = sig + 128;
8181 }
8182 fg_pipe->cmds[i].cmd_exitcode = ex;
8183 } else {
8184 fg_pipe->stopped_cmds++;
8185 }
8186 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8187 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008188 rcode = job_exited_or_stopped(fg_pipe);
8189 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008190/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8191 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8192 * and "killall -STOP cat" */
8193 if (G_interactive_fd) {
8194#if ENABLE_HUSH_JOB
8195 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008196 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008197#endif
8198 return rcode;
8199 }
8200 if (fg_pipe->alive_cmds == 0)
8201 return rcode;
8202 }
8203 /* There are still running processes in the fg_pipe */
8204 return -1;
8205 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008206 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008207 }
8208
8209#if ENABLE_HUSH_JOB
8210 /* We were asked to wait for bg or orphaned children */
8211 /* No need to remember exitcode in this case */
8212 for (pi = G.job_list; pi; pi = pi->next) {
8213 for (i = 0; i < pi->num_cmds; i++) {
8214 if (pi->cmds[i].pid == childpid)
8215 goto found_pi_and_prognum;
8216 }
8217 }
8218 /* Happens when shell is used as init process (init=/bin/sh) */
8219 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8220 return -1; /* this wasn't a process from fg_pipe */
8221
8222 found_pi_and_prognum:
8223 if (dead) {
8224 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008225 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008226 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008227 rcode = 128 + WTERMSIG(status);
8228 pi->cmds[i].cmd_exitcode = rcode;
8229 if (G.last_bg_pid == pi->cmds[i].pid)
8230 G.last_bg_pid_exitcode = rcode;
8231 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008232 pi->alive_cmds--;
8233 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008234 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008235 printf(JOB_STATUS_FORMAT, pi->jobid,
8236 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008237 delete_finished_job(pi);
8238 } else {
8239/*
8240 * bash deletes finished jobs from job table only in interactive mode,
8241 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8242 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8243 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8244 * We only retain one "dead" job, if it's the single job on the list.
8245 * This covers most of real-world scenarios where this is useful.
8246 */
8247 if (pi != G.job_list)
8248 delete_finished_job(pi);
8249 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008250 }
8251 } else {
8252 /* child stopped */
8253 pi->stopped_cmds++;
8254 }
8255#endif
8256 return -1; /* this wasn't a process from fg_pipe */
8257}
8258
8259/* Check to see if any processes have exited -- if they have,
8260 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008261 *
8262 * If non-NULL fg_pipe: wait for its completion or stop.
8263 * Return its exitcode or zero if stopped.
8264 *
8265 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8266 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8267 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8268 * or 0 if no children changed status.
8269 *
8270 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8271 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8272 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008273 */
8274static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8275{
8276 int attributes;
8277 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008278 int rcode = 0;
8279
8280 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8281
8282 attributes = WUNTRACED;
8283 if (fg_pipe == NULL)
8284 attributes |= WNOHANG;
8285
8286 errno = 0;
8287#if ENABLE_HUSH_FAST
8288 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8289//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8290//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8291 /* There was neither fork nor SIGCHLD since last waitpid */
8292 /* Avoid doing waitpid syscall if possible */
8293 if (!G.we_have_children) {
8294 errno = ECHILD;
8295 return -1;
8296 }
8297 if (fg_pipe == NULL) { /* is WNOHANG set? */
8298 /* We have children, but they did not exit
8299 * or stop yet (we saw no SIGCHLD) */
8300 return 0;
8301 }
8302 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8303 }
8304#endif
8305
8306/* Do we do this right?
8307 * bash-3.00# sleep 20 | false
8308 * <ctrl-Z pressed>
8309 * [3]+ Stopped sleep 20 | false
8310 * bash-3.00# echo $?
8311 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8312 * [hush 1.14.0: yes we do it right]
8313 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008314 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008315 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008316#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008317 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008318 i = G.count_SIGCHLD;
8319#endif
8320 childpid = waitpid(-1, &status, attributes);
8321 if (childpid <= 0) {
8322 if (childpid && errno != ECHILD)
8323 bb_perror_msg("waitpid");
8324#if ENABLE_HUSH_FAST
8325 else { /* Until next SIGCHLD, waitpid's are useless */
8326 G.we_have_children = (childpid == 0);
8327 G.handled_SIGCHLD = i;
8328//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8329 }
8330#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008331 /* ECHILD (no children), or 0 (no change in children status) */
8332 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008333 break;
8334 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008335 rcode = process_wait_result(fg_pipe, childpid, status);
8336 if (rcode >= 0) {
8337 /* fg_pipe exited or stopped */
8338 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008339 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008340 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008341 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008342 rcode = WEXITSTATUS(status);
8343 if (WIFSIGNALED(status))
8344 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008345 if (WIFSTOPPED(status))
8346 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8347 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008348 rcode++;
8349 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008350 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008351 /* This wasn't one of our processes, or */
8352 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008353 } /* while (waitpid succeeds)... */
8354
8355 return rcode;
8356}
8357
8358#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008359static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008360{
8361 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008362 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008363 if (G_saved_tty_pgrp) {
8364 /* Job finished, move the shell to the foreground */
8365 p = getpgrp(); /* our process group id */
8366 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8367 tcsetpgrp(G_interactive_fd, p);
8368 }
8369 return rcode;
8370}
8371#endif
8372
8373/* Start all the jobs, but don't wait for anything to finish.
8374 * See checkjobs().
8375 *
8376 * Return code is normally -1, when the caller has to wait for children
8377 * to finish to determine the exit status of the pipe. If the pipe
8378 * is a simple builtin command, however, the action is done by the
8379 * time run_pipe returns, and the exit code is provided as the
8380 * return value.
8381 *
8382 * Returns -1 only if started some children. IOW: we have to
8383 * mask out retvals of builtins etc with 0xff!
8384 *
8385 * The only case when we do not need to [v]fork is when the pipe
8386 * is single, non-backgrounded, non-subshell command. Examples:
8387 * cmd ; ... { list } ; ...
8388 * cmd && ... { list } && ...
8389 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008390 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008391 * or (if SH_STANDALONE) an applet, and we can run the { list }
8392 * with run_list. If it isn't one of these, we fork and exec cmd.
8393 *
8394 * Cases when we must fork:
8395 * non-single: cmd | cmd
8396 * backgrounded: cmd & { list } &
8397 * subshell: ( list ) [&]
8398 */
8399#if !ENABLE_HUSH_MODE_X
Denys Vlasenkoc96bb2c2018-06-26 15:43:56 +02008400#define redirect_and_varexp_helper(command, squirrel, argv_expanded) \
8401 redirect_and_varexp_helper(command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008402#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008403static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008404 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008405 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008406 char **argv_expanded)
8407{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008408 /* Assignments occur before redirects. Try:
8409 * a=`sleep 1` sleep 2 3>/qwe/rty
8410 */
8411
8412 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8413 dump_cmd_in_x_mode(new_env);
8414 dump_cmd_in_x_mode(argv_expanded);
8415 /* this takes ownership of new_env[i] elements, and frees new_env: */
8416 set_vars_and_save_old(new_env);
8417
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008418 /* setup_redirects acts on file descriptors, not FILEs.
8419 * This is perfect for work that comes after exec().
8420 * Is it really safe for inline use? Experimentally,
8421 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008422 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008423}
8424static NOINLINE int run_pipe(struct pipe *pi)
8425{
8426 static const char *const null_ptr = NULL;
8427
8428 int cmd_no;
8429 int next_infd;
8430 struct command *command;
8431 char **argv_expanded;
8432 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008433 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008434 int rcode;
8435
8436 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8437 debug_enter();
8438
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008439 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8440 * Result should be 3 lines: q w e, qwe, q w e
8441 */
Denys Vlasenko96786362018-04-11 16:02:58 +02008442 if (G.ifs_whitespace != G.ifs)
8443 free(G.ifs_whitespace);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008444 G.ifs = get_local_var_value("IFS");
Denys Vlasenko96786362018-04-11 16:02:58 +02008445 if (G.ifs) {
8446 char *p;
8447 G.ifs_whitespace = (char*)G.ifs;
8448 p = skip_whitespace(G.ifs);
8449 if (*p) {
8450 /* Not all $IFS is whitespace */
8451 char *d;
8452 int len = p - G.ifs;
8453 p = skip_non_whitespace(p);
8454 G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
8455 d = mempcpy(G.ifs_whitespace, G.ifs, len);
8456 while (*p) {
8457 if (isspace(*p))
8458 *d++ = *p;
8459 p++;
8460 }
8461 *d = '\0';
8462 }
8463 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008464 G.ifs = defifs;
Denys Vlasenko96786362018-04-11 16:02:58 +02008465 G.ifs_whitespace = (char*)G.ifs;
8466 }
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008467
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008468 IF_HUSH_JOB(pi->pgrp = -1;)
8469 pi->stopped_cmds = 0;
8470 command = &pi->cmds[0];
8471 argv_expanded = NULL;
8472
8473 if (pi->num_cmds != 1
8474 || pi->followup == PIPE_BG
8475 || command->cmd_type == CMD_SUBSHELL
8476 ) {
8477 goto must_fork;
8478 }
8479
8480 pi->alive_cmds = 1;
8481
8482 debug_printf_exec(": group:%p argv:'%s'\n",
8483 command->group, command->argv ? command->argv[0] : "NONE");
8484
8485 if (command->group) {
8486#if ENABLE_HUSH_FUNCTIONS
8487 if (command->cmd_type == CMD_FUNCDEF) {
8488 /* "executing" func () { list } */
8489 struct function *funcp;
8490
8491 funcp = new_function(command->argv[0]);
8492 /* funcp->name is already set to argv[0] */
8493 funcp->body = command->group;
8494# if !BB_MMU
8495 funcp->body_as_string = command->group_as_string;
8496 command->group_as_string = NULL;
8497# endif
8498 command->group = NULL;
8499 command->argv[0] = NULL;
8500 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8501 funcp->parent_cmd = command;
8502 command->child_func = funcp;
8503
8504 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8505 debug_leave();
8506 return EXIT_SUCCESS;
8507 }
8508#endif
8509 /* { list } */
8510 debug_printf("non-subshell group\n");
8511 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008512 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008513 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008514//FIXME: we need to pass squirrel down into run_list()
8515//for SH_STANDALONE case, or else this construct:
8516// { find /proc/self/fd; true; } >FILE; cmd2
8517//has no way of closing saved fd#1 for "find",
8518//and in SH_STANDALONE mode, "find" is not execed,
8519//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008520 rcode = run_list(command->group) & 0xff;
8521 }
8522 restore_redirects(squirrel);
8523 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8524 debug_leave();
8525 debug_printf_exec("run_pipe: return %d\n", rcode);
8526 return rcode;
8527 }
8528
8529 argv = command->argv ? command->argv : (char **) &null_ptr;
8530 {
8531 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008532 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8533 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008534 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008535 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008536
Denys Vlasenko5807e182018-02-08 19:19:04 +01008537#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008538 if (G.lineno_var)
8539 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8540#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008541
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008542 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008543 /* Assignments, but no command.
8544 * Ensure redirects take effect (that is, create files).
8545 * Try "a=t >file"
8546 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008547 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008548 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008549 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008550 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008551 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008552
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008553 /* Set shell variables */
8554 if (G_x_mode)
8555 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008556 i = 0;
8557 while (i < command->assignment_cnt) {
Denys Vlasenko34179952018-04-11 13:47:59 +02008558 char *p = expand_string_to_string(argv[i],
8559 EXP_FLAG_ESC_GLOB_CHARS,
8560 /*unbackslash:*/ 1
8561 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008562 if (G_x_mode)
8563 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008564 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008565 if (set_local_var(p, /*flag:*/ 0)) {
8566 /* assignment to readonly var / putenv error? */
8567 rcode = 1;
8568 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008569 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008570 }
8571 if (G_x_mode)
8572 bb_putchar_stderr('\n');
8573 /* Redirect error sets $? to 1. Otherwise,
8574 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008575 * Else, clear $?:
8576 * false; q=`exit 2`; echo $? - should print 2
8577 * false; x=1; echo $? - should print 0
8578 * Because of the 2nd case, we can't just use G.last_exitcode.
8579 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008580 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008581 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008582 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8583 debug_leave();
8584 debug_printf_exec("run_pipe: return %d\n", rcode);
8585 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008586 }
8587
8588 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008589#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008590 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008591 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008592 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008593#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008594 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008595
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008596 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008597 if (!argv_expanded[0]) {
8598 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008599 /* `false` still has to set exitcode 1 */
8600 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008601 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008602 }
8603
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008604 old_vars = NULL;
8605 sv_shadowed = G.shadowed_vars_pp;
8606
Denys Vlasenko75481d32017-07-31 05:27:09 +02008607 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008608 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8609 IF_HUSH_FUNCTIONS(x = NULL;)
8610 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008611 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008612 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008613 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8614 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008615 /*
8616 * Variable assignments are executed, but then "forgotten":
8617 * a=`sleep 1;echo A` exec 3>&-; echo $a
8618 * sleeps, but prints nothing.
8619 */
8620 enter_var_nest_level();
8621 G.shadowed_vars_pp = &old_vars;
8622 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8623 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008624 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008625
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008626 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008627 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008628
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008629 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008630 * a=b true; env | grep ^a=
8631 */
8632 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008633 /* Collect all variables "shadowed" by helper
8634 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8635 * into old_vars list:
8636 */
8637 G.shadowed_vars_pp = &old_vars;
8638 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008639 if (rcode == 0) {
8640 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008641 /* Do not collect *to old_vars list* vars shadowed
8642 * by e.g. "local VAR" builtin (collect them
8643 * in the previously nested list instead):
8644 * don't want them to be restored immediately
8645 * after "local" completes.
8646 */
8647 G.shadowed_vars_pp = sv_shadowed;
8648
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008649 debug_printf_exec(": builtin '%s' '%s'...\n",
8650 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008651 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008652 rcode = x->b_function(argv_expanded) & 0xff;
8653 fflush_all();
8654 }
8655#if ENABLE_HUSH_FUNCTIONS
8656 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008657 debug_printf_exec(": function '%s' '%s'...\n",
8658 funcp->name, argv_expanded[1]);
8659 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008660 /*
8661 * But do collect *to old_vars list* vars shadowed
8662 * within function execution. To that end, restore
8663 * this pointer _after_ function run:
8664 */
8665 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008666 }
8667#endif
8668 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008669 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008670 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008671 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008672 if (n < 0 || !APPLET_IS_NOFORK(n))
8673 goto must_fork;
8674
8675 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008676 /* Collect all variables "shadowed" by helper into old_vars list */
8677 G.shadowed_vars_pp = &old_vars;
8678 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8679 G.shadowed_vars_pp = sv_shadowed;
8680
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008681 if (rcode == 0) {
8682 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8683 argv_expanded[0], argv_expanded[1]);
8684 /*
8685 * Note: signals (^C) can't interrupt here.
8686 * We remember them and they will be acted upon
8687 * after applet returns.
8688 * This makes applets which can run for a long time
8689 * and/or wait for user input ineligible for NOFORK:
8690 * for example, "yes" or "rm" (rm -i waits for input).
8691 */
8692 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008693 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008694 } else
8695 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008696
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008697 restore_redirects(squirrel);
8698 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008699 leave_var_nest_level();
8700 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008701
8702 /*
8703 * Try "usleep 99999999" + ^C + "echo $?"
8704 * with FEATURE_SH_NOFORK=y.
8705 */
8706 if (!funcp) {
8707 /* It was builtin or nofork.
8708 * if this would be a real fork/execed program,
8709 * it should have died if a fatal sig was received.
8710 * But OTOH, there was no separate process,
8711 * the sig was sent to _shell_, not to non-existing
8712 * child.
8713 * Let's just handle ^C only, this one is obvious:
8714 * we aren't ok with exitcode 0 when ^C was pressed
8715 * during builtin/nofork.
8716 */
8717 if (sigismember(&G.pending_set, SIGINT))
8718 rcode = 128 + SIGINT;
8719 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008720 free(argv_expanded);
8721 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8722 debug_leave();
8723 debug_printf_exec("run_pipe return %d\n", rcode);
8724 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008725 }
8726
8727 must_fork:
8728 /* NB: argv_expanded may already be created, and that
8729 * might include `cmd` runs! Do not rerun it! We *must*
8730 * use argv_expanded if it's non-NULL */
8731
8732 /* Going to fork a child per each pipe member */
8733 pi->alive_cmds = 0;
8734 next_infd = 0;
8735
8736 cmd_no = 0;
8737 while (cmd_no < pi->num_cmds) {
8738 struct fd_pair pipefds;
8739#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008740 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008741 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008742 nommu_save.old_vars = NULL;
8743 nommu_save.argv = NULL;
8744 nommu_save.argv_from_re_execing = NULL;
8745#endif
8746 command = &pi->cmds[cmd_no];
8747 cmd_no++;
8748 if (command->argv) {
8749 debug_printf_exec(": pipe member '%s' '%s'...\n",
8750 command->argv[0], command->argv[1]);
8751 } else {
8752 debug_printf_exec(": pipe member with no argv\n");
8753 }
8754
8755 /* pipes are inserted between pairs of commands */
8756 pipefds.rd = 0;
8757 pipefds.wr = 1;
8758 if (cmd_no < pi->num_cmds)
8759 xpiped_pair(pipefds);
8760
Denys Vlasenko5807e182018-02-08 19:19:04 +01008761#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008762 if (G.lineno_var)
8763 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8764#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008765
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008766 command->pid = BB_MMU ? fork() : vfork();
8767 if (!command->pid) { /* child */
8768#if ENABLE_HUSH_JOB
8769 disable_restore_tty_pgrp_on_exit();
8770 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8771
8772 /* Every child adds itself to new process group
8773 * with pgid == pid_of_first_child_in_pipe */
8774 if (G.run_list_level == 1 && G_interactive_fd) {
8775 pid_t pgrp;
8776 pgrp = pi->pgrp;
8777 if (pgrp < 0) /* true for 1st process only */
8778 pgrp = getpid();
8779 if (setpgid(0, pgrp) == 0
8780 && pi->followup != PIPE_BG
8781 && G_saved_tty_pgrp /* we have ctty */
8782 ) {
8783 /* We do it in *every* child, not just first,
8784 * to avoid races */
8785 tcsetpgrp(G_interactive_fd, pgrp);
8786 }
8787 }
8788#endif
8789 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8790 /* 1st cmd in backgrounded pipe
8791 * should have its stdin /dev/null'ed */
8792 close(0);
8793 if (open(bb_dev_null, O_RDONLY))
8794 xopen("/", O_RDONLY);
8795 } else {
8796 xmove_fd(next_infd, 0);
8797 }
8798 xmove_fd(pipefds.wr, 1);
8799 if (pipefds.rd > 1)
8800 close(pipefds.rd);
8801 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008802 * and the pipe fd (fd#1) is available for dup'ing:
8803 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8804 * of cmd1 goes into pipe.
8805 */
8806 if (setup_redirects(command, NULL)) {
8807 /* Happens when redir file can't be opened:
8808 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8809 * FOO
8810 * hush: can't open '/qwe/rty': No such file or directory
8811 * BAZ
8812 * (echo BAR is not executed, it hits _exit(1) below)
8813 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008814 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008815 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008816
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008817 /* Stores to nommu_save list of env vars putenv'ed
8818 * (NOMMU, on MMU we don't need that) */
8819 /* cast away volatility... */
8820 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8821 /* pseudo_exec() does not return */
8822 }
8823
8824 /* parent or error */
8825#if ENABLE_HUSH_FAST
8826 G.count_SIGCHLD++;
8827//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8828#endif
8829 enable_restore_tty_pgrp_on_exit();
8830#if !BB_MMU
8831 /* Clean up after vforked child */
8832 free(nommu_save.argv);
8833 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008834 G.var_nest_level = sv_var_nest_level;
8835 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008836 add_vars(nommu_save.old_vars);
8837#endif
8838 free(argv_expanded);
8839 argv_expanded = NULL;
8840 if (command->pid < 0) { /* [v]fork failed */
8841 /* Clearly indicate, was it fork or vfork */
8842 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8843 } else {
8844 pi->alive_cmds++;
8845#if ENABLE_HUSH_JOB
8846 /* Second and next children need to know pid of first one */
8847 if (pi->pgrp < 0)
8848 pi->pgrp = command->pid;
8849#endif
8850 }
8851
8852 if (cmd_no > 1)
8853 close(next_infd);
8854 if (cmd_no < pi->num_cmds)
8855 close(pipefds.wr);
8856 /* Pass read (output) pipe end to next iteration */
8857 next_infd = pipefds.rd;
8858 }
8859
8860 if (!pi->alive_cmds) {
8861 debug_leave();
8862 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8863 return 1;
8864 }
8865
8866 debug_leave();
8867 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8868 return -1;
8869}
8870
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008871/* NB: called by pseudo_exec, and therefore must not modify any
8872 * global data until exec/_exit (we can be a child after vfork!) */
8873static int run_list(struct pipe *pi)
8874{
8875#if ENABLE_HUSH_CASE
8876 char *case_word = NULL;
8877#endif
8878#if ENABLE_HUSH_LOOPS
8879 struct pipe *loop_top = NULL;
8880 char **for_lcur = NULL;
8881 char **for_list = NULL;
8882#endif
8883 smallint last_followup;
8884 smalluint rcode;
8885#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8886 smalluint cond_code = 0;
8887#else
8888 enum { cond_code = 0 };
8889#endif
8890#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008891 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008892 smallint last_rword; /* ditto */
8893#endif
8894
8895 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8896 debug_enter();
8897
8898#if ENABLE_HUSH_LOOPS
8899 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008900 {
8901 struct pipe *cpipe;
8902 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8903 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8904 continue;
8905 /* current word is FOR or IN (BOLD in comments below) */
8906 if (cpipe->next == NULL) {
8907 syntax_error("malformed for");
8908 debug_leave();
8909 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8910 return 1;
8911 }
8912 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8913 if (cpipe->next->res_word == RES_DO)
8914 continue;
8915 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8916 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8917 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8918 ) {
8919 syntax_error("malformed for");
8920 debug_leave();
8921 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8922 return 1;
8923 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008924 }
8925 }
8926#endif
8927
8928 /* Past this point, all code paths should jump to ret: label
8929 * in order to return, no direct "return" statements please.
8930 * This helps to ensure that no memory is leaked. */
8931
8932#if ENABLE_HUSH_JOB
8933 G.run_list_level++;
8934#endif
8935
8936#if HAS_KEYWORDS
8937 rword = RES_NONE;
8938 last_rword = RES_XXXX;
8939#endif
8940 last_followup = PIPE_SEQ;
8941 rcode = G.last_exitcode;
8942
8943 /* Go through list of pipes, (maybe) executing them. */
8944 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008945 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008946 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008947
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008948 if (G.flag_SIGINT)
8949 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008950 if (G_flag_return_in_progress == 1)
8951 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008952
8953 IF_HAS_KEYWORDS(rword = pi->res_word;)
8954 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8955 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008956
8957 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008958 if (
8959#if ENABLE_HUSH_IF
8960 rword == RES_IF || rword == RES_ELIF ||
8961#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008962 pi->followup != PIPE_SEQ
8963 ) {
8964 G.errexit_depth++;
8965 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008966#if ENABLE_HUSH_LOOPS
8967 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8968 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8969 ) {
8970 /* start of a loop: remember where loop starts */
8971 loop_top = pi;
8972 G.depth_of_loop++;
8973 }
8974#endif
8975 /* Still in the same "if...", "then..." or "do..." branch? */
8976 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8977 if ((rcode == 0 && last_followup == PIPE_OR)
8978 || (rcode != 0 && last_followup == PIPE_AND)
8979 ) {
8980 /* It is "<true> || CMD" or "<false> && CMD"
8981 * and we should not execute CMD */
8982 debug_printf_exec("skipped cmd because of || or &&\n");
8983 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008984 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008985 }
8986 }
8987 last_followup = pi->followup;
8988 IF_HAS_KEYWORDS(last_rword = rword;)
8989#if ENABLE_HUSH_IF
8990 if (cond_code) {
8991 if (rword == RES_THEN) {
8992 /* if false; then ... fi has exitcode 0! */
8993 G.last_exitcode = rcode = EXIT_SUCCESS;
8994 /* "if <false> THEN cmd": skip cmd */
8995 continue;
8996 }
8997 } else {
8998 if (rword == RES_ELSE || rword == RES_ELIF) {
8999 /* "if <true> then ... ELSE/ELIF cmd":
9000 * skip cmd and all following ones */
9001 break;
9002 }
9003 }
9004#endif
9005#if ENABLE_HUSH_LOOPS
9006 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
9007 if (!for_lcur) {
9008 /* first loop through for */
9009
9010 static const char encoded_dollar_at[] ALIGN1 = {
9011 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
9012 }; /* encoded representation of "$@" */
9013 static const char *const encoded_dollar_at_argv[] = {
9014 encoded_dollar_at, NULL
9015 }; /* argv list with one element: "$@" */
9016 char **vals;
9017
9018 vals = (char**)encoded_dollar_at_argv;
9019 if (pi->next->res_word == RES_IN) {
9020 /* if no variable values after "in" we skip "for" */
9021 if (!pi->next->cmds[0].argv) {
9022 G.last_exitcode = rcode = EXIT_SUCCESS;
9023 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
9024 break;
9025 }
9026 vals = pi->next->cmds[0].argv;
9027 } /* else: "for var; do..." -> assume "$@" list */
9028 /* create list of variable values */
9029 debug_print_strings("for_list made from", vals);
9030 for_list = expand_strvec_to_strvec(vals);
9031 for_lcur = for_list;
9032 debug_print_strings("for_list", for_list);
9033 }
9034 if (!*for_lcur) {
9035 /* "for" loop is over, clean up */
9036 free(for_list);
9037 for_list = NULL;
9038 for_lcur = NULL;
9039 break;
9040 }
9041 /* Insert next value from for_lcur */
9042 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009043 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009044 continue;
9045 }
9046 if (rword == RES_IN) {
9047 continue; /* "for v IN list;..." - "in" has no cmds anyway */
9048 }
9049 if (rword == RES_DONE) {
9050 continue; /* "done" has no cmds too */
9051 }
9052#endif
9053#if ENABLE_HUSH_CASE
9054 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009055 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenko34179952018-04-11 13:47:59 +02009056 case_word = expand_string_to_string(pi->cmds->argv[0],
9057 EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02009058 debug_printf_exec("CASE word1:'%s'\n", case_word);
9059 //unbackslash(case_word);
9060 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009061 continue;
9062 }
9063 if (rword == RES_MATCH) {
9064 char **argv;
9065
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009066 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009067 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
9068 break;
9069 /* all prev words didn't match, does this one match? */
9070 argv = pi->cmds->argv;
9071 while (*argv) {
Denys Vlasenko34179952018-04-11 13:47:59 +02009072 char *pattern;
9073 debug_printf_exec("expand_string_to_string('%s')\n", *argv);
9074 pattern = expand_string_to_string(*argv,
9075 EXP_FLAG_ESC_GLOB_CHARS,
9076 /*unbackslash:*/ 0
9077 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009078 /* TODO: which FNM_xxx flags to use? */
9079 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenko34179952018-04-11 13:47:59 +02009080 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
9081 pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009082 free(pattern);
Denys Vlasenko34179952018-04-11 13:47:59 +02009083 if (cond_code == 0) {
9084 /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009085 free(case_word);
9086 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009087 break;
9088 }
9089 argv++;
9090 }
9091 continue;
9092 }
9093 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009094 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009095 if (cond_code != 0)
9096 continue; /* not matched yet, skip this pipe */
9097 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01009098 if (rword == RES_ESAC) {
9099 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
9100 if (case_word) {
9101 /* "case" did not match anything: still set $? (to 0) */
9102 G.last_exitcode = rcode = EXIT_SUCCESS;
9103 }
9104 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009105#endif
9106 /* Just pressing <enter> in shell should check for jobs.
9107 * OTOH, in non-interactive shell this is useless
9108 * and only leads to extra job checks */
9109 if (pi->num_cmds == 0) {
9110 if (G_interactive_fd)
9111 goto check_jobs_and_continue;
9112 continue;
9113 }
9114
9115 /* After analyzing all keywords and conditions, we decided
9116 * to execute this pipe. NB: have to do checkjobs(NULL)
9117 * after run_pipe to collect any background children,
9118 * even if list execution is to be stopped. */
9119 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009120#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009121 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009122#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009123 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
9124 if (r != -1) {
9125 /* We ran a builtin, function, or group.
9126 * rcode is already known
9127 * and we don't need to wait for anything. */
9128 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
9129 G.last_exitcode = rcode;
9130 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009131#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009132 /* Was it "break" or "continue"? */
9133 if (G.flag_break_continue) {
9134 smallint fbc = G.flag_break_continue;
9135 /* We might fall into outer *loop*,
9136 * don't want to break it too */
9137 if (loop_top) {
9138 G.depth_break_continue--;
9139 if (G.depth_break_continue == 0)
9140 G.flag_break_continue = 0;
9141 /* else: e.g. "continue 2" should *break* once, *then* continue */
9142 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
9143 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009144 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009145 break;
9146 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009147 /* "continue": simulate end of loop */
9148 rword = RES_DONE;
9149 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009150 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009151#endif
9152 if (G_flag_return_in_progress == 1) {
9153 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9154 break;
9155 }
9156 } else if (pi->followup == PIPE_BG) {
9157 /* What does bash do with attempts to background builtins? */
9158 /* even bash 3.2 doesn't do that well with nested bg:
9159 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
9160 * I'm NOT treating inner &'s as jobs */
9161#if ENABLE_HUSH_JOB
9162 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02009163 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009164#endif
9165 /* Last command's pid goes to $! */
9166 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02009167 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009168 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02009169/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009170 rcode = EXIT_SUCCESS;
9171 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009172 } else {
9173#if ENABLE_HUSH_JOB
9174 if (G.run_list_level == 1 && G_interactive_fd) {
9175 /* Waits for completion, then fg's main shell */
9176 rcode = checkjobs_and_fg_shell(pi);
9177 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009178 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009179 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01009180#endif
9181 /* This one just waits for completion */
9182 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
9183 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
9184 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01009185 G.last_exitcode = rcode;
9186 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009187 }
9188
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009189 /* Handle "set -e" */
9190 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
9191 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
9192 if (G.errexit_depth == 0)
9193 hush_exit(rcode);
9194 }
9195 G.errexit_depth = sv_errexit_depth;
9196
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009197 /* Analyze how result affects subsequent commands */
9198#if ENABLE_HUSH_IF
9199 if (rword == RES_IF || rword == RES_ELIF)
9200 cond_code = rcode;
9201#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009202 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009203 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009204 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009205#if ENABLE_HUSH_LOOPS
9206 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009207 if (pi->next
9208 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009209 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009210 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009211 if (rword == RES_WHILE) {
9212 if (rcode) {
9213 /* "while false; do...done" - exitcode 0 */
9214 G.last_exitcode = rcode = EXIT_SUCCESS;
9215 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009216 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009217 }
9218 }
9219 if (rword == RES_UNTIL) {
9220 if (!rcode) {
9221 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009222 break;
9223 }
9224 }
9225 }
9226#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009227 } /* for (pi) */
9228
9229#if ENABLE_HUSH_JOB
9230 G.run_list_level--;
9231#endif
9232#if ENABLE_HUSH_LOOPS
9233 if (loop_top)
9234 G.depth_of_loop--;
9235 free(for_list);
9236#endif
9237#if ENABLE_HUSH_CASE
9238 free(case_word);
9239#endif
9240 debug_leave();
9241 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9242 return rcode;
9243}
9244
9245/* Select which version we will use */
9246static int run_and_free_list(struct pipe *pi)
9247{
9248 int rcode = 0;
9249 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009250 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009251 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9252 rcode = run_list(pi);
9253 }
9254 /* free_pipe_list has the side effect of clearing memory.
9255 * In the long run that function can be merged with run_list,
9256 * but doing that now would hobble the debugging effort. */
9257 free_pipe_list(pi);
9258 debug_printf_exec("run_and_free_list return %d\n", rcode);
9259 return rcode;
9260}
9261
9262
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009263static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009264{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009265 sighandler_t old_handler;
9266 unsigned sig = 0;
9267 while ((mask >>= 1) != 0) {
9268 sig++;
9269 if (!(mask & 1))
9270 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009271 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009272 /* POSIX allows shell to re-enable SIGCHLD
9273 * even if it was SIG_IGN on entry.
9274 * Therefore we skip IGN check for it:
9275 */
9276 if (sig == SIGCHLD)
9277 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009278 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9279 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9280 */
9281 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009282 if (old_handler == SIG_IGN) {
9283 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009284 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009285#if ENABLE_HUSH_TRAP
9286 if (!G_traps)
9287 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9288 free(G_traps[sig]);
9289 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9290#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009291 }
9292 }
9293}
9294
9295/* Called a few times only (or even once if "sh -c") */
9296static void install_special_sighandlers(void)
9297{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009298 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009299
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009300 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009301 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009302 if (G_interactive_fd) {
9303 mask |= SPECIAL_INTERACTIVE_SIGS;
9304 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009305 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009306 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009307 /* Careful, do not re-install handlers we already installed */
9308 if (G.special_sig_mask != mask) {
9309 unsigned diff = mask & ~G.special_sig_mask;
9310 G.special_sig_mask = mask;
9311 install_sighandlers(diff);
9312 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009313}
9314
9315#if ENABLE_HUSH_JOB
9316/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009317/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009318static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009319{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009320 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009321
9322 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009323 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009324 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9325 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009326 + (1 << SIGBUS ) * HUSH_DEBUG
9327 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009328 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009329 + (1 << SIGABRT)
9330 /* bash 3.2 seems to handle these just like 'fatal' ones */
9331 + (1 << SIGPIPE)
9332 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009333 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009334 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009335 * we never want to restore pgrp on exit, and this fn is not called
9336 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009337 /*+ (1 << SIGHUP )*/
9338 /*+ (1 << SIGTERM)*/
9339 /*+ (1 << SIGINT )*/
9340 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009341 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009342
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009343 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009344}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009345#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009346
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009347static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009348{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009349 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009350 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009351 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009352 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009353 break;
9354 case 'x':
9355 IF_HUSH_MODE_X(G_x_mode = state;)
9356 break;
9357 case 'o':
9358 if (!o_opt) {
9359 /* "set -+o" without parameter.
9360 * in bash, set -o produces this output:
9361 * pipefail off
9362 * and set +o:
9363 * set +o pipefail
9364 * We always use the second form.
9365 */
9366 const char *p = o_opt_strings;
9367 idx = 0;
9368 while (*p) {
9369 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9370 idx++;
9371 p += strlen(p) + 1;
9372 }
9373 break;
9374 }
9375 idx = index_in_strings(o_opt_strings, o_opt);
9376 if (idx >= 0) {
9377 G.o_opt[idx] = state;
9378 break;
9379 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009380 case 'e':
9381 G.o_opt[OPT_O_ERREXIT] = state;
9382 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009383 default:
9384 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009385 }
9386 return EXIT_SUCCESS;
9387}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009388
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009389int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009390int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009391{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009392 enum {
9393 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009394 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009395 };
9396 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009397 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009398 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009399 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009400 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009401
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009402 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009403 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009404 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009405
Denys Vlasenko10c01312011-05-11 11:49:21 +02009406#if ENABLE_HUSH_FAST
9407 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9408#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009409#if !BB_MMU
9410 G.argv0_for_re_execing = argv[0];
9411#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009412
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009413 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009414 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9415 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009416 shell_ver = xzalloc(sizeof(*shell_ver));
9417 shell_ver->flg_export = 1;
9418 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009419 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009420 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009421 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009422
Denys Vlasenko605067b2010-09-06 12:10:51 +02009423 /* Create shell local variables from the values
9424 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009425 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009426 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009427 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009428 if (e) while (*e) {
9429 char *value = strchr(*e, '=');
9430 if (value) { /* paranoia */
9431 cur_var->next = xzalloc(sizeof(*cur_var));
9432 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009433 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009434 cur_var->max_len = strlen(*e);
9435 cur_var->flg_export = 1;
9436 }
9437 e++;
9438 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009439 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009440 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9441 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009442
9443 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009444 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009445
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009446#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9447 /* Set (but not export) PS1/2 unless already set */
9448 if (!get_local_var_value("PS1"))
9449 set_local_var_from_halves("PS1", "\\w \\$ ");
9450 if (!get_local_var_value("PS2"))
9451 set_local_var_from_halves("PS2", "> ");
9452#endif
9453
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009454#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009455 /* Set (but not export) HOSTNAME unless already set */
9456 if (!get_local_var_value("HOSTNAME")) {
9457 struct utsname uts;
9458 uname(&uts);
9459 set_local_var_from_halves("HOSTNAME", uts.nodename);
9460 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009461 /* bash also exports SHLVL and _,
9462 * and sets (but doesn't export) the following variables:
9463 * BASH=/bin/bash
9464 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9465 * BASH_VERSION='3.2.0(1)-release'
9466 * HOSTTYPE=i386
9467 * MACHTYPE=i386-pc-linux-gnu
9468 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009469 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009470 * EUID=<NNNNN>
9471 * UID=<NNNNN>
9472 * GROUPS=()
9473 * LINES=<NNN>
9474 * COLUMNS=<NNN>
9475 * BASH_ARGC=()
9476 * BASH_ARGV=()
9477 * BASH_LINENO=()
9478 * BASH_SOURCE=()
9479 * DIRSTACK=()
9480 * PIPESTATUS=([0]="0")
9481 * HISTFILE=/<xxx>/.bash_history
9482 * HISTFILESIZE=500
9483 * HISTSIZE=500
9484 * MAILCHECK=60
9485 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9486 * SHELL=/bin/bash
9487 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9488 * TERM=dumb
9489 * OPTERR=1
9490 * OPTIND=1
9491 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009492 * PS4='+ '
9493 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009494#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009495
Denys Vlasenko5807e182018-02-08 19:19:04 +01009496#if ENABLE_HUSH_LINENO_VAR
9497 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009498 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9499 set_local_var(p, /*flags*/ 0);
9500 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9501 }
9502#endif
9503
Denis Vlasenko38f63192007-01-22 09:03:07 +00009504#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009505 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009506#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009507
Eric Andersen94ac2442001-05-22 19:05:18 +00009508 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009509 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009510
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009511 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009512
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009513 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009514 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009515 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009516 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009517 * in order to intercept (more) signals.
9518 */
9519
9520 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009521 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009522 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009523 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009524 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009525 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009526#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009527 "<:$:R:V:"
9528# if ENABLE_HUSH_FUNCTIONS
9529 "F:"
9530# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009531#endif
9532 );
9533 if (opt <= 0)
9534 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009535 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009536 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009537 /* Possibilities:
9538 * sh ... -c 'script'
9539 * sh ... -c 'script' ARG0 [ARG1...]
9540 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009541 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009542 * "" needs to be replaced with NULL
9543 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009544 * Note: the form without ARG0 never happens:
9545 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009546 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009547 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009548 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009549 G.root_ppid = getppid();
9550 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009551 G.global_argv = argv + optind;
9552 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009553 if (builtin_argc) {
9554 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9555 const struct built_in_command *x;
9556
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009557 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009558 x = find_builtin(optarg);
9559 if (x) { /* paranoia */
9560 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9561 G.global_argv += builtin_argc;
9562 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009563 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009564 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009565 }
9566 goto final_return;
9567 }
9568 if (!G.global_argv[0]) {
9569 /* -c 'script' (no params): prevent empty $0 */
9570 G.global_argv--; /* points to argv[i] of 'script' */
9571 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009572 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009573 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009574 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009575 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009576 goto final_return;
9577 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009578 /* Well, we cannot just declare interactiveness,
9579 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009580 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009581 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009582 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009583 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009584 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009585 case 'l':
9586 flags |= OPT_login;
9587 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009588#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009589 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009590 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009591 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009592 case '$': {
9593 unsigned long long empty_trap_mask;
9594
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009595 G.root_pid = bb_strtou(optarg, &optarg, 16);
9596 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009597 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9598 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009599 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9600 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009601 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009602 optarg++;
9603 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009604 optarg++;
9605 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9606 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009607 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009608 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009609# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009610 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009611 for (sig = 1; sig < NSIG; sig++) {
9612 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009613 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009614 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009615 }
9616 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009617# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009618 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009619# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009620 optarg++;
9621 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009622# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009623# if ENABLE_HUSH_FUNCTIONS
9624 /* nommu uses re-exec trick for "... | func | ...",
9625 * should allow "return".
9626 * This accidentally allows returns in subshells.
9627 */
9628 G_flag_return_in_progress = -1;
9629# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009630 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009631 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009632 case 'R':
9633 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009634 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009635 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009636# if ENABLE_HUSH_FUNCTIONS
9637 case 'F': {
9638 struct function *funcp = new_function(optarg);
9639 /* funcp->name is already set to optarg */
9640 /* funcp->body is set to NULL. It's a special case. */
9641 funcp->body_as_string = argv[optind];
9642 optind++;
9643 break;
9644 }
9645# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009646#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009647 case 'n':
9648 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009649 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009650 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009651 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009652 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009653#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009654 fprintf(stderr, "Usage: sh [FILE]...\n"
9655 " or: sh -c command [args]...\n\n");
9656 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009657#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009658 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009659#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009660 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009661 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009662
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009663 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9664 G.global_argc = argc - (optind - 1);
9665 G.global_argv = argv + (optind - 1);
9666 G.global_argv[0] = argv[0];
9667
Denys Vlasenkodea47882009-10-09 15:40:49 +02009668 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009669 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009670 G.root_ppid = getppid();
9671 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009672
9673 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009674 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009675 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009676 debug_printf("sourcing /etc/profile\n");
9677 input = fopen_for_read("/etc/profile");
9678 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009679 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009680 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009681 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009682 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009683 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009684 /* bash: after sourcing /etc/profile,
9685 * tries to source (in the given order):
9686 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009687 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009688 * bash also sources ~/.bash_logout on exit.
9689 * If called as sh, skips .bash_XXX files.
9690 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009691 }
9692
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009693 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9694 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009695 FILE *input;
9696 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009697 * "bash <script>" (which is never interactive (unless -i?))
9698 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009699 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009700 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009701 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009702 G.global_argc--;
9703 G.global_argv++;
9704 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009705 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009706 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009707 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009708 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009709 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009710 parse_and_run_file(input);
9711#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009712 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009713#endif
9714 goto final_return;
9715 }
9716
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009717 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009718 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009719 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009720
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009721 /* A shell is interactive if the '-i' flag was given,
9722 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009723 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009724 * no arguments remaining or the -s flag given
9725 * standard input is a terminal
9726 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009727 * Refer to Posix.2, the description of the 'sh' utility.
9728 */
9729#if ENABLE_HUSH_JOB
9730 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009731 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9732 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9733 if (G_saved_tty_pgrp < 0)
9734 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009735
9736 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009737 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009738 if (G_interactive_fd < 0) {
9739 /* try to dup to any fd */
9740 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009741 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009742 /* give up */
9743 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009744 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009745 }
9746 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009747// TODO: track & disallow any attempts of user
9748// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009749 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009750 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009751 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009752 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009753
Mike Frysinger38478a62009-05-20 04:48:06 -04009754 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009755 /* If we were run as 'hush &', sleep until we are
9756 * in the foreground (tty pgrp == our pgrp).
9757 * If we get started under a job aware app (like bash),
9758 * make sure we are now in charge so we don't fight over
9759 * who gets the foreground */
9760 while (1) {
9761 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009762 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9763 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009764 break;
9765 /* send TTIN to ourself (should stop us) */
9766 kill(- shell_pgrp, SIGTTIN);
9767 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009768 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009769
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009770 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009771 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009772
Mike Frysinger38478a62009-05-20 04:48:06 -04009773 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009774 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009775 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009776 /* Put ourselves in our own process group
9777 * (bash, too, does this only if ctty is available) */
9778 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9779 /* Grab control of the terminal */
9780 tcsetpgrp(G_interactive_fd, getpid());
9781 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009782 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009783
9784# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9785 {
9786 const char *hp = get_local_var_value("HISTFILE");
9787 if (!hp) {
9788 hp = get_local_var_value("HOME");
9789 if (hp)
9790 hp = concat_path_file(hp, ".hush_history");
9791 } else {
9792 hp = xstrdup(hp);
9793 }
9794 if (hp) {
9795 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009796 //set_local_var(xasprintf("HISTFILE=%s", ...));
9797 }
9798# if ENABLE_FEATURE_SH_HISTFILESIZE
9799 hp = get_local_var_value("HISTFILESIZE");
9800 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9801# endif
9802 }
9803# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009804 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009805 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009806 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009807#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009808 /* No job control compiled in, only prompt/line editing */
9809 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009810 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009811 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009812 /* try to dup to any fd */
Denys Vlasenkod1a83232018-06-26 15:50:33 +02009813 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009814 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009815 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009816 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009817 }
9818 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009819 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009820 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009821 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009822 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009823#else
9824 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009825 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009826#endif
9827 /* bash:
9828 * if interactive but not a login shell, sources ~/.bashrc
9829 * (--norc turns this off, --rcfile <file> overrides)
9830 */
9831
9832 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009833 /* note: ash and hush share this string */
9834 printf("\n\n%s %s\n"
9835 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9836 "\n",
9837 bb_banner,
9838 "hush - the humble shell"
9839 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009840 }
9841
Denis Vlasenkof9375282009-04-05 19:13:39 +00009842 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009843
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009844 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009845 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009846}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009847
9848
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009849/*
9850 * Built-ins
9851 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009852static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009853{
9854 return 0;
9855}
9856
Denys Vlasenko265062d2017-01-10 15:13:30 +01009857#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009858static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009859{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009860 int argc = string_array_len(argv);
9861 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009862}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009863#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009864#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009865static int FAST_FUNC builtin_test(char **argv)
9866{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009867 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009868}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009869#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009870#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009871static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009872{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009873 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009874}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009875#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009876#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009877static int FAST_FUNC builtin_printf(char **argv)
9878{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009879 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009880}
9881#endif
9882
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009883#if ENABLE_HUSH_HELP
9884static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9885{
9886 const struct built_in_command *x;
9887
9888 printf(
9889 "Built-in commands:\n"
9890 "------------------\n");
9891 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9892 if (x->b_descr)
9893 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9894 }
9895 return EXIT_SUCCESS;
9896}
9897#endif
9898
9899#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9900static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9901{
9902 show_history(G.line_input_state);
9903 return EXIT_SUCCESS;
9904}
9905#endif
9906
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009907static char **skip_dash_dash(char **argv)
9908{
9909 argv++;
9910 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9911 argv++;
9912 return argv;
9913}
9914
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009915static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009916{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009917 const char *newdir;
9918
9919 argv = skip_dash_dash(argv);
9920 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009921 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009922 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009923 * bash says "bash: cd: HOME not set" and does nothing
9924 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009925 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009926 const char *home = get_local_var_value("HOME");
9927 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009928 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009929 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009930 /* Mimic bash message exactly */
9931 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009932 return EXIT_FAILURE;
9933 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009934 /* Read current dir (get_cwd(1) is inside) and set PWD.
9935 * Note: do not enforce exporting. If PWD was unset or unexported,
9936 * set it again, but do not export. bash does the same.
9937 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009938 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009939 return EXIT_SUCCESS;
9940}
9941
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009942static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9943{
9944 puts(get_cwd(0));
9945 return EXIT_SUCCESS;
9946}
9947
9948static int FAST_FUNC builtin_eval(char **argv)
9949{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009950 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009951
Denys Vlasenkob0441a72018-07-15 18:03:56 +02009952 if (!argv[0])
9953 return EXIT_SUCCESS;
Denys Vlasenko1f191122018-01-11 13:17:30 +01009954
Denys Vlasenkob0441a72018-07-15 18:03:56 +02009955 if (!argv[1]) {
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009956 /* bash:
9957 * eval "echo Hi; done" ("done" is syntax error):
9958 * "echo Hi" will not execute too.
9959 */
Denys Vlasenkob0441a72018-07-15 18:03:56 +02009960 parse_and_run_string(argv[0]);
9961 } else {
9962 /* "The eval utility shall construct a command by
9963 * concatenating arguments together, separating
9964 * each with a <space> character."
9965 */
9966 char *str, *p;
9967 unsigned len = 0;
9968 char **pp = argv;
9969 do
9970 len += strlen(*pp) + 1;
9971 while (*++pp);
9972 str = p = xmalloc(len);
9973 pp = argv;
9974 for (;;) {
9975 p = stpcpy(p, *pp);
9976 pp++;
9977 if (!*pp)
9978 break;
9979 *p++ = ' ';
9980 }
9981 parse_and_run_string(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009982 free(str);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009983 }
Denys Vlasenkob0441a72018-07-15 18:03:56 +02009984 return G.last_exitcode;
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009985}
9986
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009987static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009988{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009989 argv = skip_dash_dash(argv);
9990 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009991 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009992
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009993 /* Careful: we can end up here after [v]fork. Do not restore
9994 * tty pgrp then, only top-level shell process does that */
9995 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9996 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9997
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009998 /* Saved-redirect fds, script fds and G_interactive_fd are still
9999 * open here. However, they are all CLOEXEC, and execv below
10000 * closes them. Try interactive "exec ls -l /proc/self/fd",
10001 * it should show no extra open fds in the "ls" process.
10002 * If we'd try to run builtins/NOEXECs, this would need improving.
10003 */
10004 //close_saved_fds_and_FILE_fds();
10005
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010006 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010007 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +020010008 * and tcsetpgrp, and this is inherently racy.
10009 */
10010 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010011}
10012
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010013static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010014{
Denis Vlasenkocd418a22009-04-06 18:08:35 +000010015 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +000010016
10017 /* interactive bash:
10018 * # trap "echo EEE" EXIT
10019 * # exit
10020 * exit
10021 * There are stopped jobs.
10022 * (if there are _stopped_ jobs, running ones don't count)
10023 * # exit
10024 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +010010025 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +000010026 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +020010027 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +000010028 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +000010029
10030 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010031 argv = skip_dash_dash(argv);
10032 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +000010033 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010034 /* mimic bash: exit 123abc == exit 255 + error msg */
10035 xfunc_error_retval = 255;
10036 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010037 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010038}
10039
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010040#if ENABLE_HUSH_TYPE
10041/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
10042static int FAST_FUNC builtin_type(char **argv)
10043{
10044 int ret = EXIT_SUCCESS;
10045
10046 while (*++argv) {
10047 const char *type;
10048 char *path = NULL;
10049
10050 if (0) {} /* make conditional compile easier below */
10051 /*else if (find_alias(*argv))
10052 type = "an alias";*/
10053#if ENABLE_HUSH_FUNCTIONS
10054 else if (find_function(*argv))
10055 type = "a function";
10056#endif
10057 else if (find_builtin(*argv))
10058 type = "a shell builtin";
10059 else if ((path = find_in_path(*argv)) != NULL)
10060 type = path;
10061 else {
10062 bb_error_msg("type: %s: not found", *argv);
10063 ret = EXIT_FAILURE;
10064 continue;
10065 }
10066
10067 printf("%s is %s\n", *argv, type);
10068 free(path);
10069 }
10070
10071 return ret;
10072}
10073#endif
10074
10075#if ENABLE_HUSH_READ
10076/* Interruptibility of read builtin in bash
10077 * (tested on bash-4.2.8 by sending signals (not by ^C)):
10078 *
10079 * Empty trap makes read ignore corresponding signal, for any signal.
10080 *
10081 * SIGINT:
10082 * - terminates non-interactive shell;
10083 * - interrupts read in interactive shell;
10084 * if it has non-empty trap:
10085 * - executes trap and returns to command prompt in interactive shell;
10086 * - executes trap and returns to read in non-interactive shell;
10087 * SIGTERM:
10088 * - is ignored (does not interrupt) read in interactive shell;
10089 * - terminates non-interactive shell;
10090 * if it has non-empty trap:
10091 * - executes trap and returns to read;
10092 * SIGHUP:
10093 * - terminates shell (regardless of interactivity);
10094 * if it has non-empty trap:
10095 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +020010096 * SIGCHLD from children:
10097 * - does not interrupt read regardless of interactivity:
10098 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010099 */
10100static int FAST_FUNC builtin_read(char **argv)
10101{
10102 const char *r;
10103 char *opt_n = NULL;
10104 char *opt_p = NULL;
10105 char *opt_t = NULL;
10106 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010107 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010108 const char *ifs;
10109 int read_flags;
10110
10111 /* "!": do not abort on errors.
10112 * Option string must start with "sr" to match BUILTIN_READ_xxx
10113 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010114 read_flags = getopt32(argv,
10115#if BASH_READ_D
10116 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
10117#else
10118 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
10119#endif
10120 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010121 if (read_flags == (uint32_t)-1)
10122 return EXIT_FAILURE;
10123 argv += optind;
10124 ifs = get_local_var_value("IFS"); /* can be NULL */
10125
10126 again:
10127 r = shell_builtin_read(set_local_var_from_halves,
10128 argv,
10129 ifs,
10130 read_flags,
10131 opt_n,
10132 opt_p,
10133 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +020010134 opt_u,
10135 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010136 );
10137
10138 if ((uintptr_t)r == 1 && errno == EINTR) {
10139 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +020010140 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010141 goto again;
10142 }
10143
10144 if ((uintptr_t)r > 1) {
10145 bb_error_msg("%s", r);
10146 r = (char*)(uintptr_t)1;
10147 }
10148
10149 return (uintptr_t)r;
10150}
10151#endif
10152
10153#if ENABLE_HUSH_UMASK
10154static int FAST_FUNC builtin_umask(char **argv)
10155{
10156 int rc;
10157 mode_t mask;
10158
10159 rc = 1;
10160 mask = umask(0);
10161 argv = skip_dash_dash(argv);
10162 if (argv[0]) {
10163 mode_t old_mask = mask;
10164
10165 /* numeric umasks are taken as-is */
10166 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
10167 if (!isdigit(argv[0][0]))
10168 mask ^= 0777;
10169 mask = bb_parse_mode(argv[0], mask);
10170 if (!isdigit(argv[0][0]))
10171 mask ^= 0777;
10172 if ((unsigned)mask > 0777) {
10173 mask = old_mask;
10174 /* bash messages:
10175 * bash: umask: 'q': invalid symbolic mode operator
10176 * bash: umask: 999: octal number out of range
10177 */
10178 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
10179 rc = 0;
10180 }
10181 } else {
10182 /* Mimic bash */
10183 printf("%04o\n", (unsigned) mask);
10184 /* fall through and restore mask which we set to 0 */
10185 }
10186 umask(mask);
10187
10188 return !rc; /* rc != 0 - success */
10189}
10190#endif
10191
Denys Vlasenko41ade052017-01-08 18:56:24 +010010192#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010193static void print_escaped(const char *s)
10194{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010195 if (*s == '\'')
10196 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010197 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010198 const char *p = strchrnul(s, '\'');
10199 /* print 'xxxx', possibly just '' */
10200 printf("'%.*s'", (int)(p - s), s);
10201 if (*p == '\0')
10202 break;
10203 s = p;
10204 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010205 /* s points to '; print "'''...'''" */
10206 putchar('"');
10207 do putchar('\''); while (*++s == '\'');
10208 putchar('"');
10209 } while (*s);
10210}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010211#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010212
Denys Vlasenko1e660422017-07-17 21:10:50 +020010213#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010214static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010215{
10216 do {
10217 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010218 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010219
10220 /* So far we do not check that name is valid (TODO?) */
10221
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010222 if (*name_end == '\0') {
10223 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010224
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010225 vpp = get_ptr_to_local_var(name, name_end - name);
10226 var = vpp ? *vpp : NULL;
10227
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010228 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010229 /* export -n NAME (without =VALUE) */
10230 if (var) {
10231 var->flg_export = 0;
10232 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10233 unsetenv(name);
10234 } /* else: export -n NOT_EXISTING_VAR: no-op */
10235 continue;
10236 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010237 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010238 /* export NAME (without =VALUE) */
10239 if (var) {
10240 var->flg_export = 1;
10241 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10242 putenv(var->varstr);
10243 continue;
10244 }
10245 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010246 if (flags & SETFLAG_MAKE_RO) {
10247 /* readonly NAME (without =VALUE) */
10248 if (var) {
10249 var->flg_read_only = 1;
10250 continue;
10251 }
10252 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010253# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010254 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010255 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010256 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10257 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010258 /* "local x=abc; ...; local x" - ignore second local decl */
10259 continue;
10260 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010261 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010262# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010263 /* Exporting non-existing variable.
10264 * bash does not put it in environment,
10265 * but remembers that it is exported,
10266 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010267 * We just set it to "" and export.
10268 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010269 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010270 * bash sets the value to "".
10271 */
10272 /* Or, it's "readonly NAME" (without =VALUE).
10273 * bash remembers NAME and disallows its creation
10274 * in the future.
10275 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010276 name = xasprintf("%s=", name);
10277 } else {
10278 /* (Un)exporting/making local NAME=VALUE */
10279 name = xstrdup(name);
10280 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010281 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010282 if (set_local_var(name, flags))
10283 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010284 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010285 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010286}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010287#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010288
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010289#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010290static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010291{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010292 unsigned opt_unexport;
10293
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010294#if ENABLE_HUSH_EXPORT_N
10295 /* "!": do not abort on errors */
10296 opt_unexport = getopt32(argv, "!n");
10297 if (opt_unexport == (uint32_t)-1)
10298 return EXIT_FAILURE;
10299 argv += optind;
10300#else
10301 opt_unexport = 0;
10302 argv++;
10303#endif
10304
10305 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010306 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010307 if (e) {
10308 while (*e) {
10309#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010310 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010311#else
10312 /* ash emits: export VAR='VAL'
10313 * bash: declare -x VAR="VAL"
10314 * we follow ash example */
10315 const char *s = *e++;
10316 const char *p = strchr(s, '=');
10317
10318 if (!p) /* wtf? take next variable */
10319 continue;
10320 /* export var= */
10321 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010322 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010323 putchar('\n');
10324#endif
10325 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010326 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010327 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010328 return EXIT_SUCCESS;
10329 }
10330
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010331 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010332}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010333#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010334
Denys Vlasenko295fef82009-06-03 12:47:26 +020010335#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010336static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010337{
10338 if (G.func_nest_level == 0) {
10339 bb_error_msg("%s: not in a function", argv[0]);
10340 return EXIT_FAILURE; /* bash compat */
10341 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010342 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010343 /* Since all builtins run in a nested variable level,
10344 * need to use level - 1 here. Or else the variable will be removed at once
10345 * after builtin returns.
10346 */
10347 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010348}
10349#endif
10350
Denys Vlasenko1e660422017-07-17 21:10:50 +020010351#if ENABLE_HUSH_READONLY
10352static int FAST_FUNC builtin_readonly(char **argv)
10353{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010354 argv++;
10355 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010356 /* bash: readonly [-p]: list all readonly VARs
10357 * (-p has no effect in bash)
10358 */
10359 struct variable *e;
10360 for (e = G.top_var; e; e = e->next) {
10361 if (e->flg_read_only) {
10362//TODO: quote value: readonly VAR='VAL'
10363 printf("readonly %s\n", e->varstr);
10364 }
10365 }
10366 return EXIT_SUCCESS;
10367 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010368 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010369}
10370#endif
10371
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010372#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010373/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10374static int FAST_FUNC builtin_unset(char **argv)
10375{
10376 int ret;
10377 unsigned opts;
10378
10379 /* "!": do not abort on errors */
10380 /* "+": stop at 1st non-option */
10381 opts = getopt32(argv, "!+vf");
10382 if (opts == (unsigned)-1)
10383 return EXIT_FAILURE;
10384 if (opts == 3) {
10385 bb_error_msg("unset: -v and -f are exclusive");
10386 return EXIT_FAILURE;
10387 }
10388 argv += optind;
10389
10390 ret = EXIT_SUCCESS;
10391 while (*argv) {
10392 if (!(opts & 2)) { /* not -f */
10393 if (unset_local_var(*argv)) {
10394 /* unset <nonexistent_var> doesn't fail.
10395 * Error is when one tries to unset RO var.
10396 * Message was printed by unset_local_var. */
10397 ret = EXIT_FAILURE;
10398 }
10399 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010400# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010401 else {
10402 unset_func(*argv);
10403 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010404# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010405 argv++;
10406 }
10407 return ret;
10408}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010409#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010410
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010411#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010412/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10413 * built-in 'set' handler
10414 * SUSv3 says:
10415 * set [-abCefhmnuvx] [-o option] [argument...]
10416 * set [+abCefhmnuvx] [+o option] [argument...]
10417 * set -- [argument...]
10418 * set -o
10419 * set +o
10420 * Implementations shall support the options in both their hyphen and
10421 * plus-sign forms. These options can also be specified as options to sh.
10422 * Examples:
10423 * Write out all variables and their values: set
10424 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10425 * Turn on the -x and -v options: set -xv
10426 * Unset all positional parameters: set --
10427 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10428 * Set the positional parameters to the expansion of x, even if x expands
10429 * with a leading '-' or '+': set -- $x
10430 *
10431 * So far, we only support "set -- [argument...]" and some of the short names.
10432 */
10433static int FAST_FUNC builtin_set(char **argv)
10434{
10435 int n;
10436 char **pp, **g_argv;
10437 char *arg = *++argv;
10438
10439 if (arg == NULL) {
10440 struct variable *e;
10441 for (e = G.top_var; e; e = e->next)
10442 puts(e->varstr);
10443 return EXIT_SUCCESS;
10444 }
10445
10446 do {
10447 if (strcmp(arg, "--") == 0) {
10448 ++argv;
10449 goto set_argv;
10450 }
10451 if (arg[0] != '+' && arg[0] != '-')
10452 break;
10453 for (n = 1; arg[n]; ++n) {
10454 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10455 goto error;
10456 if (arg[n] == 'o' && argv[1])
10457 argv++;
10458 }
10459 } while ((arg = *++argv) != NULL);
10460 /* Now argv[0] is 1st argument */
10461
10462 if (arg == NULL)
10463 return EXIT_SUCCESS;
10464 set_argv:
10465
10466 /* NB: G.global_argv[0] ($0) is never freed/changed */
10467 g_argv = G.global_argv;
10468 if (G.global_args_malloced) {
10469 pp = g_argv;
10470 while (*++pp)
10471 free(*pp);
10472 g_argv[1] = NULL;
10473 } else {
10474 G.global_args_malloced = 1;
10475 pp = xzalloc(sizeof(pp[0]) * 2);
10476 pp[0] = g_argv[0]; /* retain $0 */
10477 g_argv = pp;
10478 }
10479 /* This realloc's G.global_argv */
10480 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10481
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010482 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010483
10484 return EXIT_SUCCESS;
10485
10486 /* Nothing known, so abort */
10487 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010488 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010489 return EXIT_FAILURE;
10490}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010491#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010492
10493static int FAST_FUNC builtin_shift(char **argv)
10494{
10495 int n = 1;
10496 argv = skip_dash_dash(argv);
10497 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010498 n = bb_strtou(argv[0], NULL, 10);
10499 if (errno || n < 0) {
10500 /* shared string with ash.c */
10501 bb_error_msg("Illegal number: %s", argv[0]);
10502 /*
10503 * ash aborts in this case.
10504 * bash prints error message and set $? to 1.
10505 * Interestingly, for "shift 99999" bash does not
10506 * print error message, but does set $? to 1
10507 * (and does no shifting at all).
10508 */
10509 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010510 }
10511 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010512 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010513 int m = 1;
10514 while (m <= n)
10515 free(G.global_argv[m++]);
10516 }
10517 G.global_argc -= n;
10518 memmove(&G.global_argv[1], &G.global_argv[n+1],
10519 G.global_argc * sizeof(G.global_argv[0]));
10520 return EXIT_SUCCESS;
10521 }
10522 return EXIT_FAILURE;
10523}
10524
Denys Vlasenko74d40582017-08-11 01:32:46 +020010525#if ENABLE_HUSH_GETOPTS
10526static int FAST_FUNC builtin_getopts(char **argv)
10527{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010528/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10529
Denys Vlasenko74d40582017-08-11 01:32:46 +020010530TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010531If a required argument is not found, and getopts is not silent,
10532a question mark (?) is placed in VAR, OPTARG is unset, and a
10533diagnostic message is printed. If getopts is silent, then a
10534colon (:) is placed in VAR and OPTARG is set to the option
10535character found.
10536
10537Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010538
10539"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010540*/
10541 char cbuf[2];
10542 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010543 int c, n, exitcode, my_opterr;
10544 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010545
10546 optstring = *++argv;
10547 if (!optstring || !(var = *++argv)) {
10548 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10549 return EXIT_FAILURE;
10550 }
10551
Denys Vlasenko238ff982017-08-29 13:38:30 +020010552 if (argv[1])
10553 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10554 else
10555 argv = G.global_argv;
10556 cbuf[1] = '\0';
10557
10558 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010559 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010560 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010561 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010562 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010563 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010564
10565 /* getopts stops on first non-option. Add "+" to force that */
10566 /*if (optstring[0] != '+')*/ {
10567 char *s = alloca(strlen(optstring) + 2);
10568 sprintf(s, "+%s", optstring);
10569 optstring = s;
10570 }
10571
Denys Vlasenko238ff982017-08-29 13:38:30 +020010572 /* Naively, now we should just
10573 * cp = get_local_var_value("OPTIND");
10574 * optind = cp ? atoi(cp) : 0;
10575 * optarg = NULL;
10576 * opterr = my_opterr;
10577 * c = getopt(string_array_len(argv), argv, optstring);
10578 * and be done? Not so fast...
10579 * Unlike normal getopt() usage in C programs, here
10580 * each successive call will (usually) have the same argv[] CONTENTS,
10581 * but not the ADDRESSES. Worse yet, it's possible that between
10582 * invocations of "getopts", there will be calls to shell builtins
10583 * which use getopt() internally. Example:
10584 * while getopts "abc" RES -a -bc -abc de; do
10585 * unset -ff func
10586 * done
10587 * This would not work correctly: getopt() call inside "unset"
10588 * modifies internal libc state which is tracking position in
10589 * multi-option strings ("-abc"). At best, it can skip options
10590 * or return the same option infinitely. With glibc implementation
10591 * of getopt(), it would use outright invalid pointers and return
10592 * garbage even _without_ "unset" mangling internal state.
10593 *
10594 * We resort to resetting getopt() state and calling it N times,
10595 * until we get Nth result (or failure).
10596 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10597 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010598 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010599 count = 0;
10600 n = string_array_len(argv);
10601 do {
10602 optarg = NULL;
10603 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10604 c = getopt(n, argv, optstring);
10605 if (c < 0)
10606 break;
10607 count++;
10608 } while (count <= G.getopt_count);
10609
10610 /* Set OPTIND. Prevent resetting of the magic counter! */
10611 set_local_var_from_halves("OPTIND", utoa(optind));
10612 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010613 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010614
10615 /* Set OPTARG */
10616 /* Always set or unset, never left as-is, even on exit/error:
10617 * "If no option was found, or if the option that was found
10618 * does not have an option-argument, OPTARG shall be unset."
10619 */
10620 cp = optarg;
10621 if (c == '?') {
10622 /* If ":optstring" and unknown option is seen,
10623 * it is stored to OPTARG.
10624 */
10625 if (optstring[1] == ':') {
10626 cbuf[0] = optopt;
10627 cp = cbuf;
10628 }
10629 }
10630 if (cp)
10631 set_local_var_from_halves("OPTARG", cp);
10632 else
10633 unset_local_var("OPTARG");
10634
10635 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010636 exitcode = EXIT_SUCCESS;
10637 if (c < 0) { /* -1: end of options */
10638 exitcode = EXIT_FAILURE;
10639 c = '?';
10640 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010641
Denys Vlasenko238ff982017-08-29 13:38:30 +020010642 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010643 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010644 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010645
Denys Vlasenko74d40582017-08-11 01:32:46 +020010646 return exitcode;
10647}
10648#endif
10649
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010650static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010651{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010652 char *arg_path, *filename;
10653 FILE *input;
10654 save_arg_t sv;
10655 char *args_need_save;
10656#if ENABLE_HUSH_FUNCTIONS
10657 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010658#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010659
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010660 argv = skip_dash_dash(argv);
10661 filename = argv[0];
10662 if (!filename) {
10663 /* bash says: "bash: .: filename argument required" */
10664 return 2; /* bash compat */
10665 }
10666 arg_path = NULL;
10667 if (!strchr(filename, '/')) {
10668 arg_path = find_in_path(filename);
10669 if (arg_path)
10670 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010671 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010672 errno = ENOENT;
10673 bb_simple_perror_msg(filename);
10674 return EXIT_FAILURE;
10675 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010676 }
10677 input = remember_FILE(fopen_or_warn(filename, "r"));
10678 free(arg_path);
10679 if (!input) {
10680 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10681 /* POSIX: non-interactive shell should abort here,
10682 * not merely fail. So far no one complained :)
10683 */
10684 return EXIT_FAILURE;
10685 }
10686
10687#if ENABLE_HUSH_FUNCTIONS
10688 sv_flg = G_flag_return_in_progress;
10689 /* "we are inside sourced file, ok to use return" */
10690 G_flag_return_in_progress = -1;
10691#endif
10692 args_need_save = argv[1]; /* used as a boolean variable */
10693 if (args_need_save)
10694 save_and_replace_G_args(&sv, argv);
10695
10696 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10697 G.last_exitcode = 0;
10698 parse_and_run_file(input);
10699 fclose_and_forget(input);
10700
10701 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10702 restore_G_args(&sv, argv);
10703#if ENABLE_HUSH_FUNCTIONS
10704 G_flag_return_in_progress = sv_flg;
10705#endif
10706
10707 return G.last_exitcode;
10708}
10709
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010710#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010711static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010712{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010713 int sig;
10714 char *new_cmd;
10715
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010716 if (!G_traps)
10717 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010718
10719 argv++;
10720 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010721 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010722 /* No args: print all trapped */
10723 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010724 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010725 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010726 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010727 /* note: bash adds "SIG", but only if invoked
10728 * as "bash". If called as "sh", or if set -o posix,
10729 * then it prints short signal names.
10730 * We are printing short names: */
10731 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010732 }
10733 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010734 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010735 return EXIT_SUCCESS;
10736 }
10737
10738 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010739 /* If first arg is a number: reset all specified signals */
10740 sig = bb_strtou(*argv, NULL, 10);
10741 if (errno == 0) {
10742 int ret;
10743 process_sig_list:
10744 ret = EXIT_SUCCESS;
10745 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010746 sighandler_t handler;
10747
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010748 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010749 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010750 ret = EXIT_FAILURE;
10751 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010752 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010753 continue;
10754 }
10755
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010756 free(G_traps[sig]);
10757 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010758
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010759 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010760 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010761
10762 /* There is no signal for 0 (EXIT) */
10763 if (sig == 0)
10764 continue;
10765
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010766 if (new_cmd)
10767 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10768 else
10769 /* We are removing trap handler */
10770 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010771 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010772 }
10773 return ret;
10774 }
10775
10776 if (!argv[1]) { /* no second arg */
10777 bb_error_msg("trap: invalid arguments");
10778 return EXIT_FAILURE;
10779 }
10780
10781 /* First arg is "-": reset all specified to default */
10782 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10783 /* Everything else: set arg as signal handler
10784 * (includes "" case, which ignores signal) */
10785 if (argv[0][0] == '-') {
10786 if (argv[0][1] == '\0') { /* "-" */
10787 /* new_cmd remains NULL: "reset these sigs" */
10788 goto reset_traps;
10789 }
10790 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10791 argv++;
10792 }
10793 /* else: "-something", no special meaning */
10794 }
10795 new_cmd = *argv;
10796 reset_traps:
10797 argv++;
10798 goto process_sig_list;
10799}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010800#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010801
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010802#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010803static struct pipe *parse_jobspec(const char *str)
10804{
10805 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010806 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010807
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010808 if (sscanf(str, "%%%u", &jobnum) != 1) {
10809 if (str[0] != '%'
10810 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10811 ) {
10812 bb_error_msg("bad argument '%s'", str);
10813 return NULL;
10814 }
10815 /* It is "%%", "%+" or "%" - current job */
10816 jobnum = G.last_jobid;
10817 if (jobnum == 0) {
10818 bb_error_msg("no current job");
10819 return NULL;
10820 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010821 }
10822 for (pi = G.job_list; pi; pi = pi->next) {
10823 if (pi->jobid == jobnum) {
10824 return pi;
10825 }
10826 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010827 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010828 return NULL;
10829}
10830
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010831static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10832{
10833 struct pipe *job;
10834 const char *status_string;
10835
10836 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10837 for (job = G.job_list; job; job = job->next) {
10838 if (job->alive_cmds == job->stopped_cmds)
10839 status_string = "Stopped";
10840 else
10841 status_string = "Running";
10842
10843 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10844 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010845
10846 clean_up_last_dead_job();
10847
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010848 return EXIT_SUCCESS;
10849}
10850
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010851/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010852static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010853{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010854 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010855 struct pipe *pi;
10856
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010857 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010858 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010859
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010860 /* If they gave us no args, assume they want the last backgrounded task */
10861 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010862 for (pi = G.job_list; pi; pi = pi->next) {
10863 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010864 goto found;
10865 }
10866 }
10867 bb_error_msg("%s: no current job", argv[0]);
10868 return EXIT_FAILURE;
10869 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010870
10871 pi = parse_jobspec(argv[1]);
10872 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010873 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010874 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010875 /* TODO: bash prints a string representation
10876 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010877 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010878 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010879 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010880 }
10881
10882 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010883 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10884 for (i = 0; i < pi->num_cmds; i++) {
10885 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010886 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010887 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010888
10889 i = kill(- pi->pgrp, SIGCONT);
10890 if (i < 0) {
10891 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010892 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010893 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010894 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010895 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010896 }
10897
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010898 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010899 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010900 return checkjobs_and_fg_shell(pi);
10901 }
10902 return EXIT_SUCCESS;
10903}
10904#endif
10905
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010906#if ENABLE_HUSH_KILL
10907static int FAST_FUNC builtin_kill(char **argv)
10908{
10909 int ret = 0;
10910
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010911# if ENABLE_HUSH_JOB
10912 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10913 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010914
10915 do {
10916 struct pipe *pi;
10917 char *dst;
10918 int j, n;
10919
10920 if (argv[i][0] != '%')
10921 continue;
10922 /*
10923 * "kill %N" - job kill
10924 * Converting to pgrp / pid kill
10925 */
10926 pi = parse_jobspec(argv[i]);
10927 if (!pi) {
10928 /* Eat bad jobspec */
10929 j = i;
10930 do {
10931 j++;
10932 argv[j - 1] = argv[j];
10933 } while (argv[j]);
10934 ret = 1;
10935 i--;
10936 continue;
10937 }
10938 /*
10939 * In jobs started under job control, we signal
10940 * entire process group by kill -PGRP_ID.
10941 * This happens, f.e., in interactive shell.
10942 *
10943 * Otherwise, we signal each child via
10944 * kill PID1 PID2 PID3.
10945 * Testcases:
10946 * sh -c 'sleep 1|sleep 1 & kill %1'
10947 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10948 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10949 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010950 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010951 dst = alloca(n * sizeof(int)*4);
10952 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010953 if (G_interactive_fd)
10954 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010955 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010956 struct command *cmd = &pi->cmds[j];
10957 /* Skip exited members of the job */
10958 if (cmd->pid == 0)
10959 continue;
10960 /*
10961 * kill_main has matching code to expect
10962 * leading space. Needed to not confuse
10963 * negative pids with "kill -SIGNAL_NO" syntax
10964 */
10965 dst += sprintf(dst, " %u", (int)cmd->pid);
10966 }
10967 *dst = '\0';
10968 } while (argv[++i]);
10969 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010970# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010971
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010972 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010973 ret = run_applet_main(argv, kill_main);
10974 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010975 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010976 return ret;
10977}
10978#endif
10979
10980#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010981/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010982#if !ENABLE_HUSH_JOB
10983# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10984#endif
10985static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010986{
10987 int ret = 0;
10988 for (;;) {
10989 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010990 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010991
Denys Vlasenko830ea352016-11-08 04:59:11 +010010992 if (!sigisemptyset(&G.pending_set))
10993 goto check_sig;
10994
Denys Vlasenko7e675362016-10-28 21:57:31 +020010995 /* waitpid is not interruptible by SA_RESTARTed
10996 * signals which we use. Thus, this ugly dance:
10997 */
10998
10999 /* Make sure possible SIGCHLD is stored in kernel's
11000 * pending signal mask before we call waitpid.
11001 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011002 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020011003 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011004 sigfillset(&oldset); /* block all signals, remember old set */
11005 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011006
11007 if (!sigisemptyset(&G.pending_set)) {
11008 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011009 goto restore;
11010 }
11011
11012 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011013/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011014 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011015 debug_printf_exec("checkjobs:%d\n", ret);
11016#if ENABLE_HUSH_JOB
11017 if (waitfor_pipe) {
11018 int rcode = job_exited_or_stopped(waitfor_pipe);
11019 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
11020 if (rcode >= 0) {
11021 ret = rcode;
11022 sigprocmask(SIG_SETMASK, &oldset, NULL);
11023 break;
11024 }
11025 }
11026#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020011027 /* if ECHILD, there are no children (ret is -1 or 0) */
11028 /* if ret == 0, no children changed state */
11029 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011030 if (errno == ECHILD || ret) {
11031 ret--;
11032 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011033 ret = 0;
11034 sigprocmask(SIG_SETMASK, &oldset, NULL);
11035 break;
11036 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011037 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011038 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
11039 /* Note: sigsuspend invokes signal handler */
11040 sigsuspend(&oldset);
11041 restore:
11042 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010011043 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020011044 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011045 sig = check_and_run_traps();
11046 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020011047 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020011048 ret = 128 + sig;
11049 break;
11050 }
11051 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
11052 }
11053 return ret;
11054}
11055
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011056static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000011057{
Denys Vlasenko7e675362016-10-28 21:57:31 +020011058 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020011059 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000011060
Denys Vlasenkob131cce2010-05-20 03:39:43 +020011061 argv = skip_dash_dash(argv);
11062 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011063 /* Don't care about wait results */
11064 /* Note 1: must wait until there are no more children */
11065 /* Note 2: must be interruptible */
11066 /* Examples:
11067 * $ sleep 3 & sleep 6 & wait
11068 * [1] 30934 sleep 3
11069 * [2] 30935 sleep 6
11070 * [1] Done sleep 3
11071 * [2] Done sleep 6
11072 * $ sleep 3 & sleep 6 & wait
11073 * [1] 30936 sleep 3
11074 * [2] 30937 sleep 6
11075 * [1] Done sleep 3
11076 * ^C <-- after ~4 sec from keyboard
11077 * $
11078 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011079 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000011080 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000011081
Denys Vlasenko7e675362016-10-28 21:57:31 +020011082 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000011083 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011084 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011085#if ENABLE_HUSH_JOB
11086 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011087 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011088 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011089 wait_pipe = parse_jobspec(*argv);
11090 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011091 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011092 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010011093 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020011094 } else {
11095 /* waiting on "last dead job" removes it */
11096 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020011097 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011098 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010011099 /* else: parse_jobspec() already emitted error msg */
11100 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010011101 }
11102#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000011103 /* mimic bash message */
11104 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011105 ret = EXIT_FAILURE;
11106 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000011107 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010011108
Denys Vlasenko7e675362016-10-28 21:57:31 +020011109 /* Do we have such child? */
11110 ret = waitpid(pid, &status, WNOHANG);
11111 if (ret < 0) {
11112 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011113 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020011114 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020011115 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011116 /* "wait $!" but last bg task has already exited. Try:
11117 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
11118 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011119 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011120 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020011121 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010011122 } else {
11123 /* Example: "wait 1". mimic bash message */
11124 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011125 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020011126 } else {
11127 /* ??? */
11128 bb_perror_msg("wait %s", *argv);
11129 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011130 continue; /* bash checks all argv[] */
11131 }
11132 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020011133 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011134 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020011135 } else {
11136 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010011137 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020011138 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011139 if (WIFSIGNALED(status))
11140 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011141 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020011142 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000011143
11144 return ret;
11145}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010011146#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000011147
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011148#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
11149static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
11150{
11151 if (argv[1]) {
11152 def = bb_strtou(argv[1], NULL, 10);
11153 if (errno || def < def_min || argv[2]) {
11154 bb_error_msg("%s: bad arguments", argv[0]);
11155 def = UINT_MAX;
11156 }
11157 }
11158 return def;
11159}
11160#endif
11161
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011162#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011163static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011164{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011165 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000011166 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011167 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020011168 /* if we came from builtin_continue(), need to undo "= 1" */
11169 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000011170 return EXIT_SUCCESS; /* bash compat */
11171 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020011172 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011173
11174 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
11175 if (depth == UINT_MAX)
11176 G.flag_break_continue = BC_BREAK;
11177 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000011178 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011179
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011180 return EXIT_SUCCESS;
11181}
11182
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011183static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011184{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000011185 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
11186 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000011187}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000011188#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011189
11190#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011191static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011192{
11193 int rc;
11194
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011195 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011196 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11197 return EXIT_FAILURE; /* bash compat */
11198 }
11199
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011200 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011201
11202 /* bash:
11203 * out of range: wraps around at 256, does not error out
11204 * non-numeric param:
11205 * f() { false; return qwe; }; f; echo $?
11206 * bash: return: qwe: numeric argument required <== we do this
11207 * 255 <== we also do this
11208 */
11209 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11210 return rc;
11211}
11212#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011213
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011214#if ENABLE_HUSH_TIMES
11215static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11216{
11217 static const uint8_t times_tbl[] ALIGN1 = {
11218 ' ', offsetof(struct tms, tms_utime),
11219 '\n', offsetof(struct tms, tms_stime),
11220 ' ', offsetof(struct tms, tms_cutime),
11221 '\n', offsetof(struct tms, tms_cstime),
11222 0
11223 };
11224 const uint8_t *p;
11225 unsigned clk_tck;
11226 struct tms buf;
11227
11228 clk_tck = bb_clk_tck();
11229
11230 times(&buf);
11231 p = times_tbl;
11232 do {
11233 unsigned sec, frac;
11234 unsigned long t;
11235 t = *(clock_t *)(((char *) &buf) + p[1]);
11236 sec = t / clk_tck;
11237 frac = t % clk_tck;
11238 printf("%um%u.%03us%c",
11239 sec / 60, sec % 60,
11240 (frac * 1000) / clk_tck,
11241 p[0]);
11242 p += 2;
11243 } while (*p);
11244
11245 return EXIT_SUCCESS;
11246}
11247#endif
11248
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011249#if ENABLE_HUSH_MEMLEAK
11250static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11251{
11252 void *p;
11253 unsigned long l;
11254
11255# ifdef M_TRIM_THRESHOLD
11256 /* Optional. Reduces probability of false positives */
11257 malloc_trim(0);
11258# endif
11259 /* Crude attempt to find where "free memory" starts,
11260 * sans fragmentation. */
11261 p = malloc(240);
11262 l = (unsigned long)p;
11263 free(p);
11264 p = malloc(3400);
11265 if (l < (unsigned long)p) l = (unsigned long)p;
11266 free(p);
11267
11268
11269# if 0 /* debug */
11270 {
11271 struct mallinfo mi = mallinfo();
11272 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11273 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11274 }
11275# endif
11276
11277 if (!G.memleak_value)
11278 G.memleak_value = l;
11279
11280 l -= G.memleak_value;
11281 if ((long)l < 0)
11282 l = 0;
11283 l /= 1024;
11284 if (l > 127)
11285 l = 127;
11286
11287 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11288 return l;
11289}
11290#endif