blob: 735fbef27621057497da73e1359cbb8f41b4a096 [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"
478#define SPECIAL_VAR_SYMBOL 3
479/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
480#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000481
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200482struct variable;
483
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000484static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
485
486/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000487 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000488 */
489#if !BB_MMU
490typedef struct nommu_save_t {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200491 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000492 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000493 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000494} nommu_save_t;
495#endif
496
Denys Vlasenko9b782552010-09-08 13:33:26 +0200497enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000498 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000499#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000500 RES_IF ,
501 RES_THEN ,
502 RES_ELIF ,
503 RES_ELSE ,
504 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000505#endif
506#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000507 RES_FOR ,
508 RES_WHILE ,
509 RES_UNTIL ,
510 RES_DO ,
511 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000512#endif
513#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000514 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000515#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000516#if ENABLE_HUSH_CASE
517 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200518 /* three pseudo-keywords support contrived "case" syntax: */
519 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
520 RES_MATCH , /* "word)" */
521 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000522 RES_ESAC ,
523#endif
524 RES_XXXX ,
525 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200526};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000527
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000528typedef struct o_string {
529 char *data;
530 int length; /* position where data is appended */
531 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200532 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000533 /* At least some part of the string was inside '' or "",
534 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200535 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000536 smallint has_empty_slot;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000537} o_string;
538enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200539 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
540 EXP_FLAG_GLOB = 0x2,
541 /* Protect newly added chars against globbing
542 * by prepending \ to *, ?, [, \ */
543 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
544};
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000545/* Used for initialization: o_string foo = NULL_O_STRING; */
546#define NULL_O_STRING { NULL }
547
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200548#ifndef debug_printf_parse
549static const char *const assignment_flag[] = {
550 "MAYBE_ASSIGNMENT",
551 "DEFINITELY_ASSIGNMENT",
552 "NOT_ASSIGNMENT",
553 "WORD_IS_KEYWORD",
554};
555#endif
556
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000557typedef struct in_str {
558 const char *p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200559 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200560 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000561 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000562} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200564/* The descrip member of this structure is only used to make
565 * debugging output pretty */
566static const struct {
567 int mode;
568 signed char default_fd;
569 char descrip[3];
570} redir_table[] = {
571 { O_RDONLY, 0, "<" },
572 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
573 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
574 { O_CREAT|O_RDWR, 1, "<>" },
575 { O_RDONLY, 0, "<<" },
576/* Should not be needed. Bogus default_fd helps in debugging */
577/* { O_RDONLY, 77, "<<" }, */
578};
579
Eric Andersen25f27032001-04-26 23:22:31 +0000580struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000581 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000582 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000583 int rd_fd; /* fd to redirect */
584 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
585 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000586 smallint rd_type; /* (enum redir_type) */
587 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000588 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200589 * bit 0: do we need to trim leading tabs?
590 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000591 */
Eric Andersen25f27032001-04-26 23:22:31 +0000592};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000593typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200594 REDIRECT_INPUT = 0,
595 REDIRECT_OVERWRITE = 1,
596 REDIRECT_APPEND = 2,
597 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000598 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200599 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000600
601 REDIRFD_CLOSE = -3,
602 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000603 REDIRFD_TO_FILE = -1,
604 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000605
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000606 HEREDOC_SKIPTABS = 1,
607 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000608} redir_type;
609
Eric Andersen25f27032001-04-26 23:22:31 +0000610
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000611struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000612 pid_t pid; /* 0 if exited */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +0200613 unsigned assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100614#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100615 unsigned lineno;
616#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200617 smallint cmd_type; /* CMD_xxx */
618#define CMD_NORMAL 0
619#define CMD_SUBSHELL 1
Denys Vlasenko11752d42018-04-03 08:20:58 +0200620#if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
621/* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
622 * "export v=t*"
623 */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200624# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000625#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200626#if ENABLE_HUSH_FUNCTIONS
627# define CMD_FUNCDEF 3
628#endif
629
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100630 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200631 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
632 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000633#if !BB_MMU
634 char *group_as_string;
635#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000636#if ENABLE_HUSH_FUNCTIONS
637 struct function *child_func;
638/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200639 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000640 * When we execute "f1() {a;}" cmd, we create new function and clear
641 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200642 * When we execute "f1() {b;}", we notice that f1 exists,
643 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000644 * we put those fields back into cmd->xxx
645 * (struct function has ->parent_cmd ptr to facilitate that).
646 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
647 * Without this trick, loop would execute a;b;b;b;...
648 * instead of correct sequence a;b;a;b;...
649 * When command is freed, it severs the link
650 * (sets ->child_func->parent_cmd to NULL).
651 */
652#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000653 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000654/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
655 * and on execution these are substituted with their values.
656 * Substitution can make _several_ words out of one argv[n]!
657 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000658 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000659 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660 struct redir_struct *redirects; /* I/O redirections */
661};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000662/* Is there anything in this command at all? */
663#define IS_NULL_CMD(cmd) \
664 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
665
Eric Andersen25f27032001-04-26 23:22:31 +0000666struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000667 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000668 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000669 int alive_cmds; /* number of commands running (not exited) */
670 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000671#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100672 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000673 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000674 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000675#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000676 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000677 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000678 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
679 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000680};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000681typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100682 PIPE_SEQ = 0,
683 PIPE_AND = 1,
684 PIPE_OR = 2,
685 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000686} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000687/* Is there anything in this pipe at all? */
688#define IS_NULL_PIPE(pi) \
689 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000690
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000691/* This holds pointers to the various results of parsing */
692struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000693 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000694 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000695 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000696 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000697 /* last command in pipe (being constructed right now) */
698 struct command *command;
699 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000700 struct redir_struct *pending_redirect;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200701 o_string word;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000702#if !BB_MMU
703 o_string as_string;
704#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200705 smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000706#if HAS_KEYWORDS
707 smallint ctx_res_w;
708 smallint ctx_inverted; /* "! cmd | cmd" */
709#if ENABLE_HUSH_CASE
710 smallint ctx_dsemicolon; /* ";;" seen */
711#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000712 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
713 int old_flag;
714 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000715 * example: "if pipe1; pipe2; then pipe3; fi"
716 * when we see "if" or "then", we malloc and copy current context,
717 * and make ->stack point to it. then we parse pipeN.
718 * when closing "then" / fi" / whatever is found,
719 * we move list_head into ->stack->command->group,
720 * copy ->stack into current context, and delete ->stack.
721 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000722 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000723 struct parse_context *stack;
724#endif
725};
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +0200726enum {
727 MAYBE_ASSIGNMENT = 0,
728 DEFINITELY_ASSIGNMENT = 1,
729 NOT_ASSIGNMENT = 2,
730 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
731 WORD_IS_KEYWORD = 3,
732};
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000733
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000734/* On program start, environ points to initial environment.
735 * putenv adds new pointers into it, unsetenv removes them.
736 * Neither of these (de)allocates the strings.
737 * setenv allocates new strings in malloc space and does putenv,
738 * and thus setenv is unusable (leaky) for shell's purposes */
739#define setenv(...) setenv_is_leaky_dont_use()
740struct variable {
741 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000742 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000743 int max_len; /* if > 0, name is part of initial env; else name is malloced */
Denys Vlasenko332e4112018-04-04 22:32:59 +0200744 uint16_t var_nest_level;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000745 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000746 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000747};
748
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000749enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000750 BC_BREAK = 1,
751 BC_CONTINUE = 2,
752};
753
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000754#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000755struct function {
756 struct function *next;
757 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000758 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000759 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200760# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000761 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200762# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000763};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000764#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000765
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000766
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100767/* set -/+o OPT support. (TODO: make it optional)
768 * bash supports the following opts:
769 * allexport off
770 * braceexpand on
771 * emacs on
772 * errexit off
773 * errtrace off
774 * functrace off
775 * hashall on
776 * histexpand off
777 * history on
778 * ignoreeof off
779 * interactive-comments on
780 * keyword off
781 * monitor on
782 * noclobber off
783 * noexec off
784 * noglob off
785 * nolog off
786 * notify off
787 * nounset off
788 * onecmd off
789 * physical off
790 * pipefail off
791 * posix off
792 * privileged off
793 * verbose off
794 * vi off
795 * xtrace off
796 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800797static const char o_opt_strings[] ALIGN1 =
798 "pipefail\0"
799 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200800 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800801#if ENABLE_HUSH_MODE_X
802 "xtrace\0"
803#endif
804 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100805enum {
806 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800807 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200808 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800809#if ENABLE_HUSH_MODE_X
810 OPT_O_XTRACE,
811#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100812 NUM_OPT_O
813};
814
815
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200816struct FILE_list {
817 struct FILE_list *next;
818 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200819 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200820};
821
822
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000823/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000824/* Sorted roughly by size (smaller offsets == smaller code) */
825struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000826 /* interactive_fd != 0 means we are an interactive shell.
827 * If we are, then saved_tty_pgrp can also be != 0, meaning
828 * that controlling tty is available. With saved_tty_pgrp == 0,
829 * job control still works, but terminal signals
830 * (^C, ^Z, ^Y, ^\) won't work at all, and background
831 * process groups can only be created with "cmd &".
832 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
833 * to give tty to the foreground process group,
834 * and will take it back when the group is stopped (^Z)
835 * or killed (^C).
836 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000837#if ENABLE_HUSH_INTERACTIVE
838 /* 'interactive_fd' is a fd# open to ctty, if we have one
839 * _AND_ if we decided to act interactively */
840 int interactive_fd;
841 const char *PS1;
Denys Vlasenkof5018da2018-04-06 17:58:21 +0200842 IF_FEATURE_EDITING_FANCY_PROMPT(const char *PS2;)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000843# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000844#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000845# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000846#endif
847#if ENABLE_FEATURE_EDITING
848 line_input_t *line_input_state;
849#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000850 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200851 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000852 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200853#if ENABLE_HUSH_RANDOM_SUPPORT
854 random_t random_gen;
855#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000856#if ENABLE_HUSH_JOB
857 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100858 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000859 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000860 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400861# define G_saved_tty_pgrp (G.saved_tty_pgrp)
862#else
863# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000864#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200865 /* How deeply are we in context where "set -e" is ignored */
866 int errexit_depth;
867 /* "set -e" rules (do we follow them correctly?):
868 * Exit if pipe, list, or compound command exits with a non-zero status.
869 * Shell does not exit if failed command is part of condition in
870 * if/while, part of && or || list except the last command, any command
871 * in a pipe but the last, or if the command's return value is being
872 * inverted with !. If a compound command other than a subshell returns a
873 * non-zero status because a command failed while -e was being ignored, the
874 * shell does not exit. A trap on ERR, if set, is executed before the shell
875 * exits [ERR is a bashism].
876 *
877 * If a compound command or function executes in a context where -e is
878 * ignored, none of the commands executed within are affected by the -e
879 * setting. If a compound command or function sets -e while executing in a
880 * context where -e is ignored, that setting does not have any effect until
881 * the compound command or the command containing the function call completes.
882 */
883
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100884 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100885#if ENABLE_HUSH_MODE_X
886# define G_x_mode (G.o_opt[OPT_O_XTRACE])
887#else
888# define G_x_mode 0
889#endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +0200890#if ENABLE_HUSH_INTERACTIVE
891 smallint promptmode; /* 0: PS1, 1: PS2 */
892#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000893 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000894#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000895 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000896#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000897#if ENABLE_HUSH_FUNCTIONS
898 /* 0: outside of a function (or sourced file)
899 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000900 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000901 */
902 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200903# define G_flag_return_in_progress (G.flag_return_in_progress)
904#else
905# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000906#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000907 smallint exiting; /* used to prevent EXIT trap recursion */
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200908 /* These support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000909 smalluint last_exitcode;
Denys Vlasenko5fa05052018-04-03 11:21:13 +0200910 smalluint expand_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200911 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100912#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000913 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000914 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100915# define G_global_args_malloced (G.global_args_malloced)
916#else
917# define G_global_args_malloced 0
918#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000919 /* how many non-NULL argv's we have. NB: $# + 1 */
920 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000921 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000922#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000923 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000924#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000925#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000926 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000927 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000928#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200929#if ENABLE_HUSH_GETOPTS
930 unsigned getopt_count;
931#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000932 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000933 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200934 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200935 char **expanded_assignments;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200936 struct variable **shadowed_vars_pp;
Denys Vlasenko332e4112018-04-04 22:32:59 +0200937 unsigned var_nest_level;
938#if ENABLE_HUSH_FUNCTIONS
939# if ENABLE_HUSH_LOCAL
940 unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200941# endif
Denys Vlasenko332e4112018-04-04 22:32:59 +0200942 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000943#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000944 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200945#if ENABLE_HUSH_FAST
946 unsigned count_SIGCHLD;
947 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200948 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200949#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100950#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100951 unsigned lineno;
952 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100953#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200954 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200955 /* Which signals have non-DFL handler (even with no traps set)?
956 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200957 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200958 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200959 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200960 * Other than these two times, never modified.
961 */
962 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200963#if ENABLE_HUSH_JOB
964 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100965# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200966#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200967# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200968#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100969#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000970 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100971# define G_traps G.traps
972#else
973# define G_traps ((char**)NULL)
974#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200975 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100976#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000977 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100978#endif
979#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000980 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000981#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200982 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200983#if ENABLE_FEATURE_EDITING
984 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
985#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000986};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000987#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000988/* Not #defining name to G.name - this quickly gets unwieldy
989 * (too many defines). Also, I actually prefer to see when a variable
990 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000991#define INIT_G() do { \
992 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200993 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
994 sigfillset(&G.sa.sa_mask); \
995 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000996} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000997
998
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000999/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001000static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001001#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001002static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001003#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001004static int builtin_eval(char **argv) FAST_FUNC;
1005static int builtin_exec(char **argv) FAST_FUNC;
1006static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001007#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001008static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001009#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001010#if ENABLE_HUSH_READONLY
1011static int builtin_readonly(char **argv) FAST_FUNC;
1012#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001013#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001014static int builtin_fg_bg(char **argv) FAST_FUNC;
1015static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001016#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001017#if ENABLE_HUSH_GETOPTS
1018static int builtin_getopts(char **argv) FAST_FUNC;
1019#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001020#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001021static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001022#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001023#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001024static int builtin_history(char **argv) FAST_FUNC;
1025#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001026#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001027static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001028#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001029#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001030static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001031#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001032#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001033static int builtin_printf(char **argv) FAST_FUNC;
1034#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001035static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001036#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001038#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001039#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001040static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001041#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001042static int builtin_shift(char **argv) FAST_FUNC;
1043static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001044#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001045static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001046#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001047#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001048static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001049#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001050#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001051static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001052#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001053#if ENABLE_HUSH_TIMES
1054static int builtin_times(char **argv) FAST_FUNC;
1055#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001056static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001057#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001058static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001059#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001060#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001061static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001062#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001063#if ENABLE_HUSH_KILL
1064static int builtin_kill(char **argv) FAST_FUNC;
1065#endif
1066#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001067static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001068#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001069#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001070static int builtin_break(char **argv) FAST_FUNC;
1071static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001072#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001073#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001074static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001075#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001076
1077/* Table of built-in functions. They can be forked or not, depending on
1078 * context: within pipes, they fork. As simple commands, they do not.
1079 * When used in non-forking context, they can change global variables
1080 * in the parent shell process. If forked, of course they cannot.
1081 * For example, 'unset foo | whatever' will parse and run, but foo will
1082 * still be set at the end. */
1083struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001084 const char *b_cmd;
1085 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001086#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001087 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001088# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001089#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001090# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001091#endif
1092};
1093
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001094static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001095 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001096 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001097#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001098 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001099#endif
1100#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001101 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001102#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001103 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001104#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001105 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001106#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001107 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1108 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001109 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001110#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001111 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001112#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001113#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001114 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001115#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001116#if ENABLE_HUSH_GETOPTS
1117 BLTIN("getopts" , builtin_getopts , NULL),
1118#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001119#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001120 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001121#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001122#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001123 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001124#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001125#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001126 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001127#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001128#if ENABLE_HUSH_KILL
1129 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1130#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001131#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001132 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001133#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001134#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001135 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001136#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001137#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001138 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001139#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001140#if ENABLE_HUSH_READONLY
1141 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1142#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001143#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001144 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001145#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001146#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001147 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001148#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001149 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001150#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001151 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001152#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001153#if ENABLE_HUSH_TIMES
1154 BLTIN("times" , builtin_times , NULL),
1155#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001156#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001157 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001158#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001159 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001160#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001161 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001162#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001163#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001164 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001165#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001166#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001167 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001168#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001169#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001171#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001172#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001173 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001174#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001175};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001176/* These builtins won't be used if we are on NOMMU and need to re-exec
1177 * (it's cheaper to run an external program in this case):
1178 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001179static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001180#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001181 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001182#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001183#if BASH_TEST2
1184 BLTIN("[[" , builtin_test , NULL),
1185#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001186#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001187 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001188#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001189#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001190 BLTIN("printf" , builtin_printf , NULL),
1191#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001192 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001193#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001194 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001195#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001196};
1197
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001198
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001199/* Debug printouts.
1200 */
1201#if HUSH_DEBUG
1202/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001203# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001204# define debug_enter() (G.debug_indent++)
1205# define debug_leave() (G.debug_indent--)
1206#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001207# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001208# define debug_enter() ((void)0)
1209# define debug_leave() ((void)0)
1210#endif
1211
1212#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001213# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001214#endif
1215
1216#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001217# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001218#endif
1219
1220#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001221#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001222#endif
1223
1224#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001225# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001226#endif
1227
1228#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001229# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001230# define DEBUG_JOBS 1
1231#else
1232# define DEBUG_JOBS 0
1233#endif
1234
1235#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001236# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001237# define DEBUG_EXPAND 1
1238#else
1239# define DEBUG_EXPAND 0
1240#endif
1241
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001242#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001243# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001244#endif
1245
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001246#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001247# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001248# define DEBUG_GLOB 1
1249#else
1250# define DEBUG_GLOB 0
1251#endif
1252
Denys Vlasenko2db74612017-07-07 22:07:28 +02001253#ifndef debug_printf_redir
1254# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1255#endif
1256
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001257#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001258# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001259#endif
1260
1261#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001262# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001263#endif
1264
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02001265#ifndef debug_printf_prompt
1266# define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
1267#endif
1268
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001269#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001270# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001271# define DEBUG_CLEAN 1
1272#else
1273# define DEBUG_CLEAN 0
1274#endif
1275
1276#if DEBUG_EXPAND
1277static void debug_print_strings(const char *prefix, char **vv)
1278{
1279 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001280 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001281 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001282 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001283}
1284#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001285# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001286#endif
1287
1288
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001289/* Leak hunting. Use hush_leaktool.sh for post-processing.
1290 */
1291#if LEAK_HUNTING
1292static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001293{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001294 void *ptr = xmalloc((size + 0xff) & ~0xff);
1295 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1296 return ptr;
1297}
1298static void *xxrealloc(int lineno, void *ptr, size_t size)
1299{
1300 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1301 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1302 return ptr;
1303}
1304static char *xxstrdup(int lineno, const char *str)
1305{
1306 char *ptr = xstrdup(str);
1307 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1308 return ptr;
1309}
1310static void xxfree(void *ptr)
1311{
1312 fdprintf(2, "free %p\n", ptr);
1313 free(ptr);
1314}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001315# define xmalloc(s) xxmalloc(__LINE__, s)
1316# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1317# define xstrdup(s) xxstrdup(__LINE__, s)
1318# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001319#endif
1320
1321
1322/* Syntax and runtime errors. They always abort scripts.
1323 * In interactive use they usually discard unparsed and/or unexecuted commands
1324 * and return to the prompt.
1325 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1326 */
1327#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001328# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001329# define syntax_error(lineno, msg) syntax_error(msg)
1330# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1331# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1332# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1333# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001334#endif
1335
Denys Vlasenko39701202017-08-02 19:44:05 +02001336static void die_if_script(void)
1337{
1338 if (!G_interactive_fd) {
1339 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1340 xfunc_error_retval = G.last_exitcode;
1341 xfunc_die();
1342 }
1343}
1344
1345static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001346{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001347 va_list p;
1348
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001349#if HUSH_DEBUG >= 2
1350 bb_error_msg("hush.c:%u", lineno);
1351#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001352 va_start(p, fmt);
1353 bb_verror_msg(fmt, p, NULL);
1354 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001355 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001356}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001357
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001358static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001359{
1360 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001361 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001362 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001363 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001364 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001365}
1366
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001367static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001368{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001369 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001370 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001371}
1372
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001373static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001374{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001375 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001376//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1377// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001378}
1379
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001380static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001381{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001382 char msg[2] = { ch, '\0' };
1383 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001384}
1385
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001386static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001387{
1388 char msg[2];
1389 msg[0] = ch;
1390 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001391#if HUSH_DEBUG >= 2
1392 bb_error_msg("hush.c:%u", lineno);
1393#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001394 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001395 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001396}
1397
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001398#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001399# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001400# undef syntax_error
1401# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001402# undef syntax_error_unterm_ch
1403# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001404# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001405#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001406# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001407# define syntax_error(msg) syntax_error(__LINE__, msg)
1408# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1409# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1410# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1411# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001412#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001413
Denis Vlasenko552433b2009-04-04 19:29:21 +00001414
Denys Vlasenkof5018da2018-04-06 17:58:21 +02001415#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001416static void cmdedit_update_prompt(void);
1417#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001418# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001419#endif
1420
1421
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001422/* Utility functions
1423 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001424/* Replace each \x with x in place, return ptr past NUL. */
1425static char *unbackslash(char *src)
1426{
Denys Vlasenko71885402009-09-24 01:44:13 +02001427 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001428 while (1) {
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001429 if (*src == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00001430 src++;
Denys Vlasenko89e9d552018-04-11 01:15:33 +02001431 if (*src != '\0') {
1432 /* \x -> x */
1433 *dst++ = *src++;
1434 continue;
1435 }
1436 /* else: "\<nul>". Do not delete this backslash.
1437 * Testcase: eval 'echo ok\'
1438 */
1439 *dst++ = '\\';
1440 /* fallthrough */
1441 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00001442 if ((*dst++ = *src++) == '\0')
1443 break;
1444 }
1445 return dst;
1446}
1447
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001448static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001449{
1450 int i;
1451 unsigned count1;
1452 unsigned count2;
1453 char **v;
1454
1455 v = strings;
1456 count1 = 0;
1457 if (v) {
1458 while (*v) {
1459 count1++;
1460 v++;
1461 }
1462 }
1463 count2 = 0;
1464 v = add;
1465 while (*v) {
1466 count2++;
1467 v++;
1468 }
1469 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1470 v[count1 + count2] = NULL;
1471 i = count2;
1472 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001473 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001474 return v;
1475}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001476#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001477static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1478{
1479 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1480 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1481 return ptr;
1482}
1483#define add_strings_to_strings(strings, add, need_to_dup) \
1484 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1485#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001486
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001487/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001488static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001489{
1490 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001491 v[0] = add;
1492 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001493 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001494}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001495#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001496static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1497{
1498 char **ptr = add_string_to_strings(strings, add);
1499 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1500 return ptr;
1501}
1502#define add_string_to_strings(strings, add) \
1503 xx_add_string_to_strings(__LINE__, strings, add)
1504#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001505
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001506static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001507{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001508 char **v;
1509
1510 if (!strings)
1511 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001512 v = strings;
1513 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001514 free(*v);
1515 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001516 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001517 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001518}
1519
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001520static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001521{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001522 int newfd;
1523 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001524 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1525 if (newfd >= 0) {
1526 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1527 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1528 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001529 if (errno == EBUSY)
1530 goto repeat;
1531 if (errno == EINTR)
1532 goto repeat;
1533 }
1534 return newfd;
1535}
1536
Denys Vlasenko657e9002017-07-30 23:34:04 +02001537static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001538{
1539 int newfd;
1540 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001541 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001542 if (newfd < 0) {
1543 if (errno == EBUSY)
1544 goto repeat;
1545 if (errno == EINTR)
1546 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001547 /* fd was not open? */
1548 if (errno == EBADF)
1549 return fd;
1550 xfunc_die();
1551 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001552 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1553 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001554 close(fd);
1555 return newfd;
1556}
1557
1558
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001559/* Manipulating the list of open FILEs */
1560static FILE *remember_FILE(FILE *fp)
1561{
1562 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001563 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001564 n->next = G.FILE_list;
1565 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001566 n->fp = fp;
1567 n->fd = fileno(fp);
1568 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001569 }
1570 return fp;
1571}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001572static void fclose_and_forget(FILE *fp)
1573{
1574 struct FILE_list **pp = &G.FILE_list;
1575 while (*pp) {
1576 struct FILE_list *cur = *pp;
1577 if (cur->fp == fp) {
1578 *pp = cur->next;
1579 free(cur);
1580 break;
1581 }
1582 pp = &cur->next;
1583 }
1584 fclose(fp);
1585}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001586static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001587{
1588 struct FILE_list *fl = G.FILE_list;
1589 while (fl) {
1590 if (fd == fl->fd) {
1591 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001592 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001593 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 +02001594 return 1;
1595 }
1596 fl = fl->next;
1597 }
1598 return 0;
1599}
1600static void restore_redirected_FILEs(void)
1601{
1602 struct FILE_list *fl = G.FILE_list;
1603 while (fl) {
1604 int should_be = fileno(fl->fp);
1605 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001606 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001607 xmove_fd(fl->fd, should_be);
1608 fl->fd = should_be;
1609 }
1610 fl = fl->next;
1611 }
1612}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001613#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001614static void close_all_FILE_list(void)
1615{
1616 struct FILE_list *fl = G.FILE_list;
1617 while (fl) {
1618 /* fclose would also free FILE object.
1619 * It is disastrous if we share memory with a vforked parent.
1620 * I'm not sure we never come here after vfork.
1621 * Therefore just close fd, nothing more.
1622 */
1623 /*fclose(fl->fp); - unsafe */
1624 close(fl->fd);
1625 fl = fl->next;
1626 }
1627}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001628#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001629static int fd_in_FILEs(int fd)
1630{
1631 struct FILE_list *fl = G.FILE_list;
1632 while (fl) {
1633 if (fl->fd == fd)
1634 return 1;
1635 fl = fl->next;
1636 }
1637 return 0;
1638}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001639
1640
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001641/* Helpers for setting new $n and restoring them back
1642 */
1643typedef struct save_arg_t {
1644 char *sv_argv0;
1645 char **sv_g_argv;
1646 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001647 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001648} save_arg_t;
1649
1650static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1651{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001652 sv->sv_argv0 = argv[0];
1653 sv->sv_g_argv = G.global_argv;
1654 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001655 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001656
1657 argv[0] = G.global_argv[0]; /* retain $0 */
1658 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001659 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001660
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001661 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001662}
1663
1664static void restore_G_args(save_arg_t *sv, char **argv)
1665{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001666#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001667 if (G.global_args_malloced) {
1668 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001669 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001670 while (*++pp) /* note: does not free $0 */
1671 free(*pp);
1672 free(G.global_argv);
1673 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001674#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001675 argv[0] = sv->sv_argv0;
1676 G.global_argv = sv->sv_g_argv;
1677 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001678 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001679}
1680
1681
Denis Vlasenkod5762932009-03-31 11:22:57 +00001682/* Basic theory of signal handling in shell
1683 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001684 * This does not describe what hush does, rather, it is current understanding
1685 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001686 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1687 *
1688 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1689 * is finished or backgrounded. It is the same in interactive and
1690 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001691 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001692 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001693 * backgrounds (i.e. stops) or kills all members of currently running
1694 * pipe.
1695 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001696 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001697 * or by SIGINT in interactive shell.
1698 *
1699 * Trap handlers will execute even within trap handlers. (right?)
1700 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001701 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1702 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001703 *
1704 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001705 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001706 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001707 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001708 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001709 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001710 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001711 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001712 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001713 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001714 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001715 *
1716 * SIGQUIT: ignore
1717 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001718 * SIGHUP (interactive):
1719 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001720 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001721 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1722 * that all pipe members are stopped. Try this in bash:
1723 * while :; do :; done - ^Z does not background it
1724 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001725 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001726 * of the command line, show prompt. NB: ^C does not send SIGINT
1727 * to interactive shell while shell is waiting for a pipe,
1728 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001729 * Example 1: this waits 5 sec, but does not execute ls:
1730 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1731 * Example 2: this does not wait and does not execute ls:
1732 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1733 * Example 3: this does not wait 5 sec, but executes ls:
1734 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001735 * Example 4: this does not wait and does not execute ls:
1736 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001737 *
1738 * (What happens to signals which are IGN on shell start?)
1739 * (What happens with signal mask on shell start?)
1740 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001741 * Old implementation
1742 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001743 * We use in-kernel pending signal mask to determine which signals were sent.
1744 * We block all signals which we don't want to take action immediately,
1745 * i.e. we block all signals which need to have special handling as described
1746 * above, and all signals which have traps set.
1747 * After each pipe execution, we extract any pending signals via sigtimedwait()
1748 * and act on them.
1749 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001750 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001751 * sigset_t blocked_set: current blocked signal set
1752 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001753 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001754 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001755 * "trap 'cmd' SIGxxx":
1756 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001757 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001758 * unblock signals with special interactive handling
1759 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001760 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001761 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001762 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001763 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001764 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001765 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001766 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001767 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001768 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001769 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001770 * Standard says "When a subshell is entered, traps that are not being ignored
1771 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001772 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001773 *
1774 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001775 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001776 * masked signals are not visible!
1777 *
1778 * New implementation
1779 * ==================
1780 * We record each signal we are interested in by installing signal handler
1781 * for them - a bit like emulating kernel pending signal mask in userspace.
1782 * We are interested in: signals which need to have special handling
1783 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001784 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001785 * After each pipe execution, we extract any pending signals
1786 * and act on them.
1787 *
1788 * unsigned special_sig_mask: a mask of shell-special signals.
1789 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1790 * char *traps[sig] if trap for sig is set (even if it's '').
1791 * sigset_t pending_set: set of sigs we received.
1792 *
1793 * "trap - SIGxxx":
1794 * if sig is in special_sig_mask, set handler back to:
1795 * record_pending_signo, or to IGN if it's a tty stop signal
1796 * if sig is in fatal_sig_mask, set handler back to sigexit.
1797 * else: set handler back to SIG_DFL
1798 * "trap 'cmd' SIGxxx":
1799 * set handler to record_pending_signo.
1800 * "trap '' SIGxxx":
1801 * set handler to SIG_IGN.
1802 * after [v]fork, if we plan to be a shell:
1803 * set signals with special interactive handling to SIG_DFL
1804 * (because child shell is not interactive),
1805 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1806 * after [v]fork, if we plan to exec:
1807 * POSIX says fork clears pending signal mask in child - no need to clear it.
1808 *
1809 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1810 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1811 *
1812 * Note (compat):
1813 * Standard says "When a subshell is entered, traps that are not being ignored
1814 * are set to the default actions". bash interprets it so that traps which
1815 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001816 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001817enum {
1818 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001819 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001820 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001821 | (1 << SIGHUP)
1822 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001823 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001824#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001825 | (1 << SIGTTIN)
1826 | (1 << SIGTTOU)
1827 | (1 << SIGTSTP)
1828#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001829 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001830};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001831
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001832static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001833{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001834 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001835#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001836 if (sig == SIGCHLD) {
1837 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001838//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 +02001839 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001840#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001841}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001842
Denys Vlasenko0806e402011-05-12 23:06:20 +02001843static sighandler_t install_sighandler(int sig, sighandler_t handler)
1844{
1845 struct sigaction old_sa;
1846
1847 /* We could use signal() to install handlers... almost:
1848 * except that we need to mask ALL signals while handlers run.
1849 * I saw signal nesting in strace, race window isn't small.
1850 * SA_RESTART is also needed, but in Linux, signal()
1851 * sets SA_RESTART too.
1852 */
1853 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1854 /* sigfillset(&G.sa.sa_mask); - already done */
1855 /* G.sa.sa_flags = SA_RESTART; - already done */
1856 G.sa.sa_handler = handler;
1857 sigaction(sig, &G.sa, &old_sa);
1858 return old_sa.sa_handler;
1859}
1860
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001861static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001862
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001863static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001864static void restore_ttypgrp_and__exit(void)
1865{
1866 /* xfunc has failed! die die die */
1867 /* no EXIT traps, this is an escape hatch! */
1868 G.exiting = 1;
1869 hush_exit(xfunc_error_retval);
1870}
1871
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001872#if ENABLE_HUSH_JOB
1873
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001874/* Needed only on some libc:
1875 * It was observed that on exit(), fgetc'ed buffered data
1876 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1877 * With the net effect that even after fork(), not vfork(),
1878 * exit() in NOEXECed applet in "sh SCRIPT":
1879 * noexec_applet_here
1880 * echo END_OF_SCRIPT
1881 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1882 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001883 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001884 * and in `cmd` handling.
1885 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1886 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001887static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001888static void fflush_and__exit(void)
1889{
1890 fflush_all();
1891 _exit(xfunc_error_retval);
1892}
1893
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001894/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001895# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001896/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001897# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001898
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001899/* Restores tty foreground process group, and exits.
1900 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001901 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001902 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001903 * We also call it if xfunc is exiting.
1904 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001905static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001906static void sigexit(int sig)
1907{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001908 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001909 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001910 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1911 /* Disable all signals: job control, SIGPIPE, etc.
1912 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1913 */
1914 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001915 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001916 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001917
1918 /* Not a signal, just exit */
1919 if (sig <= 0)
1920 _exit(- sig);
1921
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001922 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001923}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001924#else
1925
Denys Vlasenko8391c482010-05-22 17:50:43 +02001926# define disable_restore_tty_pgrp_on_exit() ((void)0)
1927# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001928
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001929#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001930
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001931static sighandler_t pick_sighandler(unsigned sig)
1932{
1933 sighandler_t handler = SIG_DFL;
1934 if (sig < sizeof(unsigned)*8) {
1935 unsigned sigmask = (1 << sig);
1936
1937#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001938 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001939 if (G_fatal_sig_mask & sigmask)
1940 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001941 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001942#endif
1943 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001944 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001945 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001946 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001947 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001948 * in an endless loop when we try to do some
1949 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001950 */
1951 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1952 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001953 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001954 }
1955 return handler;
1956}
1957
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001958/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001959static void hush_exit(int exitcode)
1960{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001961#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1962 save_history(G.line_input_state);
1963#endif
1964
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001965 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001966 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001967 char *argv[3];
1968 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001969 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001970 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001971 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001972 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001973 * "trap" will still show it, if executed
1974 * in the handler */
1975 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001976 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001977
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001978#if ENABLE_FEATURE_CLEAN_UP
1979 {
1980 struct variable *cur_var;
1981 if (G.cwd != bb_msg_unknown)
1982 free((char*)G.cwd);
1983 cur_var = G.top_var;
1984 while (cur_var) {
1985 struct variable *tmp = cur_var;
1986 if (!cur_var->max_len)
1987 free(cur_var->varstr);
1988 cur_var = cur_var->next;
1989 free(tmp);
1990 }
1991 }
1992#endif
1993
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001994 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001995#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001996 sigexit(- (exitcode & 0xff));
1997#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001998 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001999#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00002000}
2001
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02002002
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002003//TODO: return a mask of ALL handled sigs?
2004static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002005{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002006 int last_sig = 0;
2007
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002008 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002009 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02002010
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002011 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002012 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002013 sig = 0;
2014 do {
2015 sig++;
2016 if (sigismember(&G.pending_set, sig)) {
2017 sigdelset(&G.pending_set, sig);
2018 goto got_sig;
2019 }
2020 } while (sig < NSIG);
2021 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002022 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002023 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002024 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002025 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002026 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002027 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002028 char *argv[3];
2029 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002030 argv[1] = xstrdup(G_traps[sig]);
2031 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002032 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002033 save_rcode = G.last_exitcode;
2034 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002035 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002036//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002037 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002038 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002039 } /* else: "" trap, ignoring signal */
2040 continue;
2041 }
2042 /* not a trap: special action */
2043 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002044 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002045 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002046 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002047 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002048 break;
2049#if ENABLE_HUSH_JOB
2050 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002051//TODO: why are we doing this? ash and dash don't do this,
2052//they have no handler for SIGHUP at all,
2053//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002054 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002055 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002056 /* bash is observed to signal whole process groups,
2057 * not individual processes */
2058 for (job = G.job_list; job; job = job->next) {
2059 if (job->pgrp <= 0)
2060 continue;
2061 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2062 if (kill(- job->pgrp, SIGHUP) == 0)
2063 kill(- job->pgrp, SIGCONT);
2064 }
2065 sigexit(SIGHUP);
2066 }
2067#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002068#if ENABLE_HUSH_FAST
2069 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002070 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002071 G.count_SIGCHLD++;
2072//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2073 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002074 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002075 * This simplifies wait builtin a bit.
2076 */
2077 break;
2078#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002079 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002080 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002081 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002082 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002083 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002084 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002085 * in interactive shell, because TERM is ignored.
2086 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002087 break;
2088 }
2089 }
2090 return last_sig;
2091}
2092
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002093
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002094static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002095{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002096 if (force || G.cwd == NULL) {
2097 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2098 * we must not try to free(bb_msg_unknown) */
2099 if (G.cwd == bb_msg_unknown)
2100 G.cwd = NULL;
2101 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2102 if (!G.cwd)
2103 G.cwd = bb_msg_unknown;
2104 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002105 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002106}
2107
Denis Vlasenko83506862007-11-23 13:11:42 +00002108
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002109/*
2110 * Shell and environment variable support
2111 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002112static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002113{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002114 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002116
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002117 pp = &G.top_var;
2118 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002119 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002120 return pp;
2121 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002122 }
2123 return NULL;
2124}
2125
Denys Vlasenko03dad222010-01-12 23:29:57 +01002126static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002127{
Denys Vlasenko29082232010-07-16 13:52:32 +02002128 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002129 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002130
2131 if (G.expanded_assignments) {
2132 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002133 while (*cpp) {
2134 char *cp = *cpp;
2135 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2136 return cp + len + 1;
2137 cpp++;
2138 }
2139 }
2140
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002141 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002142 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002143 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002144
Denys Vlasenkodea47882009-10-09 15:40:49 +02002145 if (strcmp(name, "PPID") == 0)
2146 return utoa(G.root_ppid);
2147 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002148#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002149 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002150 return utoa(next_random(&G.random_gen));
2151#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002152 return NULL;
2153}
2154
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002155static void handle_changed_special_names(const char *name, unsigned name_len)
2156{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002157 if (ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2158 && name_len == 3 && name[0] == 'P' && name[1] == 'S'
2159 ) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002160 cmdedit_update_prompt();
2161 return;
2162 }
2163
2164 if ((ENABLE_HUSH_LINENO_VAR || ENABLE_HUSH_GETOPTS)
2165 && name_len == 6
2166 ) {
2167#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002168 if (strncmp(name, "LINENO", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002169 G.lineno_var = NULL;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002170 return;
2171 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002172#endif
2173#if ENABLE_HUSH_GETOPTS
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002174 if (strncmp(name, "OPTIND", 6) == 0) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002175 G.getopt_count = 0;
Denys Vlasenko00bd7672018-04-06 14:57:53 +02002176 return;
2177 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002178#endif
2179 }
2180}
2181
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002182/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002183 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002184 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002185#define SETFLAG_EXPORT (1 << 0)
2186#define SETFLAG_UNEXPORT (1 << 1)
2187#define SETFLAG_MAKE_RO (1 << 2)
Denys Vlasenko332e4112018-04-04 22:32:59 +02002188#define SETFLAG_VARLVL_SHIFT 3
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002189static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002190{
Denys Vlasenko61407802018-04-04 21:14:28 +02002191 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002192 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002193 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002194 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002195 int name_len;
Denys Vlasenko332e4112018-04-04 22:32:59 +02002196 unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002197
Denis Vlasenko950bd722009-04-21 11:23:56 +00002198 eq_sign = strchr(str, '=');
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002199 if (HUSH_DEBUG && !eq_sign)
2200 bb_error_msg_and_die("BUG in setvar");
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002201
Denis Vlasenko950bd722009-04-21 11:23:56 +00002202 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko61407802018-04-04 21:14:28 +02002203 cur_pp = &G.top_var;
2204 while ((cur = *cur_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002205 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko61407802018-04-04 21:14:28 +02002206 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002207 continue;
2208 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002209
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002210 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002211 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002212 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002213 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002214//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2215//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002216 return -1;
2217 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002218 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002219 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2220 *eq_sign = '\0';
2221 unsetenv(str);
2222 *eq_sign = '=';
2223 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002224 if (cur->var_nest_level < local_lvl) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002225 /* bash 3.2.33(1) and exported vars:
2226 * # export z=z
2227 * # f() { local z=a; env | grep ^z; }
2228 * # f
2229 * z=a
2230 * # env | grep ^z
2231 * z=z
2232 */
2233 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002234 flags |= SETFLAG_EXPORT;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002235 /* New variable is local ("local VAR=VAL" or
2236 * "VAR=VAL cmd")
2237 * and existing one is global, or local
2238 * on a lower level that new one.
2239 * Remove it from global variable list:
2240 */
2241 *cur_pp = cur->next;
2242 if (G.shadowed_vars_pp) {
2243 /* Save in "shadowed" list */
2244 debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
2245 cur->flg_export ? "exported " : "",
2246 cur->varstr, cur->var_nest_level, str, local_lvl
2247 );
2248 cur->next = *G.shadowed_vars_pp;
2249 *G.shadowed_vars_pp = cur;
2250 } else {
2251 /* Came from pseudo_exec_argv(), no need to save: delete it */
2252 debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
2253 cur->flg_export ? "exported " : "",
2254 cur->varstr, cur->var_nest_level, str, local_lvl
2255 );
2256 if (cur->max_len == 0) /* allocated "VAR=VAL"? */
2257 free_me = cur->varstr; /* then free it later */
2258 free(cur);
2259 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002260 break;
2261 }
Denys Vlasenko332e4112018-04-04 22:32:59 +02002262
Denis Vlasenko950bd722009-04-21 11:23:56 +00002263 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002264 debug_printf_env("assignement '%s' does not change anything\n", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002265 free_and_exp:
2266 free(str);
2267 goto exp;
2268 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002269
2270 /* Replace the value in the found "struct variable" */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002271 if (cur->max_len != 0) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002272 if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002273 /* This one is from startup env, reuse space */
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002274 debug_printf_env("reusing startup env for '%s'\n", str);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002275 strcpy(cur->varstr, str);
2276 goto free_and_exp;
2277 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002278 /* Can't reuse */
2279 cur->max_len = 0;
2280 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002281 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002282 /* max_len == 0 signifies "malloced" var, which we can
2283 * (and have to) free. But we can't free(cur->varstr) here:
2284 * if cur->flg_export is 1, it is in the environment.
2285 * We should either unsetenv+free, or wait until putenv,
2286 * then putenv(new)+free(old).
2287 */
2288 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002289 goto set_str_and_exp;
2290 }
2291
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002292 /* Not found or shadowed - create new variable struct */
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002293 debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002294 cur = xzalloc(sizeof(*cur));
Denys Vlasenko332e4112018-04-04 22:32:59 +02002295 cur->var_nest_level = local_lvl;
Denys Vlasenko61407802018-04-04 21:14:28 +02002296 cur->next = *cur_pp;
2297 *cur_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002298
2299 set_str_and_exp:
2300 cur->varstr = str;
2301 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002302#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002303 if (flags & SETFLAG_MAKE_RO) {
2304 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002305 }
2306#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002307 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002308 cur->flg_export = 1;
2309 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002310 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002311 cur->flg_export = 0;
2312 /* unsetenv was already done */
2313 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002314 int i;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002315 debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002316 i = putenv(cur->varstr);
2317 /* only now we can free old exported malloced string */
2318 free(free_me);
2319 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002320 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002321 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002322 free(free_me);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002323
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002324 handle_changed_special_names(cur->varstr, name_len - 1);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002325
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002326 return 0;
2327}
2328
Denys Vlasenko6db47842009-09-05 20:15:17 +02002329/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002330static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002331{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002332 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002333}
2334
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002335static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002336{
2337 struct variable *cur;
Denys Vlasenko61407802018-04-04 21:14:28 +02002338 struct variable **cur_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002339
Denys Vlasenko61407802018-04-04 21:14:28 +02002340 cur_pp = &G.top_var;
2341 while ((cur = *cur_pp) != NULL) {
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002342 if (strncmp(cur->varstr, name, name_len) == 0
2343 && cur->varstr[name_len] == '='
2344 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002345 if (cur->flg_read_only) {
2346 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002347 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002348 }
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002349
Denys Vlasenko61407802018-04-04 21:14:28 +02002350 *cur_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002351 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2352 bb_unsetenv(cur->varstr);
2353 if (!cur->max_len)
2354 free(cur->varstr);
2355 free(cur);
Denys Vlasenkocf079ff2018-04-06 14:50:12 +02002356
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002357 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002358 }
Denys Vlasenko61407802018-04-04 21:14:28 +02002359 cur_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002360 }
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002361
2362 /* Handle "unset PS1" et al even if did not find the variable to unset */
2363 handle_changed_special_names(name, name_len);
2364
Mike Frysingerd690f682009-03-30 06:50:54 +00002365 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002366}
2367
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002368#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002369static int unset_local_var(const char *name)
2370{
2371 return unset_local_var_len(name, strlen(name));
2372}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002373#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002374
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002375#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002376static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002377{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002378 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002379 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002380}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002381#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002382
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002383
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002384/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002385 * Helpers for "var1=val1 var2=val2 cmd" feature
2386 */
2387static void add_vars(struct variable *var)
2388{
2389 struct variable *next;
2390
2391 while (var) {
2392 next = var->next;
2393 var->next = G.top_var;
2394 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002395 if (var->flg_export) {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002396 debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002397 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002398 } else {
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002399 debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002400 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002401 var = next;
2402 }
2403}
2404
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002405/* We put strings[i] into variable table and possibly putenv them.
2406 * If variable is read only, we can free the strings[i]
2407 * which attempts to overwrite it.
2408 * The strings[] vector itself is freed.
2409 */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002410static void set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002411{
2412 char **s;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002413
2414 if (!strings)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002415 return;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002416
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002417 s = strings;
2418 while (*s) {
2419 struct variable *var_p;
2420 struct variable **var_pp;
2421 char *eq;
2422
2423 eq = strchr(*s, '=');
2424 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002425 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002426 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002427 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002428 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002429 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002430 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002431 /*
2432 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2433 * If VAR is readonly, leaving it in the list
2434 * after asssignment error (msg above)
2435 * causes doubled error message later, on unset.
2436 */
2437 debug_printf_env("removing/freeing '%s' element\n", *s);
2438 free(*s);
2439 p = s;
2440 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002441 goto next;
2442 }
Denys Vlasenko929a41d2018-04-05 14:09:14 +02002443 /* below, set_local_var() with nest level will
2444 * "shadow" (remove) this variable from
2445 * global linked list.
2446 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002447 }
Denys Vlasenko9db344a2018-04-09 19:05:11 +02002448 debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002449 set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
2450 } else if (HUSH_DEBUG) {
2451 bb_error_msg_and_die("BUG in varexp4");
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002452 }
2453 s++;
Denys Vlasenko61407802018-04-04 21:14:28 +02002454 next: ;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002455 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02002456 free(strings);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002457}
2458
2459
2460/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002461 * Unicode helper
2462 */
2463static void reinit_unicode_for_hush(void)
2464{
2465 /* Unicode support should be activated even if LANG is set
2466 * _during_ shell execution, not only if it was set when
2467 * shell was started. Therefore, re-check LANG every time:
2468 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002469 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2470 || ENABLE_UNICODE_USING_LOCALE
2471 ) {
2472 const char *s = get_local_var_value("LC_ALL");
2473 if (!s) s = get_local_var_value("LC_CTYPE");
2474 if (!s) s = get_local_var_value("LANG");
2475 reinit_unicode(s);
2476 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002477}
2478
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002479/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002480 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002481 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002482
2483#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002484/* To test correct lineedit/interactive behavior, type from command line:
2485 * echo $P\
2486 * \
2487 * AT\
2488 * H\
2489 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002490 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002491 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002492# if ENABLE_FEATURE_EDITING_FANCY_PROMPT
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002493static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002494{
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002495 G.PS1 = get_local_var_value("PS1");
2496 if (G.PS1 == NULL)
2497 G.PS1 = "";
2498 G.PS2 = get_local_var_value("PS2");
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002499 if (G.PS2 == NULL)
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002500 G.PS2 = "";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002501}
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002502# endif
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002503static const char *setup_prompt_string(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002504{
2505 const char *prompt_str;
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002506
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002507 debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002508
2509 IF_FEATURE_EDITING_FANCY_PROMPT( prompt_str = G.PS2;)
2510 IF_NOT_FEATURE_EDITING_FANCY_PROMPT(prompt_str = "> ";)
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002511 if (G.promptmode == 0) { /* PS1 */
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002512 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2513 /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
Mike Frysingerec2c6552009-03-28 12:24:44 +00002514 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002515 /* bash uses $PWD value, even if it is set by user.
2516 * It uses current dir only if PWD is unset.
2517 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002518 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Denys Vlasenkof5018da2018-04-06 17:58:21 +02002519 }
2520 prompt_str = G.PS1;
2521 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002522 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002523 return prompt_str;
2524}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002525static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002526{
2527 int r;
2528 const char *prompt_str;
2529
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002530 prompt_str = setup_prompt_string();
Denys Vlasenko8391c482010-05-22 17:50:43 +02002531# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002532 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002533 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002534 if (G.flag_SIGINT) {
2535 /* There was ^C'ed, make it look prettier: */
2536 bb_putchar('\n');
2537 G.flag_SIGINT = 0;
2538 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002539 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002540 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002541 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002542 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002543 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002544 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002545 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002546 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002547 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002548 if (r != 0 && !G.flag_SIGINT)
2549 break;
2550 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002551 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2552 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002553 G.last_exitcode = 128 + SIGINT;
2554 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002555 if (r < 0) {
2556 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002557 i->p = NULL;
2558 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002559 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002560 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002561 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002562 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002563# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002564 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002565 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002566 if (i->last_char == '\0' || i->last_char == '\n') {
2567 /* Why check_and_run_traps here? Try this interactively:
2568 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2569 * $ <[enter], repeatedly...>
2570 * Without check_and_run_traps, handler never runs.
2571 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002572 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002573 fputs(prompt_str, stdout);
2574 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002575 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002576//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002577 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002578 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2579 * no ^C masking happens during fgetc, no special code for ^C:
2580 * it generates SIGINT as usual.
2581 */
2582 check_and_run_traps();
2583 if (G.flag_SIGINT)
2584 G.last_exitcode = 128 + SIGINT;
2585 if (r != '\0')
2586 break;
2587 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002588 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002589# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002590}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002591/* This is the magic location that prints prompts
2592 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002593static int fgetc_interactive(struct in_str *i)
2594{
2595 int ch;
2596 /* If it's interactive stdin, get new line. */
2597 if (G_interactive_fd && i->file == stdin) {
2598 /* Returns first char (or EOF), the rest is in i->p[] */
2599 ch = get_user_input(i);
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02002600 G.promptmode = 1; /* PS2 */
2601 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
Denys Vlasenko4074d492016-09-30 01:49:53 +02002602 } else {
2603 /* Not stdin: script file, sourced file, etc */
2604 do ch = fgetc(i->file); while (ch == '\0');
2605 }
2606 return ch;
2607}
2608#else
2609static inline int fgetc_interactive(struct in_str *i)
2610{
2611 int ch;
2612 do ch = fgetc(i->file); while (ch == '\0');
2613 return ch;
2614}
2615#endif /* INTERACTIVE */
2616
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002617static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002618{
2619 int ch;
2620
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002621 if (!i->file) {
2622 /* string-based in_str */
2623 ch = (unsigned char)*i->p;
2624 if (ch != '\0') {
2625 i->p++;
2626 i->last_char = ch;
2627 return ch;
2628 }
2629 return EOF;
2630 }
2631
2632 /* FILE-based in_str */
2633
Denys Vlasenko4074d492016-09-30 01:49:53 +02002634#if ENABLE_FEATURE_EDITING
2635 /* This can be stdin, check line editing char[] buffer */
2636 if (i->p && *i->p != '\0') {
2637 ch = (unsigned char)*i->p++;
2638 goto out;
2639 }
2640#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002641 /* peek_buf[] is an int array, not char. Can contain EOF. */
2642 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002643 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002644 int ch2 = i->peek_buf[1];
2645 i->peek_buf[0] = ch2;
2646 if (ch2 == 0) /* very likely, avoid redundant write */
2647 goto out;
2648 i->peek_buf[1] = 0;
2649 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002650 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002651
Denys Vlasenko4074d492016-09-30 01:49:53 +02002652 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002653 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002654 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002655 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002656#if ENABLE_HUSH_LINENO_VAR
2657 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002658 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002659 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2660 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002661#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002662 return ch;
2663}
2664
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002665static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002666{
2667 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002668
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002669 if (!i->file) {
2670 /* string-based in_str */
2671 /* Doesn't report EOF on NUL. None of the callers care. */
2672 return (unsigned char)*i->p;
2673 }
2674
2675 /* FILE-based in_str */
2676
Denys Vlasenko4074d492016-09-30 01:49:53 +02002677#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002678 /* This can be stdin, check line editing char[] buffer */
2679 if (i->p && *i->p != '\0')
2680 return (unsigned char)*i->p;
2681#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002682 /* peek_buf[] is an int array, not char. Can contain EOF. */
2683 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002684 if (ch != 0)
2685 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002686
Denys Vlasenko4074d492016-09-30 01:49:53 +02002687 /* Need to get a new char */
2688 ch = fgetc_interactive(i);
2689 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2690
2691 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2692#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2693 if (i->p) {
2694 i->p -= 1;
2695 return ch;
2696 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002697#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002698 i->peek_buf[0] = ch;
2699 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002700 return ch;
2701}
2702
Denys Vlasenko4074d492016-09-30 01:49:53 +02002703/* Only ever called if i_peek() was called, and did not return EOF.
2704 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2705 * not end-of-line. Therefore we never need to read a new editing line here.
2706 */
2707static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002708{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002709 int ch;
2710
2711 /* There are two cases when i->p[] buffer exists.
2712 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002713 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002714 * In both cases, we know that i->p[0] exists and not NUL, and
2715 * the peek2 result is in i->p[1].
2716 */
2717 if (i->p)
2718 return (unsigned char)i->p[1];
2719
2720 /* Now we know it is a file-based in_str. */
2721
2722 /* peek_buf[] is an int array, not char. Can contain EOF. */
2723 /* Is there 2nd char? */
2724 ch = i->peek_buf[1];
2725 if (ch == 0) {
2726 /* We did not read it yet, get it now */
2727 do ch = fgetc(i->file); while (ch == '\0');
2728 i->peek_buf[1] = ch;
2729 }
2730
2731 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2732 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002733}
2734
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002735static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2736{
2737 for (;;) {
2738 int ch, ch2;
2739
2740 ch = i_getch(input);
2741 if (ch != '\\')
2742 return ch;
2743 ch2 = i_peek(input);
2744 if (ch2 != '\n')
2745 return ch;
2746 /* backslash+newline, skip it */
2747 i_getch(input);
2748 }
2749}
2750
2751/* Note: this function _eats_ \<newline> pairs, safe to use plain
2752 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2753 */
2754static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2755{
2756 for (;;) {
2757 int ch, ch2;
2758
2759 ch = i_peek(input);
2760 if (ch != '\\')
2761 return ch;
2762 ch2 = i_peek2(input);
2763 if (ch2 != '\n')
2764 return ch;
2765 /* backslash+newline, skip it */
2766 i_getch(input);
2767 i_getch(input);
2768 }
2769}
2770
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002771static void setup_file_in_str(struct in_str *i, FILE *f)
2772{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002773 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002774 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002775 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002776}
2777
2778static void setup_string_in_str(struct in_str *i, const char *s)
2779{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002780 memset(i, 0, sizeof(*i));
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002781 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002782 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002783}
2784
2785
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002786/*
2787 * o_string support
2788 */
2789#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002790
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002791static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002792{
2793 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002794 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002795 if (o->data)
2796 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002797}
2798
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002799static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002800{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002801 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002802 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002803}
2804
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002805static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2806{
2807 free(o->data);
2808}
2809
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002810static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002811{
2812 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002813 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002814 o->data = xrealloc(o->data, 1 + o->maxlen);
2815 }
2816}
2817
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002818static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002819{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002820 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002821 if (o->length < o->maxlen) {
2822 /* likely. avoid o_grow_by() call */
2823 add:
2824 o->data[o->length] = ch;
2825 o->length++;
2826 o->data[o->length] = '\0';
2827 return;
2828 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002829 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002830 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002831}
2832
Denys Vlasenko657086a2016-09-29 18:07:42 +02002833#if 0
2834/* Valid only if we know o_string is not empty */
2835static void o_delchr(o_string *o)
2836{
2837 o->length--;
2838 o->data[o->length] = '\0';
2839}
2840#endif
2841
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002842static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002843{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002844 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002845 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002846 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002847}
2848
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002849static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002850{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002851 o_addblock(o, str, strlen(str));
2852}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002853
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002854#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002855static void nommu_addchr(o_string *o, int ch)
2856{
2857 if (o)
2858 o_addchr(o, ch);
2859}
2860#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002861# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002862#endif
2863
2864static void o_addstr_with_NUL(o_string *o, const char *str)
2865{
2866 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002867}
2868
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002869/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002870 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002871 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2872 * Apparently, on unquoted $v bash still does globbing
2873 * ("v='*.txt'; echo $v" prints all .txt files),
2874 * but NOT brace expansion! Thus, there should be TWO independent
2875 * quoting mechanisms on $v expansion side: one protects
2876 * $v from brace expansion, and other additionally protects "$v" against globbing.
2877 * We have only second one.
2878 */
2879
Denys Vlasenko9e800222010-10-03 14:28:04 +02002880#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002881# define MAYBE_BRACES "{}"
2882#else
2883# define MAYBE_BRACES ""
2884#endif
2885
Eric Andersen25f27032001-04-26 23:22:31 +00002886/* My analysis of quoting semantics tells me that state information
2887 * is associated with a destination, not a source.
2888 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002889static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002890{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002891 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002892 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002893 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002894 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002895 o_grow_by(o, sz);
2896 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002897 o->data[o->length] = '\\';
2898 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002899 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002900 o->data[o->length] = ch;
2901 o->length++;
2902 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002903}
2904
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002905static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002906{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002907 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002908 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2909 && strchr("*?[\\" MAYBE_BRACES, ch)
2910 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002911 sz++;
2912 o->data[o->length] = '\\';
2913 o->length++;
2914 }
2915 o_grow_by(o, sz);
2916 o->data[o->length] = ch;
2917 o->length++;
2918 o->data[o->length] = '\0';
2919}
2920
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002921static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002922{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002923 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002924 char ch;
2925 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002926 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002927 if (ordinary_cnt > len) /* paranoia */
2928 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002929 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002930 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002931 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002932 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002933 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002934
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002935 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002936 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002937 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002938 sz++;
2939 o->data[o->length] = '\\';
2940 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002941 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002942 o_grow_by(o, sz);
2943 o->data[o->length] = ch;
2944 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002945 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002946 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002947}
2948
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002949static void o_addQblock(o_string *o, const char *str, int len)
2950{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002951 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002952 o_addblock(o, str, len);
2953 return;
2954 }
2955 o_addqblock(o, str, len);
2956}
2957
Denys Vlasenko38292b62010-09-05 14:49:40 +02002958static void o_addQstr(o_string *o, const char *str)
2959{
2960 o_addQblock(o, str, strlen(str));
2961}
2962
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002963/* A special kind of o_string for $VAR and `cmd` expansion.
2964 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002965 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002966 * list[i] contains an INDEX (int!) into this string data.
2967 * It means that if list[] needs to grow, data needs to be moved higher up
2968 * but list[i]'s need not be modified.
2969 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002970 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002971 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2972 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002973#if DEBUG_EXPAND || DEBUG_GLOB
2974static void debug_print_list(const char *prefix, o_string *o, int n)
2975{
2976 char **list = (char**)o->data;
2977 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2978 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002979
2980 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002981 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 +02002982 prefix, list, n, string_start, o->length, o->maxlen,
2983 !!(o->o_expflags & EXP_FLAG_GLOB),
2984 o->has_quoted_part,
2985 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002986 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002987 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002988 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2989 o->data + (int)(uintptr_t)list[i] + string_start,
2990 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002991 i++;
2992 }
2993 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002994 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002995 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002996 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002997 }
2998}
2999#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02003000# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003001#endif
3002
3003/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
3004 * in list[n] so that it points past last stored byte so far.
3005 * It returns n+1. */
3006static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003007{
3008 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00003009 int string_start;
3010 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003011
3012 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00003013 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3014 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003015 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003016 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003017 /* list[n] points to string_start, make space for 16 more pointers */
3018 o->maxlen += 0x10 * sizeof(list[0]);
3019 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003020 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003021 memmove(list + n + 0x10, list + n, string_len);
3022 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003023 } else {
3024 debug_printf_list("list[%d]=%d string_start=%d\n",
3025 n, string_len, string_start);
3026 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003027 } else {
3028 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00003029 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
3030 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003031 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
3032 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003033 o->has_empty_slot = 0;
3034 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02003035 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003036 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003037 return n + 1;
3038}
3039
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003040/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003041static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003042{
3043 char **list = (char**)o->data;
3044 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3045
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003046 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003047}
3048
Denys Vlasenko9e800222010-10-03 14:28:04 +02003049#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003050/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3051 * first, it processes even {a} (no commas), second,
3052 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003053 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003054 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003055
3056/* Helper */
3057static int glob_needed(const char *s)
3058{
3059 while (*s) {
3060 if (*s == '\\') {
3061 if (!s[1])
3062 return 0;
3063 s += 2;
3064 continue;
3065 }
3066 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3067 return 1;
3068 s++;
3069 }
3070 return 0;
3071}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003072/* Return pointer to next closing brace or to comma */
3073static const char *next_brace_sub(const char *cp)
3074{
3075 unsigned depth = 0;
3076 cp++;
3077 while (*cp != '\0') {
3078 if (*cp == '\\') {
3079 if (*++cp == '\0')
3080 break;
3081 cp++;
3082 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003083 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003084 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003085 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003086 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003087 depth++;
3088 }
3089
3090 return *cp != '\0' ? cp : NULL;
3091}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003092/* Recursive brace globber. Note: may garble pattern[]. */
3093static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003094{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003095 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003096 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003097 const char *next;
3098 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003099 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003100 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003101
3102 debug_printf_glob("glob_brace('%s')\n", pattern);
3103
3104 begin = pattern;
3105 while (1) {
3106 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003107 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003108 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003109 /* Find the first sub-pattern and at the same time
3110 * find the rest after the closing brace */
3111 next = next_brace_sub(begin);
3112 if (next == NULL) {
3113 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003114 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003115 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003116 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003117 /* "{abc}" with no commas - illegal
3118 * brace expr, disregard and skip it */
3119 begin = next + 1;
3120 continue;
3121 }
3122 break;
3123 }
3124 if (*begin == '\\' && begin[1] != '\0')
3125 begin++;
3126 begin++;
3127 }
3128 debug_printf_glob("begin:%s\n", begin);
3129 debug_printf_glob("next:%s\n", next);
3130
3131 /* Now find the end of the whole brace expression */
3132 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003133 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003134 rest = next_brace_sub(rest);
3135 if (rest == NULL) {
3136 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003137 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003138 }
3139 debug_printf_glob("rest:%s\n", rest);
3140 }
3141 rest_len = strlen(++rest) + 1;
3142
3143 /* We are sure the brace expression is well-formed */
3144
3145 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003146 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003147
3148 /* We have a brace expression. BEGIN points to the opening {,
3149 * NEXT points past the terminator of the first element, and REST
3150 * points past the final }. We will accumulate result names from
3151 * recursive runs for each brace alternative in the buffer using
3152 * GLOB_APPEND. */
3153
3154 p = begin + 1;
3155 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003156 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003157 memcpy(
3158 mempcpy(
3159 mempcpy(new_pattern_buf,
3160 /* We know the prefix for all sub-patterns */
3161 pattern, begin - pattern),
3162 p, next - p),
3163 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003164
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003165 /* Note: glob_brace() may garble new_pattern_buf[].
3166 * That's why we re-copy prefix every time (1st memcpy above).
3167 */
3168 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003169 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003170 /* We saw the last entry */
3171 break;
3172 }
3173 p = next + 1;
3174 next = next_brace_sub(next);
3175 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003176 free(new_pattern_buf);
3177 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003178
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003179 simple_glob:
3180 {
3181 int gr;
3182 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003183
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003184 memset(&globdata, 0, sizeof(globdata));
3185 gr = glob(pattern, 0, NULL, &globdata);
3186 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3187 if (gr != 0) {
3188 if (gr == GLOB_NOMATCH) {
3189 globfree(&globdata);
3190 /* NB: garbles parameter */
3191 unbackslash(pattern);
3192 o_addstr_with_NUL(o, pattern);
3193 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3194 return o_save_ptr_helper(o, n);
3195 }
3196 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003197 bb_die_memory_exhausted();
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003198 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3199 * but we didn't specify it. Paranoia again. */
3200 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3201 }
3202 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3203 char **argv = globdata.gl_pathv;
3204 while (1) {
3205 o_addstr_with_NUL(o, *argv);
3206 n = o_save_ptr_helper(o, n);
3207 argv++;
3208 if (!*argv)
3209 break;
3210 }
3211 }
3212 globfree(&globdata);
3213 }
3214 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003215}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003216/* Performs globbing on last list[],
3217 * saving each result as a new list[].
3218 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003219static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003220{
3221 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003222
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003223 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003224 if (!o->data)
3225 return o_save_ptr_helper(o, n);
3226 pattern = o->data + o_get_last_ptr(o, n);
3227 debug_printf_glob("glob pattern '%s'\n", pattern);
3228 if (!glob_needed(pattern)) {
3229 /* unbackslash last string in o in place, fix length */
3230 o->length = unbackslash(pattern) - o->data;
3231 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3232 return o_save_ptr_helper(o, n);
3233 }
3234
3235 copy = xstrdup(pattern);
3236 /* "forget" pattern in o */
3237 o->length = pattern - o->data;
3238 n = glob_brace(copy, o, n);
3239 free(copy);
3240 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003241 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003242 return n;
3243}
3244
Denys Vlasenko238081f2010-10-03 14:26:26 +02003245#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003246
3247/* Helper */
3248static int glob_needed(const char *s)
3249{
3250 while (*s) {
3251 if (*s == '\\') {
3252 if (!s[1])
3253 return 0;
3254 s += 2;
3255 continue;
3256 }
3257 if (*s == '*' || *s == '[' || *s == '?')
3258 return 1;
3259 s++;
3260 }
3261 return 0;
3262}
3263/* Performs globbing on last list[],
3264 * saving each result as a new list[].
3265 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003266static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003267{
3268 glob_t globdata;
3269 int gr;
3270 char *pattern;
3271
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003272 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003273 if (!o->data)
3274 return o_save_ptr_helper(o, n);
3275 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003276 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003277 if (!glob_needed(pattern)) {
3278 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003279 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003280 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003281 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003282 return o_save_ptr_helper(o, n);
3283 }
3284
3285 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003286 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3287 * If we glob "*.\*" and don't find anything, we need
3288 * to fall back to using literal "*.*", but GLOB_NOCHECK
3289 * will return "*.\*"!
3290 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003291 gr = glob(pattern, 0, NULL, &globdata);
3292 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003293 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003294 if (gr == GLOB_NOMATCH) {
3295 globfree(&globdata);
3296 goto literal;
3297 }
3298 if (gr == GLOB_NOSPACE)
Denys Vlasenko899ae532018-04-01 19:59:37 +02003299 bb_die_memory_exhausted();
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003300 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3301 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003302 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003303 }
3304 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3305 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003306 /* "forget" pattern in o */
3307 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003308 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003309 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003310 n = o_save_ptr_helper(o, n);
3311 argv++;
3312 if (!*argv)
3313 break;
3314 }
3315 }
3316 globfree(&globdata);
3317 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003318 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003319 return n;
3320}
3321
Denys Vlasenko238081f2010-10-03 14:26:26 +02003322#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003323
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003324/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003325 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003326static int o_save_ptr(o_string *o, int n)
3327{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003328 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003329 /* If o->has_empty_slot, list[n] was already globbed
3330 * (if it was requested back then when it was filled)
3331 * so don't do that again! */
3332 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003333 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003334 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003335 return o_save_ptr_helper(o, n);
3336}
3337
3338/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003339static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003340{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003341 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003342 int string_start;
3343
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003344 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3345 if (DEBUG_EXPAND)
3346 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003347 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003348 list = (char**)o->data;
3349 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3350 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003351 while (n) {
3352 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003353 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003354 }
3355 return list;
3356}
3357
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003358static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003359
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003360/* Returns pi->next - next pipe in the list */
3361static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003362{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003363 struct pipe *next;
3364 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003365
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003366 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003367 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003368 struct command *command;
3369 struct redir_struct *r, *rnext;
3370
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003371 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003372 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003373 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003374 if (DEBUG_CLEAN) {
3375 int a;
3376 char **p;
3377 for (a = 0, p = command->argv; *p; a++, p++) {
3378 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3379 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003380 }
3381 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003382 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003383 }
3384 /* not "else if": on syntax error, we may have both! */
3385 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003386 debug_printf_clean(" begin group (cmd_type:%d)\n",
3387 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003388 free_pipe_list(command->group);
3389 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003390 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003391 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003392 /* else is crucial here.
3393 * If group != NULL, child_func is meaningless */
3394#if ENABLE_HUSH_FUNCTIONS
3395 else if (command->child_func) {
3396 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3397 command->child_func->parent_cmd = NULL;
3398 }
3399#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003400#if !BB_MMU
3401 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003402 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003403#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003404 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003405 debug_printf_clean(" redirect %d%s",
3406 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003407 /* guard against the case >$FOO, where foo is unset or blank */
3408 if (r->rd_filename) {
3409 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3410 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003411 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003412 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003413 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003414 rnext = r->next;
3415 free(r);
3416 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003417 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003418 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003419 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003420 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003421#if ENABLE_HUSH_JOB
3422 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003423 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003424#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003425
3426 next = pi->next;
3427 free(pi);
3428 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003429}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003430
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003431static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003432{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003433 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003434#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003435 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003436#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003437 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003438 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003439 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003440}
3441
3442
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003443/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003444
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003445#ifndef debug_print_tree
3446static void debug_print_tree(struct pipe *pi, int lvl)
3447{
3448 static const char *const PIPE[] = {
3449 [PIPE_SEQ] = "SEQ",
3450 [PIPE_AND] = "AND",
3451 [PIPE_OR ] = "OR" ,
3452 [PIPE_BG ] = "BG" ,
3453 };
3454 static const char *RES[] = {
3455 [RES_NONE ] = "NONE" ,
3456# if ENABLE_HUSH_IF
3457 [RES_IF ] = "IF" ,
3458 [RES_THEN ] = "THEN" ,
3459 [RES_ELIF ] = "ELIF" ,
3460 [RES_ELSE ] = "ELSE" ,
3461 [RES_FI ] = "FI" ,
3462# endif
3463# if ENABLE_HUSH_LOOPS
3464 [RES_FOR ] = "FOR" ,
3465 [RES_WHILE] = "WHILE",
3466 [RES_UNTIL] = "UNTIL",
3467 [RES_DO ] = "DO" ,
3468 [RES_DONE ] = "DONE" ,
3469# endif
3470# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3471 [RES_IN ] = "IN" ,
3472# endif
3473# if ENABLE_HUSH_CASE
3474 [RES_CASE ] = "CASE" ,
3475 [RES_CASE_IN ] = "CASE_IN" ,
3476 [RES_MATCH] = "MATCH",
3477 [RES_CASE_BODY] = "CASE_BODY",
3478 [RES_ESAC ] = "ESAC" ,
3479# endif
3480 [RES_XXXX ] = "XXXX" ,
3481 [RES_SNTX ] = "SNTX" ,
3482 };
3483 static const char *const CMDTYPE[] = {
3484 "{}",
3485 "()",
3486 "[noglob]",
3487# if ENABLE_HUSH_FUNCTIONS
3488 "func()",
3489# endif
3490 };
3491
3492 int pin, prn;
3493
3494 pin = 0;
3495 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003496 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3497 lvl*2, "",
3498 pin,
3499 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3500 RES[pi->res_word],
3501 pi->followup, PIPE[pi->followup]
3502 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003503 prn = 0;
3504 while (prn < pi->num_cmds) {
3505 struct command *command = &pi->cmds[prn];
3506 char **argv = command->argv;
3507
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003508 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003509 lvl*2, "", prn,
3510 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003511#if ENABLE_HUSH_LINENO_VAR
3512 fdprintf(2, " LINENO:%u", command->lineno);
3513#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003514 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003515 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003516 CMDTYPE[command->cmd_type],
3517 argv
3518# if !BB_MMU
3519 , " group_as_string:", command->group_as_string
3520# else
3521 , "", ""
3522# endif
3523 );
3524 debug_print_tree(command->group, lvl+1);
3525 prn++;
3526 continue;
3527 }
3528 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003529 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003530 argv++;
3531 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003532 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003533 prn++;
3534 }
3535 pi = pi->next;
3536 pin++;
3537 }
3538}
3539#endif /* debug_print_tree */
3540
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003541static struct pipe *new_pipe(void)
3542{
Eric Andersen25f27032001-04-26 23:22:31 +00003543 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003544 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003545 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003546 return pi;
3547}
3548
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003549/* Command (member of a pipe) is complete, or we start a new pipe
3550 * if ctx->command is NULL.
3551 * No errors possible here.
3552 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003553static int done_command(struct parse_context *ctx)
3554{
3555 /* The command is really already in the pipe structure, so
3556 * advance the pipe counter and make a new, null command. */
3557 struct pipe *pi = ctx->pipe;
3558 struct command *command = ctx->command;
3559
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003560#if 0 /* Instead we emit error message at run time */
3561 if (ctx->pending_redirect) {
3562 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003563 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003564 ctx->pending_redirect = NULL;
3565 }
3566#endif
3567
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003568 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003569 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003570 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003571 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003572 }
3573 pi->num_cmds++;
3574 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003575 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003576 } else {
3577 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3578 }
3579
3580 /* Only real trickiness here is that the uncommitted
3581 * command structure is not counted in pi->num_cmds. */
3582 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003583 ctx->command = command = &pi->cmds[pi->num_cmds];
3584 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003585 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003586#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003587 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003588 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003589#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003590 return pi->num_cmds; /* used only for 0/nonzero check */
3591}
3592
3593static void done_pipe(struct parse_context *ctx, pipe_style type)
3594{
3595 int not_null;
3596
3597 debug_printf_parse("done_pipe entered, followup %d\n", type);
3598 /* Close previous command */
3599 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003600#if HAS_KEYWORDS
3601 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3602 ctx->ctx_inverted = 0;
3603 ctx->pipe->res_word = ctx->ctx_res_w;
3604#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003605 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3606 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003607 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3608 * in a backgrounded subshell.
3609 */
3610 struct pipe *pi;
3611 struct command *command;
3612
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003613 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003614 pi = ctx->list_head;
3615 while (pi != ctx->pipe) {
3616 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3617 goto no_conv;
3618 pi = pi->next;
3619 }
3620
3621 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3622 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3623 pi = xzalloc(sizeof(*pi));
3624 pi->followup = PIPE_BG;
3625 pi->num_cmds = 1;
3626 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3627 command = &pi->cmds[0];
3628 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3629 command->cmd_type = CMD_NORMAL;
3630 command->group = ctx->list_head;
3631#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003632 command->group_as_string = xstrndup(
3633 ctx->as_string.data,
3634 ctx->as_string.length - 1 /* do not copy last char, "&" */
3635 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003636#endif
3637 /* Replace all pipes in ctx with one newly created */
3638 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003639 } else {
3640 no_conv:
3641 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003642 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003643
3644 /* Without this check, even just <enter> on command line generates
3645 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003646 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003647 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003648#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003649 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003650#endif
3651#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003652 || ctx->ctx_res_w == RES_DONE
3653 || ctx->ctx_res_w == RES_FOR
3654 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003655#endif
3656#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003657 || ctx->ctx_res_w == RES_ESAC
3658#endif
3659 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003660 struct pipe *new_p;
3661 debug_printf_parse("done_pipe: adding new pipe: "
3662 "not_null:%d ctx->ctx_res_w:%d\n",
3663 not_null, ctx->ctx_res_w);
3664 new_p = new_pipe();
3665 ctx->pipe->next = new_p;
3666 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003667 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003668 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003669 * This is used to control execution.
3670 * RES_FOR and RES_IN are NOT sticky (needed to support
3671 * cases where variable or value happens to match a keyword):
3672 */
3673#if ENABLE_HUSH_LOOPS
3674 if (ctx->ctx_res_w == RES_FOR
3675 || ctx->ctx_res_w == RES_IN)
3676 ctx->ctx_res_w = RES_NONE;
3677#endif
3678#if ENABLE_HUSH_CASE
3679 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003680 ctx->ctx_res_w = RES_CASE_BODY;
3681 if (ctx->ctx_res_w == RES_CASE)
3682 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003683#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003684 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003685 /* Create the memory for command, roughly:
3686 * ctx->pipe->cmds = new struct command;
3687 * ctx->command = &ctx->pipe->cmds[0];
3688 */
3689 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003690 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003691 }
3692 debug_printf_parse("done_pipe return\n");
3693}
3694
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003695static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003696{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003697 memset(ctx, 0, sizeof(*ctx));
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003698 if (MAYBE_ASSIGNMENT != 0)
3699 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003700 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003701 /* Create the memory for command, roughly:
3702 * ctx->pipe->cmds = new struct command;
3703 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003704 */
3705 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003706}
3707
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003708/* If a reserved word is found and processed, parse context is modified
3709 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003710 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003711#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003712struct reserved_combo {
3713 char literal[6];
3714 unsigned char res;
3715 unsigned char assignment_flag;
3716 int flag;
3717};
3718enum {
3719 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003720# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003721 FLAG_IF = (1 << RES_IF ),
3722 FLAG_THEN = (1 << RES_THEN ),
3723 FLAG_ELIF = (1 << RES_ELIF ),
3724 FLAG_ELSE = (1 << RES_ELSE ),
3725 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003726# endif
3727# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003728 FLAG_FOR = (1 << RES_FOR ),
3729 FLAG_WHILE = (1 << RES_WHILE),
3730 FLAG_UNTIL = (1 << RES_UNTIL),
3731 FLAG_DO = (1 << RES_DO ),
3732 FLAG_DONE = (1 << RES_DONE ),
3733 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003734# endif
3735# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003736 FLAG_MATCH = (1 << RES_MATCH),
3737 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003738# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003739 FLAG_START = (1 << RES_XXXX ),
3740};
3741
3742static const struct reserved_combo* match_reserved_word(o_string *word)
3743{
Eric Andersen25f27032001-04-26 23:22:31 +00003744 /* Mostly a list of accepted follow-up reserved words.
3745 * FLAG_END means we are done with the sequence, and are ready
3746 * to turn the compound list into a command.
3747 * FLAG_START means the word must start a new compound list.
3748 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003749 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003750# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003751 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3752 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3753 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3754 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3755 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3756 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003757# endif
3758# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003759 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3760 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3761 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3762 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3763 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3764 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003765# endif
3766# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003767 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3768 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003769# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003770 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003771 const struct reserved_combo *r;
3772
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003773 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003774 if (strcmp(word->data, r->literal) == 0)
3775 return r;
3776 }
3777 return NULL;
3778}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003779/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003780 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003781static const struct reserved_combo* reserved_word(struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003782{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003783# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003784 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003785 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003786 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003787# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003788 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003789
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003790 if (ctx->word.has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003791 return 0;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003792 r = match_reserved_word(&ctx->word);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003793 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003794 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003795
3796 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003797# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003798 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3799 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003800 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003801 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003802# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003803 if (r->flag == 0) { /* '!' */
3804 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003805 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003806 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003807 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003808 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003809 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003810 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003811 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003812 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003813
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003814 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003815 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003816 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003817 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003818 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003819 syntax_error_at(ctx->word.data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003820 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003821 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003822 } else {
3823 /* "{...} fi" is ok. "{...} if" is not
3824 * Example:
3825 * if { echo foo; } then { echo bar; } fi */
3826 if (ctx->command->group)
3827 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003828 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003829
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003830 ctx->ctx_res_w = r->res;
3831 ctx->old_flag = r->flag;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003832 ctx->is_assignment = r->assignment_flag;
3833 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003834
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003835 if (ctx->old_flag & FLAG_END) {
3836 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003837
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003838 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003839 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003840 old = ctx->stack;
3841 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003842 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003843# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003844 /* At this point, the compound command's string is in
3845 * ctx->as_string... except for the leading keyword!
3846 * Consider this example: "echo a | if true; then echo a; fi"
3847 * ctx->as_string will contain "true; then echo a; fi",
3848 * with "if " remaining in old->as_string!
3849 */
3850 {
3851 char *str;
3852 int len = old->as_string.length;
3853 /* Concatenate halves */
3854 o_addstr(&old->as_string, ctx->as_string.data);
3855 o_free_unsafe(&ctx->as_string);
3856 /* Find where leading keyword starts in first half */
3857 str = old->as_string.data + len;
3858 if (str > old->as_string.data)
3859 str--; /* skip whitespace after keyword */
3860 while (str > old->as_string.data && isalpha(str[-1]))
3861 str--;
3862 /* Ugh, we're done with this horrid hack */
3863 old->command->group_as_string = xstrdup(str);
3864 debug_printf_parse("pop, remembering as:'%s'\n",
3865 old->command->group_as_string);
3866 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003867# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003868 *ctx = *old; /* physical copy */
3869 free(old);
3870 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003871 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003872}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003873#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003874
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003875/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003876 * Normal return is 0. Syntax errors return 1.
3877 * Note: on return, word is reset, but not o_free'd!
3878 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003879static int done_word(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003880{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003881 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003882
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003883 debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
3884 if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003885 debug_printf_parse("done_word return 0: true null, ignored\n");
3886 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003887 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003888
Eric Andersen25f27032001-04-26 23:22:31 +00003889 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003890 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3891 * only if run as "bash", not "sh" */
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003892 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003893 * "2.7 Redirection
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003894 * If the redirection operator is "<<" or "<<-", the word
3895 * that follows the redirection operator shall be
3896 * subjected to quote removal; it is unspecified whether
3897 * any of the other expansions occur. For the other
3898 * redirection operators, the word that follows the
3899 * redirection operator shall be subjected to tilde
3900 * expansion, parameter expansion, command substitution,
3901 * arithmetic expansion, and quote removal.
3902 * Pathname expansion shall not be performed
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003903 * on the word by a non-interactive shell; an interactive
3904 * shell may perform it, but shall do so only when
3905 * the expansion would result in one word."
3906 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003907//bash does not do parameter/command substitution or arithmetic expansion
3908//for _heredoc_ redirection word: these constructs look for exact eof marker
3909// as written:
3910// <<EOF$t
3911// <<EOF$((1))
Denys Vlasenkoe84212f2018-04-01 20:11:23 +02003912// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
3913
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003914 ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003915 /* Cater for >\file case:
3916 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3917 * Same with heredocs:
3918 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3919 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003920 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3921 unbackslash(ctx->pending_redirect->rd_filename);
3922 /* Is it <<"HEREDOC"? */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003923 if (ctx->word.has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003924 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3925 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003926 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003927 debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003928 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003929 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003930#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003931# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003932 if (ctx->ctx_dsemicolon
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003933 && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
Denis Vlasenko757361f2008-07-14 08:26:47 +00003934 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003935 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003936 /* ctx->ctx_res_w = RES_MATCH; */
3937 ctx->ctx_dsemicolon = 0;
3938 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003939# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003940 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003941# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003942 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3943 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003944# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003945# if ENABLE_HUSH_CASE
3946 && ctx->ctx_res_w != RES_CASE
3947# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003948 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003949 const struct reserved_combo *reserved;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003950 reserved = reserved_word(ctx);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003951 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003952 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003953# if ENABLE_HUSH_LINENO_VAR
3954/* Case:
3955 * "while ...; do
3956 * cmd ..."
3957 * If we don't close the pipe _now_, immediately after "do", lineno logic
3958 * sees "cmd" as starting at "do" - i.e., at the previous line.
3959 */
3960 if (0
3961 IF_HUSH_IF(|| reserved->res == RES_THEN)
3962 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3963 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3964 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3965 ) {
3966 done_pipe(ctx, PIPE_SEQ);
3967 }
3968# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003969 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003970 debug_printf_parse("done_word return %d\n",
3971 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003972 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003973 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02003974# if defined(CMD_SINGLEWORD_NOGLOB)
3975 if (0
3976# if BASH_TEST2
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003977 || strcmp(ctx->word.data, "[[") == 0
Denys Vlasenko11752d42018-04-03 08:20:58 +02003978# endif
3979 /* In bash, local/export/readonly are special, args
3980 * are assignments and therefore expansion of them
3981 * should be "one-word" expansion:
3982 * $ export i=`echo 'a b'` # one arg: "i=a b"
3983 * compare with:
3984 * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
3985 * ls: cannot access i=a: No such file or directory
3986 * ls: cannot access b: No such file or directory
3987 * Note: bash 3.2.33(1) does this only if export word
3988 * itself is not quoted:
3989 * $ export i=`echo 'aaa bbb'`; echo "$i"
3990 * aaa bbb
3991 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
3992 * aaa
3993 */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02003994 IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
3995 IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
3996 IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
Denys Vlasenko11752d42018-04-03 08:20:58 +02003997 ) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003998 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3999 }
4000 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004001# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004002 }
Denys Vlasenko11752d42018-04-03 08:20:58 +02004003#endif /* HAS_KEYWORDS */
4004
Denis Vlasenkobb929512009-04-16 10:59:40 +00004005 if (command->group) {
4006 /* "{ echo foo; } echo bar" - bad */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004007 syntax_error_at(ctx->word.data);
Denis Vlasenkobb929512009-04-16 10:59:40 +00004008 debug_printf_parse("done_word return 1: syntax error, "
4009 "groups and arglists don't mix\n");
4010 return 1;
4011 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004012
4013 /* If this word wasn't an assignment, next ones definitely
4014 * can't be assignments. Even if they look like ones. */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004015 if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
4016 && ctx->is_assignment != WORD_IS_KEYWORD
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004017 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004018 ctx->is_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004019 } else {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004020 if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004021 command->assignment_cnt++;
4022 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
4023 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004024 debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
4025 ctx->is_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004026 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004027 debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
4028 command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004029 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004030 }
Eric Andersen25f27032001-04-26 23:22:31 +00004031
Denis Vlasenko06810332007-05-21 23:30:54 +00004032#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004033 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004034 if (ctx->word.has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004035 || !is_well_formed_var_name(command->argv[0], '\0')
4036 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004037 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004038 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004039 return 1;
4040 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004041 /* Force FOR to have just one word (variable name) */
4042 /* NB: basically, this makes hush see "for v in ..."
4043 * syntax as if it is "for v; in ...". FOR and IN become
4044 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004045 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004046 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004047#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004048#if ENABLE_HUSH_CASE
4049 /* Force CASE to have just one word */
4050 if (ctx->ctx_res_w == RES_CASE) {
4051 done_pipe(ctx, PIPE_SEQ);
4052 }
4053#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004054
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004055 o_reset_to_empty_unquoted(&ctx->word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004056
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004057 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004058 return 0;
4059}
4060
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004061
4062/* Peek ahead in the input to find out if we have a "&n" construct,
4063 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004064 * Return:
4065 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4066 * REDIRFD_SYNTAX_ERR if syntax error,
4067 * REDIRFD_TO_FILE if no & was seen,
4068 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004069 */
4070#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004071#define parse_redir_right_fd(as_string, input) \
4072 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004073#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004074static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004075{
4076 int ch, d, ok;
4077
4078 ch = i_peek(input);
4079 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004080 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004081
4082 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004083 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004084 ch = i_peek(input);
4085 if (ch == '-') {
4086 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004087 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004088 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004089 }
4090 d = 0;
4091 ok = 0;
4092 while (ch != EOF && isdigit(ch)) {
4093 d = d*10 + (ch-'0');
4094 ok = 1;
4095 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004096 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004097 ch = i_peek(input);
4098 }
4099 if (ok) return d;
4100
4101//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4102
4103 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004104 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004105}
4106
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004107/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004108 */
4109static int parse_redirect(struct parse_context *ctx,
4110 int fd,
4111 redir_type style,
4112 struct in_str *input)
4113{
4114 struct command *command = ctx->command;
4115 struct redir_struct *redir;
4116 struct redir_struct **redirp;
4117 int dup_num;
4118
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004119 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004120 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004121 /* Check for a '>&1' type redirect */
4122 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4123 if (dup_num == REDIRFD_SYNTAX_ERR)
4124 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004125 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004126 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004127 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004128 if (dup_num) { /* <<-... */
4129 ch = i_getch(input);
4130 nommu_addchr(&ctx->as_string, ch);
4131 ch = i_peek(input);
4132 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004133 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004134
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004135 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004136 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004137 if (ch == '|') {
4138 /* >|FILE redirect ("clobbering" >).
4139 * Since we do not support "set -o noclobber" yet,
4140 * >| and > are the same for now. Just eat |.
4141 */
4142 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004143 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004144 }
4145 }
4146
4147 /* Create a new redir_struct and append it to the linked list */
4148 redirp = &command->redirects;
4149 while ((redir = *redirp) != NULL) {
4150 redirp = &(redir->next);
4151 }
4152 *redirp = redir = xzalloc(sizeof(*redir));
4153 /* redir->next = NULL; */
4154 /* redir->rd_filename = NULL; */
4155 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004156 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004157
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004158 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4159 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004160
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004161 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004162 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004163 /* Erik had a check here that the file descriptor in question
4164 * is legit; I postpone that to "run time"
4165 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004166 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4167 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004168 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004169#if 0 /* Instead we emit error message at run time */
4170 if (ctx->pending_redirect) {
4171 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004172 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004173 }
4174#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 /* Set ctx->pending_redirect, so we know what to do at the
4176 * end of the next parsed word. */
4177 ctx->pending_redirect = redir;
4178 }
4179 return 0;
4180}
4181
Eric Andersen25f27032001-04-26 23:22:31 +00004182/* If a redirect is immediately preceded by a number, that number is
4183 * supposed to tell which file descriptor to redirect. This routine
4184 * looks for such preceding numbers. In an ideal world this routine
4185 * needs to handle all the following classes of redirects...
4186 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4187 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4188 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4189 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004190 *
4191 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4192 * "2.7 Redirection
4193 * ... If n is quoted, the number shall not be recognized as part of
4194 * the redirection expression. For example:
4195 * echo \2>a
4196 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004197 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004198 *
4199 * A -1 return means no valid number was found,
4200 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004201 */
4202static int redirect_opt_num(o_string *o)
4203{
4204 int num;
4205
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004206 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004207 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004208 num = bb_strtou(o->data, NULL, 10);
4209 if (errno || num < 0)
4210 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004211 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004212 return num;
4213}
4214
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004215#if BB_MMU
4216#define fetch_till_str(as_string, input, word, skip_tabs) \
4217 fetch_till_str(input, word, skip_tabs)
4218#endif
4219static char *fetch_till_str(o_string *as_string,
4220 struct in_str *input,
4221 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004222 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004223{
4224 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004225 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004226 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004227 int ch;
4228
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004229 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004230
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004231 while (1) {
4232 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004233 if (ch != EOF)
4234 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004235 if (ch == '\n' || ch == EOF) {
4236 check_heredoc_end:
4237 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4238 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4239 heredoc.data[past_EOL] = '\0';
4240 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4241 return heredoc.data;
4242 }
4243 if (ch == '\n') {
4244 /* This is a new line.
4245 * Remember position and backslash-escaping status.
4246 */
4247 o_addchr(&heredoc, ch);
4248 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004249 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004250 past_EOL = heredoc.length;
4251 /* Get 1st char of next line, possibly skipping leading tabs */
4252 do {
4253 ch = i_getch(input);
4254 if (ch != EOF)
4255 nommu_addchr(as_string, ch);
4256 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4257 /* If this immediately ended the line,
4258 * go back to end-of-line checks.
4259 */
4260 if (ch == '\n')
4261 goto check_heredoc_end;
4262 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004263 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004264 }
4265 if (ch == EOF) {
4266 o_free_unsafe(&heredoc);
4267 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004268 }
4269 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004270 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004271 if (prev == '\\' && ch == '\\')
4272 /* Correctly handle foo\\<eol> (not a line cont.) */
4273 prev = 0; /* not \ */
4274 else
4275 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004276 }
4277}
4278
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004279/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4280 * and load them all. There should be exactly heredoc_cnt of them.
4281 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004282static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4283{
4284 struct pipe *pi = ctx->list_head;
4285
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004286 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004287 int i;
4288 struct command *cmd = pi->cmds;
4289
4290 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4291 pi->num_cmds,
4292 cmd->argv ? cmd->argv[0] : "NONE");
4293 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004294 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004295
4296 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4297 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004298 while (redir) {
4299 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004300 char *p;
4301
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004302 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004303 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004304 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004305 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004306 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004307 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004308 return 1;
4309 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004310 free(redir->rd_filename);
4311 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004312 heredoc_cnt--;
4313 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004314 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004315 }
4316 cmd++;
4317 }
4318 pi = pi->next;
4319 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004320#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004321 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004322 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004323 bb_error_msg_and_die("heredoc BUG 2");
4324#endif
4325 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004326}
4327
4328
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004329static int run_list(struct pipe *pi);
4330#if BB_MMU
4331#define parse_stream(pstring, input, end_trigger) \
4332 parse_stream(input, end_trigger)
4333#endif
4334static struct pipe *parse_stream(char **pstring,
4335 struct in_str *input,
4336 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004337
Eric Andersen25f27032001-04-26 23:22:31 +00004338
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004339static int parse_group(struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004340 struct in_str *input, int ch)
4341{
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004342 /* ctx->word contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004343 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004344 * it contains function name (without '()'). */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004345#if BB_MMU
4346# define as_string NULL
4347#else
4348 char *as_string = NULL;
4349#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004350 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004351 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004352 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004353
4354 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004355#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004356 if (ch == '(' && !ctx->word.has_quoted_part) {
4357 if (ctx->word.length)
4358 if (done_word(ctx))
Denis Vlasenkobb929512009-04-16 10:59:40 +00004359 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004360 if (!command->argv)
4361 goto skip; /* (... */
4362 if (command->argv[1]) { /* word word ... (... */
4363 syntax_error_unexpected_ch('(');
4364 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004365 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004366 /* it is "word(..." or "word (..." */
4367 do
4368 ch = i_getch(input);
4369 while (ch == ' ' || ch == '\t');
4370 if (ch != ')') {
4371 syntax_error_unexpected_ch(ch);
4372 return 1;
4373 }
4374 nommu_addchr(&ctx->as_string, ch);
4375 do
4376 ch = i_getch(input);
4377 while (ch == ' ' || ch == '\t' || ch == '\n');
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004378 if (ch != '{' && ch != '(') {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004379 syntax_error_unexpected_ch(ch);
4380 return 1;
4381 }
4382 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004383 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004384 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004385 }
4386#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004387
4388#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004389 if (command->argv /* word [word]{... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02004390 || ctx->word.length /* word{... */
4391 || ctx->word.has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004392 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004393 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004394 debug_printf_parse("parse_group return 1: "
4395 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004396 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004397 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004398#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004399
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004400 IF_HUSH_FUNCTIONS(skip:)
4401
Denis Vlasenko240c2552009-04-03 03:45:05 +00004402 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004403 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004404 endch = ')';
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004405 IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
4406 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004407 } else {
4408 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004409 ch = i_peek(input);
4410 if (ch != ' ' && ch != '\t' && ch != '\n'
4411 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4412 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004413 syntax_error_unexpected_ch(ch);
4414 return 1;
4415 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004416 if (ch != '(') {
4417 ch = i_getch(input);
4418 nommu_addchr(&ctx->as_string, ch);
4419 }
Eric Andersen25f27032001-04-26 23:22:31 +00004420 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004421
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004422 pipe_list = parse_stream(&as_string, input, endch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004423#if !BB_MMU
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004424 if (as_string)
4425 o_addstr(&ctx->as_string, as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004426#endif
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004427
4428 /* empty ()/{} or parse error? */
4429 if (!pipe_list || pipe_list == ERR_PTR) {
4430 /* parse_stream already emitted error msg */
4431 if (!BB_MMU)
4432 free(as_string);
4433 debug_printf_parse("parse_group return 1: "
4434 "parse_stream returned %p\n", pipe_list);
4435 return 1;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004436 }
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004437#if !BB_MMU
4438 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4439 command->group_as_string = as_string;
4440 debug_printf_parse("end of group, remembering as:'%s'\n",
4441 command->group_as_string);
4442#endif
4443
4444#if ENABLE_HUSH_FUNCTIONS
4445 /* Convert "f() (cmds)" to "f() {(cmds)}" */
4446 if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
4447 struct command *cmd2;
4448
4449 cmd2 = xzalloc(sizeof(*cmd2));
4450 cmd2->cmd_type = CMD_SUBSHELL;
4451 cmd2->group = pipe_list;
4452# if !BB_MMU
4453//UNTESTED!
4454 cmd2->group_as_string = command->group_as_string;
4455 command->group_as_string = xasprintf("(%s)", command->group_as_string);
4456# endif
4457
4458 pipe_list = new_pipe();
4459 pipe_list->cmds = cmd2;
4460 pipe_list->num_cmds = 1;
4461 }
4462#endif
4463
4464 command->group = pipe_list;
4465
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004466 debug_printf_parse("parse_group return 0\n");
4467 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004468 /* command remains "open", available for possible redirects */
Denys Vlasenkofbf44852018-04-03 14:56:52 +02004469#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004470}
4471
Denys Vlasenko0b883582016-12-23 16:49:07 +01004472#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004473/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004474static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004475/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004476static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004477{
4478 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004479 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004480 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004481 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004482 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004483 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004484 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004485 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004486 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004487 }
4488}
4489/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004490static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004491{
4492 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004493 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004494 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004495 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004496 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004497 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004498 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004499 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004500 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004501 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004502 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004503 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004504 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004505 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004506 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4507 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004508 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004509 continue;
4510 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004511 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004512 }
4513}
4514/* Process `cmd` - copy contents until "`" is seen. Complicated by
4515 * \` quoting.
4516 * "Within the backquoted style of command substitution, backslash
4517 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4518 * The search for the matching backquote shall be satisfied by the first
4519 * backquote found without a preceding backslash; during this search,
4520 * if a non-escaped backquote is encountered within a shell comment,
4521 * a here-document, an embedded command substitution of the $(command)
4522 * form, or a quoted string, undefined results occur. A single-quoted
4523 * or double-quoted string that begins, but does not end, within the
4524 * "`...`" sequence produces undefined results."
4525 * Example Output
4526 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4527 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004528static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004529{
4530 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004531 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004532 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004533 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004534 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004535 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4536 ch = i_getch(input);
4537 if (ch != '`'
4538 && ch != '$'
4539 && ch != '\\'
4540 && (!in_dquote || ch != '"')
4541 ) {
4542 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004543 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004544 }
4545 if (ch == EOF) {
4546 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004547 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004548 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004549 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004550 }
4551}
4552/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4553 * quoting and nested ()s.
4554 * "With the $(command) style of command substitution, all characters
4555 * following the open parenthesis to the matching closing parenthesis
4556 * constitute the command. Any valid shell script can be used for command,
4557 * except a script consisting solely of redirections which produces
4558 * unspecified results."
4559 * Example Output
4560 * echo $(echo '(TEST)' BEST) (TEST) BEST
4561 * echo $(echo 'TEST)' BEST) TEST) BEST
4562 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004563 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004564 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004565 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004566 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4567 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004568 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004569#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004570static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004571{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004572 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004573 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004574# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004575 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004576# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004577 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4578
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004579 G.promptmode = 1; /* PS2 */
4580 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
4581
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004582 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004583 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004584 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004585 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004586 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004587 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004588 if (ch == end_ch
4589# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004590 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004591# endif
4592 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004593 if (!dbl)
4594 break;
4595 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004596 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004597 i_getch(input); /* eat second ')' */
4598 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004599 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004600 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004601 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004602 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004603 if (ch == '(' || ch == '{') {
4604 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004605 if (!add_till_closing_bracket(dest, input, ch))
4606 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004607 o_addchr(dest, ch);
4608 continue;
4609 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004610 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004611 if (!add_till_single_quote(dest, input))
4612 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004613 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004614 continue;
4615 }
4616 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004617 if (!add_till_double_quote(dest, input))
4618 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004619 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004620 continue;
4621 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004622 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004623 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4624 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004625 o_addchr(dest, ch);
4626 continue;
4627 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004628 if (ch == '\\') {
4629 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004630 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004631 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004632 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004633 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004634 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004635#if 0
4636 if (ch == '\n') {
4637 /* "backslash+newline", ignore both */
4638 o_delchr(dest); /* undo insertion of '\' */
4639 continue;
4640 }
4641#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004642 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004643 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004644 continue;
4645 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004646 }
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02004647 debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004648 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004649}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004650#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004651
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004652/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004653#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004654#define parse_dollar(as_string, dest, input, quote_mask) \
4655 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004656#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004657#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004658static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004659 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004660 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004661{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004662 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004663
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004664 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004665 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004666 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004667 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004668 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004669 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004670 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004671 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004672 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004673 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004674 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004675 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004676 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004677 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004678 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004679 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004680 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004681 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004682 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004683 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004684 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004685 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004686 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004687 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004688 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004689 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004690 o_addchr(dest, ch | quote_mask);
4691 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004692 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004693 case '$': /* pid */
4694 case '!': /* last bg pid */
4695 case '?': /* last exit code */
4696 case '#': /* number of args */
4697 case '*': /* args */
4698 case '@': /* args */
4699 goto make_one_char_var;
4700 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004701 char len_single_ch;
4702
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004703 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4704
Denys Vlasenko74369502010-05-21 19:52:01 +02004705 ch = i_getch(input); /* eat '{' */
4706 nommu_addchr(as_string, ch);
4707
Denys Vlasenko46e64982016-09-29 19:50:55 +02004708 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004709 /* It should be ${?}, or ${#var},
4710 * or even ${?+subst} - operator acting on a special variable,
4711 * or the beginning of variable name.
4712 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004713 if (ch == EOF
4714 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4715 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004716 bad_dollar_syntax:
4717 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004718 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4719 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004720 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004721 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004722 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004723 ch |= quote_mask;
4724
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004725 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004726 * However, this regresses some of our testsuite cases
4727 * which check invalid constructs like ${%}.
4728 * Oh well... let's check that the var name part is fine... */
4729
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004730 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004731 unsigned pos;
4732
Denys Vlasenko74369502010-05-21 19:52:01 +02004733 o_addchr(dest, ch);
4734 debug_printf_parse(": '%c'\n", ch);
4735
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004736 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004737 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004738 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004739 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004740
Denys Vlasenko74369502010-05-21 19:52:01 +02004741 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004742 unsigned end_ch;
4743 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004744 /* handle parameter expansions
4745 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4746 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004747 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4748 if (len_single_ch != '#'
4749 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4750 || i_peek(input) != '}'
4751 ) {
4752 goto bad_dollar_syntax;
4753 }
4754 /* else: it's "length of C" ${#C} op,
4755 * where C is a single char
4756 * special var name, e.g. ${#!}.
4757 */
4758 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004759 /* Eat everything until closing '}' (or ':') */
4760 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004761 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004762 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004763 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004764 ) {
4765 /* It's ${var:N[:M]} thing */
4766 end_ch = '}' * 0x100 + ':';
4767 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004768 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004769 && ch == '/'
4770 ) {
4771 /* It's ${var/[/]pattern[/repl]} thing */
4772 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4773 i_getch(input);
4774 nommu_addchr(as_string, '/');
4775 ch = '\\';
4776 }
4777 end_ch = '}' * 0x100 + '/';
4778 }
4779 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004780 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004781 if (!BB_MMU)
4782 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004783#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004784 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004785 if (last_ch == 0) /* error? */
4786 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004787#else
4788#error Simple code to only allow ${var} is not implemented
4789#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004790 if (as_string) {
4791 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004792 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004793 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004794
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004795 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4796 && (end_ch & 0xff00)
4797 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004798 /* close the first block: */
4799 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004800 /* while parsing N from ${var:N[:M]}
4801 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004802 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004803 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004804 end_ch = '}';
4805 goto again;
4806 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004807 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004808 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004809 /* it's ${var:N} - emulate :999999999 */
4810 o_addstr(dest, "999999999");
4811 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004812 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004813 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004814 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004815 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004816 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004817 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4818 break;
4819 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004820#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004821 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004822 unsigned pos;
4823
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004824 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004825 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004826# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004827 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004828 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004829 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004830 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4831 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004832 if (!BB_MMU)
4833 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004834 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4835 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004836 if (as_string) {
4837 o_addstr(as_string, dest->data + pos);
4838 o_addchr(as_string, ')');
4839 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004840 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004841 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004842 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004843 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004844# endif
4845# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004846 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4847 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004848 if (!BB_MMU)
4849 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004850 if (!add_till_closing_bracket(dest, input, ')'))
4851 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004852 if (as_string) {
4853 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004854 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004855 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004856 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004857# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004858 break;
4859 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004860#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004861 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004862 goto make_var;
4863#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004864 /* TODO: $_ and $-: */
4865 /* $_ Shell or shell script name; or last argument of last command
4866 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4867 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004868 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004869 ch = i_getch(input);
4870 nommu_addchr(as_string, ch);
4871 ch = i_peek_and_eat_bkslash_nl(input);
4872 if (isalnum(ch)) { /* it's $_name or $_123 */
4873 ch = '_';
4874 goto make_var1;
4875 }
4876 /* else: it's $_ */
4877#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004878 default:
4879 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004880 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004881 debug_printf_parse("parse_dollar return 1 (ok)\n");
4882 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004883#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004884}
4885
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004886#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004887# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004888#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4889 encode_string(dest, input, dquote_end, process_bkslash)
4890# else
4891/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4892#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4893 encode_string(dest, input, dquote_end)
4894# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004895#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004896
4897#else /* !MMU */
4898
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004899# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004900/* all parameters are needed, no macro tricks */
4901# else
4902#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4903 encode_string(as_string, dest, input, dquote_end)
4904# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004905#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004906static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004907 o_string *dest,
4908 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004909 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004910 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004911{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004912#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004913 const int process_bkslash = 1;
4914#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004915 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004916 int next;
4917
4918 again:
4919 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004920 if (ch != EOF)
4921 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004922 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004923 debug_printf_parse("encode_string return 1 (ok)\n");
4924 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004925 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004926 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004927 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004928 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004929 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004930 }
4931 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004932 if (ch != '\n') {
4933 next = i_peek(input);
4934 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004935 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004936 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004937 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004938 if (next == EOF) {
Denys Vlasenko4709df02018-04-10 14:49:01 +02004939 /* Testcase: in interactive shell a file with
4940 * echo "unterminated string\<eof>
4941 * is sourced.
4942 */
4943 syntax_error_unterm_ch('"');
4944 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004945 }
4946 /* bash:
4947 * "The backslash retains its special meaning [in "..."]
4948 * only when followed by one of the following characters:
4949 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004950 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004951 * NB: in (unquoted) heredoc, above does not apply to ",
4952 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004953 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004954 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004955 ch = i_getch(input); /* eat next */
4956 if (ch == '\n')
4957 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004958 } /* else: ch remains == '\\', and we double it below: */
4959 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004960 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004961 goto again;
4962 }
4963 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004964 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4965 debug_printf_parse("encode_string return 0: "
4966 "parse_dollar returned 0 (error)\n");
4967 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004968 }
4969 goto again;
4970 }
4971#if ENABLE_HUSH_TICK
4972 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004973 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004974 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4975 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004976 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4977 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004978 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4979 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004980 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004981 }
4982#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004983 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004984 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004985#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004986}
4987
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004988/*
4989 * Scan input until EOF or end_trigger char.
4990 * Return a list of pipes to execute, or NULL on EOF
4991 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004992 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004993 * reset parsing machinery and start parsing anew,
4994 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004995 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004996static struct pipe *parse_stream(char **pstring,
4997 struct in_str *input,
4998 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004999{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005000 struct parse_context ctx;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005001 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005002
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005003 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005004 * found. When recursing, quote state is passed in via ctx.word.o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005005 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005006 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005007 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005008 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005009
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005010 initialize_context(&ctx);
5011
5012 /* If very first arg is "" or '', ctx.word.data may end up NULL.
5013 * Preventing this:
5014 */
5015 o_addchr(&ctx.word, '\0');
5016 ctx.word.length = 0;
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005017
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005018 /* We used to separate words on $IFS here. This was wrong.
5019 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005020 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005021 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005022
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005023 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005024 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005025 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005026 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005027 int ch;
5028 int next;
5029 int redir_fd;
5030 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005031
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005032 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005033 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005034 ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005035 if (ch == EOF) {
5036 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005037
5038 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005039 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005040 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005041 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005042 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005043 syntax_error_unterm_ch('(');
5044 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005045 }
Denys Vlasenko42246472016-11-07 16:22:35 +01005046 if (end_trigger == '}') {
5047 syntax_error_unterm_ch('{');
5048 goto parse_error;
5049 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005050
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005051 if (done_word(&ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005052 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005053 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005054 o_free(&ctx.word);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005055 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005056 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005057 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005058 /* (this makes bare "&" cmd a no-op.
5059 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005060 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005061 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005062 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005063 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005064 pi = NULL;
5065 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005066#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005067 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005068 if (pstring)
5069 *pstring = ctx.as_string.data;
5070 else
5071 o_free_unsafe(&ctx.as_string);
5072#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005073 debug_leave();
5074 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005075 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005076 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005077 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005078
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005079 /* Handle "'" and "\" first, as they won't play nice with
5080 * i_peek_and_eat_bkslash_nl() anyway:
5081 * echo z\\
5082 * and
5083 * echo '\
5084 * '
5085 * would break.
5086 */
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005087 if (ch == '\'') {
5088 ctx.word.has_quoted_part = 1;
5089 next = i_getch(input);
5090 if (next == '\'' && !ctx.pending_redirect)
5091 goto insert_empty_quoted_str_marker;
5092
5093 ch = next;
5094 while (1) {
5095 if (ch == EOF) {
5096 syntax_error_unterm_ch('\'');
5097 goto parse_error;
5098 }
5099 nommu_addchr(&ctx.as_string, ch);
5100 if (ch == '\'')
5101 break;
5102 if (ch == SPECIAL_VAR_SYMBOL) {
5103 /* Convert raw ^C to corresponding special variable reference */
5104 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5105 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
5106 }
5107 o_addqchr(&ctx.word, ch);
5108 ch = i_getch(input);
5109 }
5110 continue; /* get next char */
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005111 }
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005112 if (ch == '\\') {
5113 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5114 o_addchr(&ctx.word, '\\');
5115 ch = i_getch(input);
5116 if (ch == EOF) {
5117 /* Testcase: eval 'echo Ok\' */
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005118
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005119#if 0 /* bash-4.3.43 was removing backslash, but 4.4.19 retains it, most other shells too */
5120 /* Remove trailing '\' from ctx.as_string */
5121 ctx.as_string.data[--ctx.as_string.length] = '\0';
5122#endif
5123 continue; /* get next char */
5124 }
5125 /* Example: echo Hello \2>file
5126 * we need to know that word 2 is quoted
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005127 */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005128 ctx.word.has_quoted_part = 1;
5129 nommu_addchr(&ctx.as_string, ch);
5130 o_addchr(&ctx.word, ch);
5131 continue; /* get next char */
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005132 }
5133
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005134 next = '\0';
5135 if (ch != '\n')
5136 next = i_peek_and_eat_bkslash_nl(input);
5137
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005138 is_special = "{}<>;&|()#" /* special outside of "str" */
Denys Vlasenko0403bed2018-04-11 01:33:54 +02005139 "$\"" IF_HUSH_TICK("`") /* always special */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005140 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005141 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005142 if (ctx.command->argv /* word [word]{... - non-special */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005143 || ctx.word.length /* word{... - non-special */
5144 || ctx.word.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005145 || (next != ';' /* }; - special */
5146 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005147 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005148 && next != '&' /* }& and }&& ... - special */
5149 && next != '|' /* }|| ... - special */
5150 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005151 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005152 ) {
5153 /* They are not special, skip "{}" */
5154 is_special += 2;
5155 }
5156 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005157 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005158
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005159 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005160 ordinary_char:
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005161 o_addQchr(&ctx.word, ch);
5162 if ((ctx.is_assignment == MAYBE_ASSIGNMENT
5163 || ctx.is_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005164 && ch == '='
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005165 && is_well_formed_var_name(ctx.word.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005166 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005167 ctx.is_assignment = DEFINITELY_ASSIGNMENT;
5168 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005169 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005170 continue;
5171 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005172
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005173 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005174#if ENABLE_HUSH_LINENO_VAR
5175/* Case:
5176 * "while ...; do<whitespace><newline>
5177 * cmd ..."
5178 * would think that "cmd" starts in <whitespace> -
5179 * i.e., at the previous line.
5180 * We need to skip all whitespace before newlines.
5181 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005182 while (ch != '\n') {
5183 next = i_peek(input);
5184 if (next != ' ' && next != '\t' && next != '\n')
5185 break; /* next char is not ws */
5186 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005187 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005188 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005189#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005190 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005191 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005192 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005193 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005194 /* Is this a case when newline is simply ignored?
5195 * Some examples:
5196 * "cmd | <newline> cmd ..."
5197 * "case ... in <newline> word) ..."
5198 */
5199 if (IS_NULL_CMD(ctx.command)
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005200 && ctx.word.length == 0 && !ctx.word.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005201 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005202 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005203 * Without check #1, interactive shell
5204 * ignores even bare <newline>,
5205 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005206 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005207 * ps2> _ <=== wrong, should be ps1
5208 * Without check #2, "cmd & <newline>"
5209 * is similarly mistreated.
5210 * (BTW, this makes "cmd & cmd"
5211 * and "cmd && cmd" non-orthogonal.
5212 * Really, ask yourself, why
5213 * "cmd && <newline>" doesn't start
5214 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005215 * The only reason is that it might be
5216 * a "cmd1 && <nl> cmd2 &" construct,
5217 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005218 */
5219 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005220 if (pi->num_cmds != 0 /* check #1 */
5221 && pi->followup != PIPE_BG /* check #2 */
5222 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005223 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005224 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005225 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005226 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005227 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005228 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5229 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005230 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005231 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005232 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005233 heredoc_cnt = 0;
5234 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005235 ctx.is_assignment = MAYBE_ASSIGNMENT;
5236 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005237 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005238 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005239 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005240 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005241 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005242
5243 /* "cmd}" or "cmd }..." without semicolon or &:
5244 * } is an ordinary char in this case, even inside { cmd; }
5245 * Pathological example: { ""}; } should exec "}" cmd
5246 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005247 if (ch == '}') {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005248 if (ctx.word.length != 0 /* word} */
5249 || ctx.word.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005250 ) {
5251 goto ordinary_char;
5252 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005253 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5254 /* Generally, there should be semicolon: "cmd; }"
5255 * However, bash allows to omit it if "cmd" is
5256 * a group. Examples:
5257 * { { echo 1; } }
5258 * {(echo 1)}
5259 * { echo 0 >&2 | { echo 1; } }
5260 * { while false; do :; done }
5261 * { case a in b) ;; esac }
5262 */
5263 if (ctx.command->group)
5264 goto term_group;
5265 goto ordinary_char;
5266 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005267 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005268 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005269 goto skip_end_trigger;
5270 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005271 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005272 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005273 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005274 && (ch != ';' || heredoc_cnt == 0)
5275#if ENABLE_HUSH_CASE
5276 && (ch != ')'
5277 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005278 || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005279 )
5280#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005281 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005282 if (heredoc_cnt) {
5283 /* This is technically valid:
5284 * { cat <<HERE; }; echo Ok
5285 * heredoc
5286 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005287 * HERE
5288 * but we don't support this.
5289 * We require heredoc to be in enclosing {}/(),
5290 * if any.
5291 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005292 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005293 goto parse_error;
5294 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005295 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005296 goto parse_error;
5297 }
5298 done_pipe(&ctx, PIPE_SEQ);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005299 ctx.is_assignment = MAYBE_ASSIGNMENT;
5300 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005301 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005302 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005303 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005304 ) {
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005305 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005306#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005307 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005308 if (pstring)
5309 *pstring = ctx.as_string.data;
5310 else
5311 o_free_unsafe(&ctx.as_string);
5312#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005313 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5314 /* Example: bare "{ }", "()" */
5315 G.last_exitcode = 2; /* bash compat */
5316 syntax_error_unexpected_ch(ch);
5317 goto parse_error2;
5318 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005319 debug_printf_parse("parse_stream return %p: "
5320 "end_trigger char found\n",
5321 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005322 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005323 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005324 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005325 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005326
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005327 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005328 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005329
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005330 /* Catch <, > before deciding whether this word is
5331 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5332 switch (ch) {
5333 case '>':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005334 redir_fd = redirect_opt_num(&ctx.word);
5335 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005336 goto parse_error;
5337 }
5338 redir_style = REDIRECT_OVERWRITE;
5339 if (next == '>') {
5340 redir_style = REDIRECT_APPEND;
5341 ch = i_getch(input);
5342 nommu_addchr(&ctx.as_string, ch);
5343 }
5344#if 0
5345 else if (next == '(') {
5346 syntax_error(">(process) not supported");
5347 goto parse_error;
5348 }
5349#endif
5350 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5351 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005352 continue; /* get next char */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005353 case '<':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005354 redir_fd = redirect_opt_num(&ctx.word);
5355 if (done_word(&ctx)) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005356 goto parse_error;
5357 }
5358 redir_style = REDIRECT_INPUT;
5359 if (next == '<') {
5360 redir_style = REDIRECT_HEREDOC;
5361 heredoc_cnt++;
5362 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5363 ch = i_getch(input);
5364 nommu_addchr(&ctx.as_string, ch);
5365 } else if (next == '>') {
5366 redir_style = REDIRECT_IO;
5367 ch = i_getch(input);
5368 nommu_addchr(&ctx.as_string, ch);
5369 }
5370#if 0
5371 else if (next == '(') {
5372 syntax_error("<(process) not supported");
5373 goto parse_error;
5374 }
5375#endif
5376 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5377 goto parse_error;
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005378 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005379 case '#':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005380 if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005381 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005382 /* note: we do not add it to &ctx.as_string */
5383/* TODO: in bash:
5384 * comment inside $() goes to the next \n, even inside quoted string (!):
5385 * cmd "$(cmd2 #comment)" - syntax error
5386 * cmd "`cmd2 #comment`" - ok
5387 * We accept both (comment ends where command subst ends, in both cases).
5388 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005389 while (1) {
5390 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005391 if (ch == '\n') {
5392 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005393 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005394 }
5395 ch = i_getch(input);
5396 if (ch == EOF)
5397 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005398 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005399 continue; /* get next char */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005400 }
5401 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005402 }
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005403 skip_end_trigger:
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005404
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005405 if (ctx.is_assignment == MAYBE_ASSIGNMENT
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005406 /* check that we are not in word in "a=1 2>word b=1": */
5407 && !ctx.pending_redirect
5408 ) {
5409 /* ch is a special char and thus this word
5410 * cannot be an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005411 ctx.is_assignment = NOT_ASSIGNMENT;
5412 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005413 }
5414
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005415 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5416
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005417 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005418 case SPECIAL_VAR_SYMBOL:
5419 /* Convert raw ^C to corresponding special variable reference */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005420 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5421 o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
Denys Vlasenko932b9972018-01-11 12:39:48 +01005422 /* fall through */
5423 case '#':
5424 /* non-comment #: "echo a#b" etc */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005425 o_addchr(&ctx.word, ch);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005426 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005427 case '$':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005428 if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005429 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005430 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005431 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005432 }
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005433 continue; /* get next char */
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005434 case '"':
5435 ctx.word.has_quoted_part = 1;
5436 if (next == '"' && !ctx.pending_redirect) {
Denys Vlasenko92a930b2018-04-10 14:20:48 +02005437 i_getch(input); /* eat second " */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005438 insert_empty_quoted_str_marker:
5439 nommu_addchr(&ctx.as_string, next);
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005440 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5441 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005442 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005443 }
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005444 if (ctx.is_assignment == NOT_ASSIGNMENT)
5445 ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5446 if (!encode_string(&ctx.as_string, &ctx.word, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005447 goto parse_error;
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005448 ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005449 continue; /* get next char */
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005450#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005451 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005452 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005453
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005454 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5455 o_addchr(&ctx.word, '`');
5456 USE_FOR_NOMMU(pos = ctx.word.length;)
5457 if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005458 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005459# if !BB_MMU
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005460 o_addstr(&ctx.as_string, ctx.word.data + pos);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005461 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005462# endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005463 o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
5464 //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005465 continue; /* get next char */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005466 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005467#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005468 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005469#if ENABLE_HUSH_CASE
5470 case_semi:
5471#endif
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005472 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005473 goto parse_error;
5474 }
5475 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005476#if ENABLE_HUSH_CASE
5477 /* Eat multiple semicolons, detect
5478 * whether it means something special */
5479 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005480 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005481 if (ch != ';')
5482 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005483 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005484 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005485 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005486 ctx.ctx_dsemicolon = 1;
5487 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005488 break;
5489 }
5490 }
5491#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005492 new_cmd:
5493 /* We just finished a cmd. New one may start
5494 * with an assignment */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005495 ctx.is_assignment = MAYBE_ASSIGNMENT;
5496 debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005497 continue; /* get next char */
Eric Andersen25f27032001-04-26 23:22:31 +00005498 case '&':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005499 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005500 goto parse_error;
5501 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005502 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005503 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005504 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005505 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005506 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005507 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005508 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005509 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005510 case '|':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005511 if (done_word(&ctx)) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005512 goto parse_error;
5513 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005514#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005515 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005516 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005517#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005518 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005519 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005520 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005521 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005522 } else {
5523 /* we could pick up a file descriptor choice here
5524 * with redirect_opt_num(), but bash doesn't do it.
5525 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005526 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005527 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005528 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005529 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005530#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005531 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005532 if (ctx.ctx_res_w == RES_MATCH
5533 && ctx.command->argv == NULL /* not (word|(... */
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005534 && ctx.word.length == 0 /* not word(... */
5535 && ctx.word.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005536 ) {
Denys Vlasenkoe8b1bc02018-04-10 13:13:10 +02005537 continue; /* get next char */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005538 }
5539#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005540 case '{':
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005541 if (parse_group(&ctx, input, ch) != 0) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005542 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005543 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005544 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005545 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005546#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005547 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005548 goto case_semi;
5549#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005550 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005551 /* proper use of this character is caught by end_trigger:
5552 * if we see {, we call parse_group(..., end_trigger='}')
5553 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005554 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005555 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005556 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005557 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005558 if (HUSH_DEBUG)
Denys Vlasenko332e4112018-04-04 22:32:59 +02005559 bb_error_msg_and_die("BUG: unexpected %c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005560 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005561 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005562
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005563 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005564 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005565 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005566 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005567 struct parse_context *pctx;
5568 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005569
5570 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005571 * Sample for finding leaks on syntax error recovery path.
5572 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005573 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005574 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005575 * while if (true | { true;}); then echo ok; fi; do break; done
5576 * 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 +00005577 */
5578 pctx = &ctx;
5579 do {
5580 /* Update pipe/command counts,
5581 * otherwise freeing may miss some */
5582 done_pipe(pctx, PIPE_SEQ);
5583 debug_printf_clean("freeing list %p from ctx %p\n",
5584 pctx->list_head, pctx);
5585 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005586 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005587 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005588#if !BB_MMU
5589 o_free_unsafe(&pctx->as_string);
5590#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005591 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005592 if (pctx != &ctx) {
5593 free(pctx);
5594 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005595 IF_HAS_KEYWORDS(pctx = p2;)
5596 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005597
Denys Vlasenko09b7a7e2018-04-10 03:22:10 +02005598 o_free(&ctx.word);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005599#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005600 if (pstring)
5601 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005602#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005603 debug_leave();
5604 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005605 }
Eric Andersen25f27032001-04-26 23:22:31 +00005606}
5607
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005608
5609/*** Execution routines ***/
5610
5611/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005612#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005613/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5614#define expand_string_to_string(str, do_unbackslash) \
5615 expand_string_to_string(str)
5616#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005617static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005618#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005619static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005620#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005621
5622/* expand_strvec_to_strvec() takes a list of strings, expands
5623 * all variable references within and returns a pointer to
5624 * a list of expanded strings, possibly with larger number
5625 * of strings. (Think VAR="a b"; echo $VAR).
5626 * This new list is allocated as a single malloc block.
5627 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005628 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005629 * Caller can deallocate entire list by single free(list). */
5630
Denys Vlasenko238081f2010-10-03 14:26:26 +02005631/* A horde of its helpers come first: */
5632
5633static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5634{
5635 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005636 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005637
Denys Vlasenko9e800222010-10-03 14:28:04 +02005638#if ENABLE_HUSH_BRACE_EXPANSION
5639 if (c == '{' || c == '}') {
5640 /* { -> \{, } -> \} */
5641 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005642 /* And now we want to add { or } and continue:
5643 * o_addchr(o, c);
5644 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005645 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005646 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005647 }
5648#endif
5649 o_addchr(o, c);
5650 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005651 /* \z -> \\\z; \<eol> -> \\<eol> */
5652 o_addchr(o, '\\');
5653 if (len) {
5654 len--;
5655 o_addchr(o, '\\');
5656 o_addchr(o, *str++);
5657 }
5658 }
5659 }
5660}
5661
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005662/* Store given string, finalizing the word and starting new one whenever
5663 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005664 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5665 * Return in *ended_with_ifs:
5666 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5667 */
5668static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005669{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005670 int last_is_ifs = 0;
5671
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005672 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005673 int word_len;
5674
5675 if (!*str) /* EOL - do not finalize word */
5676 break;
5677 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005678 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005679 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005680 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005681 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005682 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005683 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005684 * Example: "v='\*'; echo b$v" prints "b\*"
5685 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005686 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005687 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005688 /*/ Why can't we do it easier? */
5689 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5690 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5691 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005692 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005693 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005694 if (!*str) /* EOL - do not finalize word */
5695 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005696 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005697
5698 /* We know str here points to at least one IFS char */
5699 last_is_ifs = 1;
5700 str += strspn(str, G.ifs); /* skip IFS chars */
5701 if (!*str) /* EOL - do not finalize word */
5702 break;
5703
5704 /* Start new word... but not always! */
5705 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005706 if (output->has_quoted_part
5707 /* Case "v=' a'; echo $v":
5708 * here nothing precedes the space in $v expansion,
5709 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005710 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005711 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005712 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005713 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005714 o_addchr(output, '\0');
5715 debug_print_list("expand_on_ifs", output, n);
5716 n = o_save_ptr(output, n);
5717 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005718 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005719
5720 if (ended_with_ifs)
5721 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005722 debug_print_list("expand_on_ifs[1]", output, n);
5723 return n;
5724}
5725
5726/* Helper to expand $((...)) and heredoc body. These act as if
5727 * they are in double quotes, with the exception that they are not :).
5728 * Just the rules are similar: "expand only $var and `cmd`"
5729 *
5730 * Returns malloced string.
5731 * As an optimization, we return NULL if expansion is not needed.
5732 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005733#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005734/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5735#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5736 encode_then_expand_string(str)
5737#endif
5738static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005739{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005740#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005741 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005742#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005743 char *exp_str;
5744 struct in_str input;
5745 o_string dest = NULL_O_STRING;
5746
5747 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005748 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005749#if ENABLE_HUSH_TICK
5750 && !strchr(str, '`')
5751#endif
5752 ) {
5753 return NULL;
5754 }
5755
5756 /* We need to expand. Example:
5757 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5758 */
5759 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005760 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005761//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005762 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005763 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005764 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5765 o_free_unsafe(&dest);
5766 return exp_str;
5767}
5768
Denys Vlasenko0b883582016-12-23 16:49:07 +01005769#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005770static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005771{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005772 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005773 arith_t res;
5774 char *exp_str;
5775
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005776 math_state.lookupvar = get_local_var_value;
5777 math_state.setvar = set_local_var_from_halves;
5778 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005779 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005780 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005781 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005782 if (errmsg_p)
5783 *errmsg_p = math_state.errmsg;
5784 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005785 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005786 return res;
5787}
5788#endif
5789
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005790#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005791/* ${var/[/]pattern[/repl]} helpers */
5792static char *strstr_pattern(char *val, const char *pattern, int *size)
5793{
5794 while (1) {
5795 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5796 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5797 if (end) {
5798 *size = end - val;
5799 return val;
5800 }
5801 if (*val == '\0')
5802 return NULL;
5803 /* Optimization: if "*pat" did not match the start of "string",
5804 * we know that "tring", "ring" etc will not match too:
5805 */
5806 if (pattern[0] == '*')
5807 return NULL;
5808 val++;
5809 }
5810}
5811static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5812{
5813 char *result = NULL;
5814 unsigned res_len = 0;
5815 unsigned repl_len = strlen(repl);
5816
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005817 /* Null pattern never matches, including if "var" is empty */
5818 if (!pattern[0])
5819 return result; /* NULL, no replaces happened */
5820
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005821 while (1) {
5822 int size;
5823 char *s = strstr_pattern(val, pattern, &size);
5824 if (!s)
5825 break;
5826
5827 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005828 strcpy(mempcpy(result + res_len, val, s - val), repl);
5829 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005830 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5831
5832 val = s + size;
5833 if (exp_op == '/')
5834 break;
5835 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005836 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005837 result = xrealloc(result, res_len + strlen(val) + 1);
5838 strcpy(result + res_len, val);
5839 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5840 }
5841 debug_printf_varexp("result:'%s'\n", result);
5842 return result;
5843}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005844#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005845
5846/* Helper:
5847 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5848 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005849static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005850{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005851 const char *val;
5852 char *to_be_freed;
5853 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005854 char *var;
5855 char first_char;
5856 char exp_op;
5857 char exp_save = exp_save; /* for compiler */
5858 char *exp_saveptr; /* points to expansion operator */
5859 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005860 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005861
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005862 val = NULL;
5863 to_be_freed = NULL;
5864 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005865 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005866 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005867 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005868 arg0 = arg[0];
5869 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005870 exp_op = 0;
5871
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005872 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5873 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5874 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5875 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005876 ) {
5877 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005878 var++;
5879 exp_op = 'L';
5880 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005881 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005882 if (exp_saveptr /* if 2nd char is one of expansion operators */
5883 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5884 ) {
5885 /* ${?:0}, ${#[:]%0} etc */
5886 exp_saveptr = var + 1;
5887 } else {
5888 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5889 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5890 }
5891 exp_op = exp_save = *exp_saveptr;
5892 if (exp_op) {
5893 exp_word = exp_saveptr + 1;
5894 if (exp_op == ':') {
5895 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005896//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005897 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005898 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005899 ) {
5900 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5901 exp_op = ':';
5902 exp_word--;
5903 }
5904 }
5905 *exp_saveptr = '\0';
5906 } /* else: it's not an expansion op, but bare ${var} */
5907 }
5908
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005909 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005910 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005911 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005912 int n = xatoi_positive(var);
5913 if (n < G.global_argc)
5914 val = G.global_argv[n];
5915 /* else val remains NULL: $N with too big N */
5916 } else {
5917 switch (var[0]) {
5918 case '$': /* pid */
5919 val = utoa(G.root_pid);
5920 break;
5921 case '!': /* bg pid */
5922 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5923 break;
5924 case '?': /* exitcode */
5925 val = utoa(G.last_exitcode);
5926 break;
5927 case '#': /* argc */
5928 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5929 break;
5930 default:
5931 val = get_local_var_value(var);
5932 }
5933 }
5934
5935 /* Handle any expansions */
5936 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005937 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005938 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005939 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005940 debug_printf_expand("%s\n", val);
5941 } else if (exp_op) {
5942 if (exp_op == '%' || exp_op == '#') {
5943 /* Standard-mandated substring removal ops:
5944 * ${parameter%word} - remove smallest suffix pattern
5945 * ${parameter%%word} - remove largest suffix pattern
5946 * ${parameter#word} - remove smallest prefix pattern
5947 * ${parameter##word} - remove largest prefix pattern
5948 *
5949 * Word is expanded to produce a glob pattern.
5950 * Then var's value is matched to it and matching part removed.
5951 */
5952 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005953 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005954 char *exp_exp_word;
5955 char *loc;
5956 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005957 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005958 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005959 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01005960 /*
5961 * process_bkslash:1 unbackslash:1 breaks this:
5962 * a='a\\'; echo ${a%\\\\} # correct output is: a
5963 * process_bkslash:1 unbackslash:0 breaks this:
5964 * a='a}'; echo ${a%\}} # correct output is: a
5965 */
5966 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005967 if (exp_exp_word)
5968 exp_word = exp_exp_word;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005969 debug_printf_expand("expand: exp_exp_word:'%s'\n", exp_word);
Denys Vlasenko4f870492010-09-10 11:06:01 +02005970 /* HACK ALERT. We depend here on the fact that
5971 * G.global_argv and results of utoa and get_local_var_value
5972 * are actually in writable memory:
5973 * scan_and_match momentarily stores NULs there. */
5974 t = (char*)val;
5975 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01005976 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 +02005977 free(exp_exp_word);
5978 if (loc) { /* match was found */
5979 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005980 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005981 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005982 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005983 }
5984 }
5985 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005986#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005987 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005988 /* It's ${var/[/]pattern[/repl]} thing.
5989 * Note that in encoded form it has TWO parts:
5990 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005991 * and if // is used, it is encoded as \:
5992 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005993 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005994 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005995 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005996 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005997 * by the usual expansion rules:
Denys Vlasenkode026252018-04-05 17:04:53 +02005998 * >az >bz
5999 * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
6000 * v='a bz'; echo "${v/a*z/\z}" #prints "z"
6001 * v='a bz'; echo ${v/a*z/a*z} #prints "az"
6002 * v='a bz'; echo ${v/a*z/\z} #prints "z"
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006003 * (note that a*z _pattern_ is never globbed!)
6004 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006005 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006006 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006007 if (!pattern)
6008 pattern = xstrdup(exp_word);
6009 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
6010 *p++ = SPECIAL_VAR_SYMBOL;
6011 exp_word = p;
6012 p = strchr(p, SPECIAL_VAR_SYMBOL);
6013 *p = '\0';
Denys Vlasenkode026252018-04-05 17:04:53 +02006014 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006015 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
6016 /* HACK ALERT. We depend here on the fact that
6017 * G.global_argv and results of utoa and get_local_var_value
6018 * are actually in writable memory:
6019 * replace_pattern momentarily stores NULs there. */
6020 t = (char*)val;
6021 to_be_freed = replace_pattern(t,
6022 pattern,
6023 (repl ? repl : exp_word),
6024 exp_op);
6025 if (to_be_freed) /* at least one replace happened */
6026 val = to_be_freed;
6027 free(pattern);
6028 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01006029 } else {
6030 /* Empty variable always gives nothing */
6031 // "v=''; echo ${v/*/w}" prints "", not "w"
6032 /* Just skip "replace" part */
6033 *p++ = SPECIAL_VAR_SYMBOL;
6034 p = strchr(p, SPECIAL_VAR_SYMBOL);
6035 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006036 }
6037 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006038#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006039 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006040#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006041 /* It's ${var:N[:M]} bashism.
6042 * Note that in encoded form it has TWO parts:
6043 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
6044 */
6045 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02006046 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006047
Denys Vlasenko063847d2010-09-15 13:33:02 +02006048 beg = expand_and_evaluate_arith(exp_word, &errmsg);
6049 if (errmsg)
6050 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006051 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
6052 *p++ = SPECIAL_VAR_SYMBOL;
6053 exp_word = p;
6054 p = strchr(p, SPECIAL_VAR_SYMBOL);
6055 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02006056 len = expand_and_evaluate_arith(exp_word, &errmsg);
6057 if (errmsg)
6058 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006059 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006060 if (beg < 0) {
6061 /* negative beg counts from the end */
6062 beg = (arith_t)strlen(val) + beg;
6063 if (beg < 0) /* ${v: -999999} is "" */
6064 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006065 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006066 debug_printf_varexp("from val:'%s'\n", val);
6067 if (len < 0) {
6068 /* in bash, len=-n means strlen()-n */
6069 len = (arith_t)strlen(val) - beg + len;
6070 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02006071 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006072 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02006073 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006074 arith_err:
6075 val = NULL;
6076 } else {
6077 /* Paranoia. What if user entered 9999999999999
6078 * which fits in arith_t but not int? */
6079 if (len >= INT_MAX)
6080 len = INT_MAX;
6081 val = to_be_freed = xstrndup(val + beg, len);
6082 }
6083 debug_printf_varexp("val:'%s'\n", val);
6084#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006085 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006086 val = NULL;
6087#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006088 } else { /* one of "-=+?" */
6089 /* Standard-mandated substitution ops:
6090 * ${var?word} - indicate error if unset
6091 * If var is unset, word (or a message indicating it is unset
6092 * if word is null) is written to standard error
6093 * and the shell exits with a non-zero exit status.
6094 * Otherwise, the value of var is substituted.
6095 * ${var-word} - use default value
6096 * If var is unset, word is substituted.
6097 * ${var=word} - assign and use default value
6098 * If var is unset, word is assigned to var.
6099 * In all cases, final value of var is substituted.
6100 * ${var+word} - use alternative value
6101 * If var is unset, null is substituted.
6102 * Otherwise, word is substituted.
6103 *
6104 * Word is subjected to tilde expansion, parameter expansion,
6105 * command substitution, and arithmetic expansion.
6106 * If word is not needed, it is not expanded.
6107 *
6108 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6109 * but also treat null var as if it is unset.
6110 */
6111 int use_word = (!val || ((exp_save == ':') && !val[0]));
6112 if (exp_op == '+')
6113 use_word = !use_word;
6114 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6115 (exp_save == ':') ? "true" : "false", use_word);
6116 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006117 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006118 if (to_be_freed)
6119 exp_word = to_be_freed;
6120 if (exp_op == '?') {
6121 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006122 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006123 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02006124 exp_word[0]
6125 ? exp_word
6126 : "parameter null or not set"
6127 /* ash has more specific messages, a-la: */
6128 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006129 );
6130//TODO: how interactive bash aborts expansion mid-command?
6131 } else {
6132 val = exp_word;
6133 }
6134
6135 if (exp_op == '=') {
6136 /* ${var=[word]} or ${var:=[word]} */
6137 if (isdigit(var[0]) || var[0] == '#') {
6138 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006139 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006140 val = NULL;
6141 } else {
6142 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02006143 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006144 }
6145 }
6146 }
6147 } /* one of "-=+?" */
6148
6149 *exp_saveptr = exp_save;
6150 } /* if (exp_op) */
6151
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006152 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006153
6154 *pp = p;
6155 *to_be_freed_pp = to_be_freed;
6156 return val;
6157}
6158
6159/* Expand all variable references in given string, adding words to list[]
6160 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6161 * to be filled). This routine is extremely tricky: has to deal with
6162 * variables/parameters with whitespace, $* and $@, and constructs like
6163 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006164static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006165{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006166 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006167 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006168 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006169 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006170 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006171 char *p;
6172
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006173 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6174 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006175 debug_print_list("expand_vars_to_list", output, n);
6176 n = o_save_ptr(output, n);
6177 debug_print_list("expand_vars_to_list[0]", output, n);
6178
6179 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6180 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006181 char *to_be_freed = NULL;
6182 const char *val = NULL;
6183#if ENABLE_HUSH_TICK
6184 o_string subst_result = NULL_O_STRING;
6185#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006186#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006187 char arith_buf[sizeof(arith_t)*3 + 2];
6188#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006189
6190 if (ended_in_ifs) {
6191 o_addchr(output, '\0');
6192 n = o_save_ptr(output, n);
6193 ended_in_ifs = 0;
6194 }
6195
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006196 o_addblock(output, arg, p - arg);
6197 debug_print_list("expand_vars_to_list[1]", output, n);
6198 arg = ++p;
6199 p = strchr(p, SPECIAL_VAR_SYMBOL);
6200
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006201 /* Fetch special var name (if it is indeed one of them)
6202 * and quote bit, force the bit on if singleword expansion -
6203 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006204 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006205
6206 /* Is this variable quoted and thus expansion can't be null?
6207 * "$@" is special. Even if quoted, it can still
6208 * expand to nothing (not even an empty string),
6209 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006210 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006211 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006212
6213 switch (first_ch & 0x7f) {
6214 /* Highest bit in first_ch indicates that var is double-quoted */
6215 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006216 case '@': {
6217 int i;
6218 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006219 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006220 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006221 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006222 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006223 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006224 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006225 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6226 if (G.global_argv[i++][0] && G.global_argv[i]) {
6227 /* this argv[] is not empty and not last:
6228 * put terminating NUL, start new word */
6229 o_addchr(output, '\0');
6230 debug_print_list("expand_vars_to_list[2]", output, n);
6231 n = o_save_ptr(output, n);
6232 debug_print_list("expand_vars_to_list[3]", output, n);
6233 }
6234 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006235 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006236 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006237 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006238 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006239 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006240 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006241 while (1) {
6242 o_addQstr(output, G.global_argv[i]);
6243 if (++i >= G.global_argc)
6244 break;
6245 o_addchr(output, '\0');
6246 debug_print_list("expand_vars_to_list[4]", output, n);
6247 n = o_save_ptr(output, n);
6248 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006249 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006250 while (1) {
6251 o_addQstr(output, G.global_argv[i]);
6252 if (!G.global_argv[++i])
6253 break;
6254 if (G.ifs[0])
6255 o_addchr(output, G.ifs[0]);
6256 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006257 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006258 }
6259 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006260 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006261 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6262 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006263 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006264 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006265 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006266 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006267 case SPECIAL_VAR_QUOTED_SVS:
6268 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6269 arg++;
6270 val = SPECIAL_VAR_SYMBOL_STR;
6271 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006272#if ENABLE_HUSH_TICK
6273 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006274 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006275 arg++;
6276 /* Can't just stuff it into output o_string,
6277 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006278 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006279 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6280 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenko5fa05052018-04-03 11:21:13 +02006281 G.expand_exitcode = G.last_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006282 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6283 val = subst_result.data;
6284 goto store_val;
6285#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006286#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006287 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6288 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006289
6290 arg++; /* skip '+' */
6291 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6292 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006293 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006294 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6295 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006296 val = arith_buf;
6297 break;
6298 }
6299#endif
6300 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006301 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006302 IF_HUSH_TICK(store_val:)
6303 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006304 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6305 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006306 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006307 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006308 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006309 }
6310 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006311 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006312 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6313 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006314 }
6315 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006316 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6317
6318 if (val && val[0]) {
6319 o_addQstr(output, val);
6320 }
6321 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006322
6323 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6324 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006325 if (*p != SPECIAL_VAR_SYMBOL)
6326 *p = SPECIAL_VAR_SYMBOL;
6327
6328#if ENABLE_HUSH_TICK
6329 o_free(&subst_result);
6330#endif
6331 arg = ++p;
6332 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6333
6334 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006335 if (ended_in_ifs) {
6336 o_addchr(output, '\0');
6337 n = o_save_ptr(output, n);
6338 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006339 debug_print_list("expand_vars_to_list[a]", output, n);
6340 /* this part is literal, and it was already pre-quoted
6341 * if needed (much earlier), do not use o_addQstr here! */
6342 o_addstr_with_NUL(output, arg);
6343 debug_print_list("expand_vars_to_list[b]", output, n);
6344 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006345 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006346 ) {
6347 n--;
6348 /* allow to reuse list[n] later without re-growth */
6349 output->has_empty_slot = 1;
6350 } else {
6351 o_addchr(output, '\0');
6352 }
6353
6354 return n;
6355}
6356
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006357static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006358{
6359 int n;
6360 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006361 o_string output = NULL_O_STRING;
6362
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006363 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006364
6365 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006366 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006367 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006368 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006369 }
6370 debug_print_list("expand_variables", &output, n);
6371
6372 /* output.data (malloced in one block) gets returned in "list" */
6373 list = o_finalize_list(&output, n);
6374 debug_print_strings("expand_variables[1]", list);
6375 return list;
6376}
6377
6378static char **expand_strvec_to_strvec(char **argv)
6379{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006380 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006381}
6382
Denys Vlasenko11752d42018-04-03 08:20:58 +02006383#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006384static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6385{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006386 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006387}
6388#endif
6389
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006390/* Used for expansion of right hand of assignments,
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02006391 * $((...)), heredocs, variable expansion parts.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006392 *
6393 * NB: should NOT do globbing!
6394 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6395 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006396static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006397{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006398#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006399 const int do_unbackslash = 1;
6400#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006401 char *argv[2], **list;
6402
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006403 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006404 /* This is generally an optimization, but it also
6405 * handles "", which otherwise trips over !list[0] check below.
6406 * (is this ever happens that we actually get str="" here?)
6407 */
6408 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6409 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006410 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006411 return xstrdup(str);
6412 }
6413
6414 argv[0] = (char*)str;
6415 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006416 list = expand_variables(argv, do_unbackslash
6417 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6418 : EXP_FLAG_SINGLEWORD
6419 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006420 if (HUSH_DEBUG)
6421 if (!list[0] || list[1])
6422 bb_error_msg_and_die("BUG in varexp2");
6423 /* actually, just move string 2*sizeof(char*) bytes back */
6424 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006425 if (do_unbackslash)
6426 unbackslash((char*)list);
6427 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006428 return (char*)list;
6429}
6430
Denys Vlasenkoabf75562018-04-02 17:25:18 +02006431#if 0
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006432static char* expand_strvec_to_string(char **argv)
6433{
6434 char **list;
6435
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006436 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006437 /* Convert all NULs to spaces */
6438 if (list[0]) {
6439 int n = 1;
6440 while (list[n]) {
6441 if (HUSH_DEBUG)
6442 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6443 bb_error_msg_and_die("BUG in varexp3");
6444 /* bash uses ' ' regardless of $IFS contents */
6445 list[n][-1] = ' ';
6446 n++;
6447 }
6448 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006449 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006450 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6451 return (char*)list;
6452}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006453#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006454
6455static char **expand_assignments(char **argv, int count)
6456{
6457 int i;
6458 char **p;
6459
6460 G.expanded_assignments = p = NULL;
6461 /* Expand assignments into one string each */
6462 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006463 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006464 }
6465 G.expanded_assignments = NULL;
6466 return p;
6467}
6468
6469
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006470static void switch_off_special_sigs(unsigned mask)
6471{
6472 unsigned sig = 0;
6473 while ((mask >>= 1) != 0) {
6474 sig++;
6475 if (!(mask & 1))
6476 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006477#if ENABLE_HUSH_TRAP
6478 if (G_traps) {
6479 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006480 /* trap is '', has to remain SIG_IGN */
6481 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006482 free(G_traps[sig]);
6483 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006484 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006485#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006486 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006487 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006488 }
6489}
6490
Denys Vlasenkob347df92011-08-09 22:49:15 +02006491#if BB_MMU
6492/* never called */
6493void re_execute_shell(char ***to_free, const char *s,
6494 char *g_argv0, char **g_argv,
6495 char **builtin_argv) NORETURN;
6496
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006497static void reset_traps_to_defaults(void)
6498{
6499 /* This function is always called in a child shell
6500 * after fork (not vfork, NOMMU doesn't use this function).
6501 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006502 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006503 unsigned mask;
6504
6505 /* Child shells are not interactive.
6506 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6507 * Testcase: (while :; do :; done) + ^Z should background.
6508 * Same goes for SIGTERM, SIGHUP, SIGINT.
6509 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006510 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006511 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006512 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006513
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006514 /* Switch off special sigs */
6515 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006516# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006517 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006518# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006519 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006520 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6521 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006522
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006523# if ENABLE_HUSH_TRAP
6524 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006525 return;
6526
6527 /* Reset all sigs to default except ones with empty traps */
6528 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006529 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006530 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006531 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006532 continue; /* empty trap: has to remain SIG_IGN */
6533 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006534 free(G_traps[sig]);
6535 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006536 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006537 if (sig == 0)
6538 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006539 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006540 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006541# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006542}
6543
6544#else /* !BB_MMU */
6545
6546static void re_execute_shell(char ***to_free, const char *s,
6547 char *g_argv0, char **g_argv,
6548 char **builtin_argv) NORETURN;
6549static void re_execute_shell(char ***to_free, const char *s,
6550 char *g_argv0, char **g_argv,
6551 char **builtin_argv)
6552{
6553# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6554 /* delims + 2 * (number of bytes in printed hex numbers) */
6555 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6556 char *heredoc_argv[4];
6557 struct variable *cur;
6558# if ENABLE_HUSH_FUNCTIONS
6559 struct function *funcp;
6560# endif
6561 char **argv, **pp;
6562 unsigned cnt;
6563 unsigned long long empty_trap_mask;
6564
6565 if (!g_argv0) { /* heredoc */
6566 argv = heredoc_argv;
6567 argv[0] = (char *) G.argv0_for_re_execing;
6568 argv[1] = (char *) "-<";
6569 argv[2] = (char *) s;
6570 argv[3] = NULL;
6571 pp = &argv[3]; /* used as pointer to empty environment */
6572 goto do_exec;
6573 }
6574
6575 cnt = 0;
6576 pp = builtin_argv;
6577 if (pp) while (*pp++)
6578 cnt++;
6579
6580 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006581 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006582 int sig;
6583 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006584 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006585 empty_trap_mask |= 1LL << sig;
6586 }
6587 }
6588
6589 sprintf(param_buf, NOMMU_HACK_FMT
6590 , (unsigned) G.root_pid
6591 , (unsigned) G.root_ppid
6592 , (unsigned) G.last_bg_pid
6593 , (unsigned) G.last_exitcode
6594 , cnt
6595 , empty_trap_mask
6596 IF_HUSH_LOOPS(, G.depth_of_loop)
6597 );
6598# undef NOMMU_HACK_FMT
6599 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6600 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6601 */
6602 cnt += 6;
6603 for (cur = G.top_var; cur; cur = cur->next) {
6604 if (!cur->flg_export || cur->flg_read_only)
6605 cnt += 2;
6606 }
6607# if ENABLE_HUSH_FUNCTIONS
6608 for (funcp = G.top_func; funcp; funcp = funcp->next)
6609 cnt += 3;
6610# endif
6611 pp = g_argv;
6612 while (*pp++)
6613 cnt++;
6614 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6615 *pp++ = (char *) G.argv0_for_re_execing;
6616 *pp++ = param_buf;
6617 for (cur = G.top_var; cur; cur = cur->next) {
6618 if (strcmp(cur->varstr, hush_version_str) == 0)
6619 continue;
6620 if (cur->flg_read_only) {
6621 *pp++ = (char *) "-R";
6622 *pp++ = cur->varstr;
6623 } else if (!cur->flg_export) {
6624 *pp++ = (char *) "-V";
6625 *pp++ = cur->varstr;
6626 }
6627 }
6628# if ENABLE_HUSH_FUNCTIONS
6629 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6630 *pp++ = (char *) "-F";
6631 *pp++ = funcp->name;
6632 *pp++ = funcp->body_as_string;
6633 }
6634# endif
6635 /* We can pass activated traps here. Say, -Tnn:trap_string
6636 *
6637 * However, POSIX says that subshells reset signals with traps
6638 * to SIG_DFL.
6639 * I tested bash-3.2 and it not only does that with true subshells
6640 * of the form ( list ), but with any forked children shells.
6641 * I set trap "echo W" WINCH; and then tried:
6642 *
6643 * { echo 1; sleep 20; echo 2; } &
6644 * while true; do echo 1; sleep 20; echo 2; break; done &
6645 * true | { echo 1; sleep 20; echo 2; } | cat
6646 *
6647 * In all these cases sending SIGWINCH to the child shell
6648 * did not run the trap. If I add trap "echo V" WINCH;
6649 * _inside_ group (just before echo 1), it works.
6650 *
6651 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006652 */
6653 *pp++ = (char *) "-c";
6654 *pp++ = (char *) s;
6655 if (builtin_argv) {
6656 while (*++builtin_argv)
6657 *pp++ = *builtin_argv;
6658 *pp++ = (char *) "";
6659 }
6660 *pp++ = g_argv0;
6661 while (*g_argv)
6662 *pp++ = *g_argv++;
6663 /* *pp = NULL; - is already there */
6664 pp = environ;
6665
6666 do_exec:
6667 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006668 /* Don't propagate SIG_IGN to the child */
6669 if (SPECIAL_JOBSTOP_SIGS != 0)
6670 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006671 execve(bb_busybox_exec_path, argv, pp);
6672 /* Fallback. Useful for init=/bin/hush usage etc */
6673 if (argv[0][0] == '/')
6674 execve(argv[0], argv, pp);
6675 xfunc_error_retval = 127;
6676 bb_error_msg_and_die("can't re-execute the shell");
6677}
6678#endif /* !BB_MMU */
6679
6680
6681static int run_and_free_list(struct pipe *pi);
6682
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006683/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006684 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6685 * end_trigger controls how often we stop parsing
6686 * NUL: parse all, execute, return
6687 * ';': parse till ';' or newline, execute, repeat till EOF
6688 */
6689static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006690{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006691 /* Why we need empty flag?
6692 * An obscure corner case "false; ``; echo $?":
6693 * empty command in `` should still set $? to 0.
6694 * But we can't just set $? to 0 at the start,
6695 * this breaks "false; echo `echo $?`" case.
6696 */
6697 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006698 while (1) {
6699 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006700
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006701#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko8d6eab32018-04-07 17:01:31 +02006702 if (end_trigger == ';') {
6703 G.promptmode = 0; /* PS1 */
6704 debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
6705 }
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006706#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006707 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006708 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6709 /* If we are in "big" script
6710 * (not in `cmd` or something similar)...
6711 */
6712 if (pipe_list == ERR_PTR && end_trigger == ';') {
6713 /* Discard cached input (rest of line) */
6714 int ch = inp->last_char;
6715 while (ch != EOF && ch != '\n') {
6716 //bb_error_msg("Discarded:'%c'", ch);
6717 ch = i_getch(inp);
6718 }
6719 /* Force prompt */
6720 inp->p = NULL;
6721 /* This stream isn't empty */
6722 empty = 0;
6723 continue;
6724 }
6725 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006726 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006727 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006728 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006729 debug_print_tree(pipe_list, 0);
6730 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6731 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006732 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006733 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006734 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006735 }
Eric Andersen25f27032001-04-26 23:22:31 +00006736}
6737
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006738static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006739{
6740 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006741 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6742
Eric Andersen25f27032001-04-26 23:22:31 +00006743 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006744 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006745 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006746}
6747
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006748static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006749{
Eric Andersen25f27032001-04-26 23:22:31 +00006750 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006751 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01006752
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006753 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01006754 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006755 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006756 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006757}
6758
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006759#if ENABLE_HUSH_TICK
6760static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6761{
6762 pid_t pid;
6763 int channel[2];
6764# if !BB_MMU
6765 char **to_free = NULL;
6766# endif
6767
6768 xpipe(channel);
6769 pid = BB_MMU ? xfork() : xvfork();
6770 if (pid == 0) { /* child */
6771 disable_restore_tty_pgrp_on_exit();
6772 /* Process substitution is not considered to be usual
6773 * 'command execution'.
6774 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6775 */
6776 bb_signals(0
6777 + (1 << SIGTSTP)
6778 + (1 << SIGTTIN)
6779 + (1 << SIGTTOU)
6780 , SIG_IGN);
6781 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6782 close(channel[0]); /* NB: close _first_, then move fd! */
6783 xmove_fd(channel[1], 1);
6784 /* Prevent it from trying to handle ctrl-z etc */
6785 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006786# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006787 /* Awful hack for `trap` or $(trap).
6788 *
6789 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6790 * contains an example where "trap" is executed in a subshell:
6791 *
6792 * save_traps=$(trap)
6793 * ...
6794 * eval "$save_traps"
6795 *
6796 * Standard does not say that "trap" in subshell shall print
6797 * parent shell's traps. It only says that its output
6798 * must have suitable form, but then, in the above example
6799 * (which is not supposed to be normative), it implies that.
6800 *
6801 * bash (and probably other shell) does implement it
6802 * (traps are reset to defaults, but "trap" still shows them),
6803 * but as a result, "trap" logic is hopelessly messed up:
6804 *
6805 * # trap
6806 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6807 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6808 * # true | trap <--- trap is in subshell - no output (ditto)
6809 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6810 * trap -- 'echo Ho' SIGWINCH
6811 * # echo `(trap)` <--- in subshell in subshell - output
6812 * trap -- 'echo Ho' SIGWINCH
6813 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6814 * trap -- 'echo Ho' SIGWINCH
6815 *
6816 * The rules when to forget and when to not forget traps
6817 * get really complex and nonsensical.
6818 *
6819 * Our solution: ONLY bare $(trap) or `trap` is special.
6820 */
6821 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006822 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006823 && skip_whitespace(s + 4)[0] == '\0'
6824 ) {
6825 static const char *const argv[] = { NULL, NULL };
6826 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006827 fflush_all(); /* important */
6828 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006829 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006830# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006831# if BB_MMU
6832 reset_traps_to_defaults();
6833 parse_and_run_string(s);
6834 _exit(G.last_exitcode);
6835# else
6836 /* We re-execute after vfork on NOMMU. This makes this script safe:
6837 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6838 * huge=`cat BIG` # was blocking here forever
6839 * echo OK
6840 */
6841 re_execute_shell(&to_free,
6842 s,
6843 G.global_argv[0],
6844 G.global_argv + 1,
6845 NULL);
6846# endif
6847 }
6848
6849 /* parent */
6850 *pid_p = pid;
6851# if ENABLE_HUSH_FAST
6852 G.count_SIGCHLD++;
6853//bb_error_msg("[%d] fork in generate_stream_from_string:"
6854// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6855// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6856# endif
6857 enable_restore_tty_pgrp_on_exit();
6858# if !BB_MMU
6859 free(to_free);
6860# endif
6861 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006862 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006863}
6864
6865/* Return code is exit status of the process that is run. */
6866static int process_command_subs(o_string *dest, const char *s)
6867{
6868 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006869 pid_t pid;
6870 int status, ch, eol_cnt;
6871
6872 fp = generate_stream_from_string(s, &pid);
6873
6874 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006875 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006876 while ((ch = getc(fp)) != EOF) {
6877 if (ch == '\0')
6878 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006879 if (ch == '\n') {
6880 eol_cnt++;
6881 continue;
6882 }
6883 while (eol_cnt) {
6884 o_addchr(dest, '\n');
6885 eol_cnt--;
6886 }
6887 o_addQchr(dest, ch);
6888 }
6889
6890 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006891 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006892 /* We need to extract exitcode. Test case
6893 * "true; echo `sleep 1; false` $?"
6894 * should print 1 */
6895 safe_waitpid(pid, &status, 0);
6896 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6897 return WEXITSTATUS(status);
6898}
6899#endif /* ENABLE_HUSH_TICK */
6900
6901
6902static void setup_heredoc(struct redir_struct *redir)
6903{
6904 struct fd_pair pair;
6905 pid_t pid;
6906 int len, written;
6907 /* the _body_ of heredoc (misleading field name) */
6908 const char *heredoc = redir->rd_filename;
6909 char *expanded;
6910#if !BB_MMU
6911 char **to_free;
6912#endif
6913
6914 expanded = NULL;
6915 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006916 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006917 if (expanded)
6918 heredoc = expanded;
6919 }
6920 len = strlen(heredoc);
6921
6922 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6923 xpiped_pair(pair);
6924 xmove_fd(pair.rd, redir->rd_fd);
6925
6926 /* Try writing without forking. Newer kernels have
6927 * dynamically growing pipes. Must use non-blocking write! */
6928 ndelay_on(pair.wr);
6929 while (1) {
6930 written = write(pair.wr, heredoc, len);
6931 if (written <= 0)
6932 break;
6933 len -= written;
6934 if (len == 0) {
6935 close(pair.wr);
6936 free(expanded);
6937 return;
6938 }
6939 heredoc += written;
6940 }
6941 ndelay_off(pair.wr);
6942
6943 /* Okay, pipe buffer was not big enough */
6944 /* Note: we must not create a stray child (bastard? :)
6945 * for the unsuspecting parent process. Child creates a grandchild
6946 * and exits before parent execs the process which consumes heredoc
6947 * (that exec happens after we return from this function) */
6948#if !BB_MMU
6949 to_free = NULL;
6950#endif
6951 pid = xvfork();
6952 if (pid == 0) {
6953 /* child */
6954 disable_restore_tty_pgrp_on_exit();
6955 pid = BB_MMU ? xfork() : xvfork();
6956 if (pid != 0)
6957 _exit(0);
6958 /* grandchild */
6959 close(redir->rd_fd); /* read side of the pipe */
6960#if BB_MMU
6961 full_write(pair.wr, heredoc, len); /* may loop or block */
6962 _exit(0);
6963#else
6964 /* Delegate blocking writes to another process */
6965 xmove_fd(pair.wr, STDOUT_FILENO);
6966 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6967#endif
6968 }
6969 /* parent */
6970#if ENABLE_HUSH_FAST
6971 G.count_SIGCHLD++;
6972//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6973#endif
6974 enable_restore_tty_pgrp_on_exit();
6975#if !BB_MMU
6976 free(to_free);
6977#endif
6978 close(pair.wr);
6979 free(expanded);
6980 wait(NULL); /* wait till child has died */
6981}
6982
Denys Vlasenko2db74612017-07-07 22:07:28 +02006983struct squirrel {
6984 int orig_fd;
6985 int moved_to;
6986 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6987 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6988};
6989
Denys Vlasenko621fc502017-07-24 12:42:17 +02006990static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6991{
6992 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6993 sq[i].orig_fd = orig;
6994 sq[i].moved_to = moved;
6995 sq[i+1].orig_fd = -1; /* end marker */
6996 return sq;
6997}
6998
Denys Vlasenko2db74612017-07-07 22:07:28 +02006999static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
7000{
Denys Vlasenko621fc502017-07-24 12:42:17 +02007001 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007002 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007003
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007004 i = 0;
7005 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007006 /* If we collide with an already moved fd... */
7007 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007008 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007009 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
7010 if (sq[i].moved_to < 0) /* what? */
7011 xfunc_die();
7012 return sq;
7013 }
7014 if (fd == sq[i].orig_fd) {
7015 /* Example: echo Hello >/dev/null 1>&2 */
7016 debug_printf_redir("redirect_fd %d: already moved\n", fd);
7017 return sq;
7018 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007019 }
7020
Denys Vlasenko2db74612017-07-07 22:07:28 +02007021 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007022 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007023 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
7024 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02007025 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02007026 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007027}
7028
Denys Vlasenko657e9002017-07-30 23:34:04 +02007029static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
7030{
7031 int i;
7032
Denys Vlasenkod16e6122017-08-11 15:41:39 +02007033 i = 0;
7034 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007035 /* If we collide with an already moved fd... */
7036 if (fd == sq[i].orig_fd) {
7037 /* Examples:
7038 * "echo 3>FILE 3>&- 3>FILE"
7039 * "echo 3>&- 3>FILE"
7040 * No need for last redirect to insert
7041 * another "need to close 3" indicator.
7042 */
7043 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
7044 return sq;
7045 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007046 }
7047
7048 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
7049 return append_squirrel(sq, i, fd, -1);
7050}
7051
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007052/* fd: redirect wants this fd to be used (e.g. 3>file).
7053 * Move all conflicting internally used fds,
7054 * and remember them so that we can restore them later.
7055 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007056static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007057{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007058 if (avoid_fd < 9) /* the important case here is that it can be -1 */
7059 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007060
7061#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007062 if (fd == G.interactive_fd) {
7063 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007064 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02007065 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
7066 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007067 }
7068#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007069 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
7070 * (1) Redirect in a forked child. No need to save FILEs' fds,
7071 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02007072 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
7073 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007074 * "fileno(fd) = new_fd" can't be done.
7075 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007076 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007077 return 0;
7078
Denys Vlasenko2db74612017-07-07 22:07:28 +02007079 /* If this one of script's fds? */
7080 if (save_FILEs_on_redirect(fd, avoid_fd))
7081 return 1; /* yes. "we closed fd" */
7082
7083 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
7084 *sqp = add_squirrel(*sqp, fd, avoid_fd);
7085 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007086}
7087
Denys Vlasenko2db74612017-07-07 22:07:28 +02007088static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007089{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007090 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007091 int i;
7092 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007093 if (sq[i].moved_to >= 0) {
7094 /* We simply die on error */
7095 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7096 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7097 } else {
7098 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7099 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7100 close(sq[i].orig_fd);
7101 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007102 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007103 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007104 }
7105
Denys Vlasenko2db74612017-07-07 22:07:28 +02007106 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007107
7108 restore_redirected_FILEs();
7109}
7110
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007111#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007112static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007113{
7114 if (G_interactive_fd)
7115 close(G_interactive_fd);
7116 close_all_FILE_list();
7117}
7118#endif
7119
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007120static int internally_opened_fd(int fd, struct squirrel *sq)
7121{
7122 int i;
7123
7124#if ENABLE_HUSH_INTERACTIVE
7125 if (fd == G.interactive_fd)
7126 return 1;
7127#endif
7128 /* If this one of script's fds? */
7129 if (fd_in_FILEs(fd))
7130 return 1;
7131
7132 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7133 if (fd == sq[i].moved_to)
7134 return 1;
7135 }
7136 return 0;
7137}
7138
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007139/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7140 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007141static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007142{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007143 struct redir_struct *redir;
7144
7145 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007146 int newfd;
7147 int closed;
7148
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007149 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007150 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007151 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007152 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7153 * of the heredoc */
7154 debug_printf_parse("set heredoc '%s'\n",
7155 redir->rd_filename);
7156 setup_heredoc(redir);
7157 continue;
7158 }
7159
7160 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007161 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007162 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007163 int mode;
7164
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007165 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007166 /*
7167 * Examples:
7168 * "cmd >" (no filename)
7169 * "cmd > <file" (2nd redirect starts too early)
7170 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007171 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007172 continue;
7173 }
7174 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007175 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007176 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007177 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007178 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007179 /* Error message from open_or_warn can be lost
7180 * if stderr has been redirected, but bash
7181 * and ash both lose it as well
7182 * (though zsh doesn't!)
7183 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007184 return 1;
7185 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007186 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007187 /* open() gave us precisely the fd we wanted.
7188 * This means that this fd was not busy
7189 * (not opened to anywhere).
7190 * Remember to close it on restore:
7191 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007192 *sqp = add_squirrel_closed(*sqp, newfd);
7193 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007194 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007195 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007196 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7197 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007198 }
7199
Denys Vlasenko657e9002017-07-30 23:34:04 +02007200 if (newfd == redir->rd_fd)
7201 continue;
7202
7203 /* if "N>FILE": move newfd to redir->rd_fd */
7204 /* if "N>&M": dup newfd to redir->rd_fd */
7205 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7206
7207 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7208 if (newfd == REDIRFD_CLOSE) {
7209 /* "N>&-" means "close me" */
7210 if (!closed) {
7211 /* ^^^ optimization: saving may already
7212 * have closed it. If not... */
7213 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007214 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007215 /* Sometimes we do another close on restore, getting EBADF.
7216 * Consider "echo 3>FILE 3>&-"
7217 * first redirect remembers "need to close 3",
7218 * and second redirect closes 3! Restore code then closes 3 again.
7219 */
7220 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007221 /* if newfd is a script fd or saved fd, simulate EBADF */
7222 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7223 //errno = EBADF;
7224 //bb_perror_msg_and_die("can't duplicate file descriptor");
7225 newfd = -1; /* same effect as code above */
7226 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007227 xdup2(newfd, redir->rd_fd);
7228 if (redir->rd_dup == REDIRFD_TO_FILE)
7229 /* "rd_fd > FILE" */
7230 close(newfd);
7231 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007232 }
7233 }
7234 return 0;
7235}
7236
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007237static char *find_in_path(const char *arg)
7238{
7239 char *ret = NULL;
7240 const char *PATH = get_local_var_value("PATH");
7241
7242 if (!PATH)
7243 return NULL;
7244
7245 while (1) {
7246 const char *end = strchrnul(PATH, ':');
7247 int sz = end - PATH; /* must be int! */
7248
7249 free(ret);
7250 if (sz != 0) {
7251 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7252 } else {
7253 /* We have xxx::yyyy in $PATH,
7254 * it means "use current dir" */
7255 ret = xstrdup(arg);
7256 }
7257 if (access(ret, F_OK) == 0)
7258 break;
7259
7260 if (*end == '\0') {
7261 free(ret);
7262 return NULL;
7263 }
7264 PATH = end + 1;
7265 }
7266
7267 return ret;
7268}
7269
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007270static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007271 const struct built_in_command *x,
7272 const struct built_in_command *end)
7273{
7274 while (x != end) {
7275 if (strcmp(name, x->b_cmd) != 0) {
7276 x++;
7277 continue;
7278 }
7279 debug_printf_exec("found builtin '%s'\n", name);
7280 return x;
7281 }
7282 return NULL;
7283}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007284static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007285{
7286 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7287}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007288static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007289{
7290 const struct built_in_command *x = find_builtin1(name);
7291 if (x)
7292 return x;
7293 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7294}
7295
7296#if ENABLE_HUSH_FUNCTIONS
7297static struct function **find_function_slot(const char *name)
7298{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007299 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007300 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007301
7302 while ((funcp = *funcpp) != NULL) {
7303 if (strcmp(name, funcp->name) == 0) {
7304 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007305 break;
7306 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007307 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007308 }
7309 return funcpp;
7310}
7311
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007312static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007313{
7314 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007315 return funcp;
7316}
7317
7318/* Note: takes ownership on name ptr */
7319static struct function *new_function(char *name)
7320{
7321 struct function **funcpp = find_function_slot(name);
7322 struct function *funcp = *funcpp;
7323
7324 if (funcp != NULL) {
7325 struct command *cmd = funcp->parent_cmd;
7326 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7327 if (!cmd) {
7328 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7329 free(funcp->name);
7330 /* Note: if !funcp->body, do not free body_as_string!
7331 * This is a special case of "-F name body" function:
7332 * body_as_string was not malloced! */
7333 if (funcp->body) {
7334 free_pipe_list(funcp->body);
7335# if !BB_MMU
7336 free(funcp->body_as_string);
7337# endif
7338 }
7339 } else {
7340 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7341 cmd->argv[0] = funcp->name;
7342 cmd->group = funcp->body;
7343# if !BB_MMU
7344 cmd->group_as_string = funcp->body_as_string;
7345# endif
7346 }
7347 } else {
7348 debug_printf_exec("remembering new function '%s'\n", name);
7349 funcp = *funcpp = xzalloc(sizeof(*funcp));
7350 /*funcp->next = NULL;*/
7351 }
7352
7353 funcp->name = name;
7354 return funcp;
7355}
7356
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007357# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007358static void unset_func(const char *name)
7359{
7360 struct function **funcpp = find_function_slot(name);
7361 struct function *funcp = *funcpp;
7362
7363 if (funcp != NULL) {
7364 debug_printf_exec("freeing function '%s'\n", funcp->name);
7365 *funcpp = funcp->next;
7366 /* funcp is unlinked now, deleting it.
7367 * Note: if !funcp->body, the function was created by
7368 * "-F name body", do not free ->body_as_string
7369 * and ->name as they were not malloced. */
7370 if (funcp->body) {
7371 free_pipe_list(funcp->body);
7372 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007373# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007374 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007375# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007376 }
7377 free(funcp);
7378 }
7379}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007380# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007381
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007382static void remove_nested_vars(void)
7383{
7384 struct variable *cur;
7385 struct variable **cur_pp;
7386
7387 cur_pp = &G.top_var;
7388 while ((cur = *cur_pp) != NULL) {
7389 if (cur->var_nest_level <= G.var_nest_level) {
7390 cur_pp = &cur->next;
7391 continue;
7392 }
7393 /* Unexport */
7394 if (cur->flg_export) {
7395 debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7396 bb_unsetenv(cur->varstr);
7397 }
7398 /* Remove from global list */
7399 *cur_pp = cur->next;
7400 /* Free */
7401 if (!cur->max_len) {
7402 debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
7403 free(cur->varstr);
7404 }
7405 free(cur);
7406 }
7407}
7408
7409static void enter_var_nest_level(void)
7410{
7411 G.var_nest_level++;
7412 debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
7413
7414 /* Try: f() { echo -n .; f; }; f
7415 * struct variable::var_nest_level is uint16_t,
7416 * thus limiting recursion to < 2^16.
7417 * In any case, with 8 Mbyte stack SEGV happens
7418 * not too long after 2^16 recursions anyway.
7419 */
7420 if (G.var_nest_level > 0xff00)
7421 bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
7422}
7423
7424static void leave_var_nest_level(void)
7425{
7426 G.var_nest_level--;
7427 debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
7428 if (HUSH_DEBUG && (int)G.var_nest_level < 0)
7429 bb_error_msg_and_die("BUG: nesting underflow");
7430
7431 remove_nested_vars();
7432}
7433
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007434# if BB_MMU
7435#define exec_function(to_free, funcp, argv) \
7436 exec_function(funcp, argv)
7437# endif
7438static void exec_function(char ***to_free,
7439 const struct function *funcp,
7440 char **argv) NORETURN;
7441static void exec_function(char ***to_free,
7442 const struct function *funcp,
7443 char **argv)
7444{
7445# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007446 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007447
7448 argv[0] = G.global_argv[0];
7449 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007450 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007451
7452// Example when we are here: "cmd | func"
7453// func will run with saved-redirect fds open.
7454// $ f() { echo /proc/self/fd/*; }
7455// $ true | f
7456// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7457// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7458// Same in script:
7459// $ . ./SCRIPT
7460// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7461// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7462// They are CLOEXEC so external programs won't see them, but
7463// for "more correctness" we might want to close those extra fds here:
7464//? close_saved_fds_and_FILE_fds();
7465
Denys Vlasenko332e4112018-04-04 22:32:59 +02007466 /* "we are in a function, ok to use return" */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007467 G_flag_return_in_progress = -1;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007468 enter_var_nest_level();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007469 IF_HUSH_LOCAL(G.func_nest_level++;)
7470
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007471 /* On MMU, funcp->body is always non-NULL */
7472 n = run_list(funcp->body);
7473 fflush_all();
7474 _exit(n);
7475# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007476//? close_saved_fds_and_FILE_fds();
7477
7478//TODO: check whether "true | func_with_return" works
7479
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007480 re_execute_shell(to_free,
7481 funcp->body_as_string,
7482 G.global_argv[0],
7483 argv + 1,
7484 NULL);
7485# endif
7486}
7487
7488static int run_function(const struct function *funcp, char **argv)
7489{
7490 int rc;
7491 save_arg_t sv;
7492 smallint sv_flg;
7493
7494 save_and_replace_G_args(&sv, argv);
7495
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007496 /* "We are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007497 sv_flg = G_flag_return_in_progress;
7498 G_flag_return_in_progress = -1;
Denys Vlasenko332e4112018-04-04 22:32:59 +02007499
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007500 /* Make "local" variables properly shadow previous ones */
7501 IF_HUSH_LOCAL(enter_var_nest_level();)
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007502 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007503
7504 /* On MMU, funcp->body is always non-NULL */
7505# if !BB_MMU
7506 if (!funcp->body) {
7507 /* Function defined by -F */
7508 parse_and_run_string(funcp->body_as_string);
7509 rc = G.last_exitcode;
7510 } else
7511# endif
7512 {
7513 rc = run_list(funcp->body);
7514 }
7515
Denys Vlasenko332e4112018-04-04 22:32:59 +02007516 IF_HUSH_LOCAL(G.func_nest_level--;)
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02007517 IF_HUSH_LOCAL(leave_var_nest_level();)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007518
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007519 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007520
7521 restore_G_args(&sv, argv);
7522
7523 return rc;
7524}
7525#endif /* ENABLE_HUSH_FUNCTIONS */
7526
7527
7528#if BB_MMU
7529#define exec_builtin(to_free, x, argv) \
7530 exec_builtin(x, argv)
7531#else
7532#define exec_builtin(to_free, x, argv) \
7533 exec_builtin(to_free, argv)
7534#endif
7535static void exec_builtin(char ***to_free,
7536 const struct built_in_command *x,
7537 char **argv) NORETURN;
7538static void exec_builtin(char ***to_free,
7539 const struct built_in_command *x,
7540 char **argv)
7541{
7542#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007543 int rcode;
7544 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007545//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007546 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007547 fflush_all();
7548 _exit(rcode);
7549#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007550 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007551 /* On NOMMU, we must never block!
7552 * Example: { sleep 99 | read line; } & echo Ok
7553 */
7554 re_execute_shell(to_free,
7555 argv[0],
7556 G.global_argv[0],
7557 G.global_argv + 1,
7558 argv);
7559#endif
7560}
7561
7562
7563static void execvp_or_die(char **argv) NORETURN;
7564static void execvp_or_die(char **argv)
7565{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007566 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007567 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007568 /* Don't propagate SIG_IGN to the child */
7569 if (SPECIAL_JOBSTOP_SIGS != 0)
7570 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007571 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007572 e = 2;
7573 if (errno == EACCES) e = 126;
7574 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007575 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007576 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007577}
7578
7579#if ENABLE_HUSH_MODE_X
7580static void dump_cmd_in_x_mode(char **argv)
7581{
7582 if (G_x_mode && argv) {
7583 /* We want to output the line in one write op */
7584 char *buf, *p;
7585 int len;
7586 int n;
7587
7588 len = 3;
7589 n = 0;
7590 while (argv[n])
7591 len += strlen(argv[n++]) + 1;
7592 buf = xmalloc(len);
7593 buf[0] = '+';
7594 p = buf + 1;
7595 n = 0;
7596 while (argv[n])
7597 p += sprintf(p, " %s", argv[n++]);
7598 *p++ = '\n';
7599 *p = '\0';
7600 fputs(buf, stderr);
7601 free(buf);
7602 }
7603}
7604#else
7605# define dump_cmd_in_x_mode(argv) ((void)0)
7606#endif
7607
Denys Vlasenko57000292018-01-12 14:41:45 +01007608#if ENABLE_HUSH_COMMAND
7609static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7610{
7611 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007612
Denys Vlasenko57000292018-01-12 14:41:45 +01007613 if (!opt_vV)
7614 return;
7615
7616 to_free = NULL;
7617 if (!explanation) {
7618 char *path = getenv("PATH");
7619 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007620 if (!explanation)
7621 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007622 if (opt_vV != 'V')
7623 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7624 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007625 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007626 free(to_free);
7627 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007628 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007629}
7630#else
7631# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7632#endif
7633
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007634#if BB_MMU
7635#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7636 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7637#define pseudo_exec(nommu_save, command, argv_expanded) \
7638 pseudo_exec(command, argv_expanded)
7639#endif
7640
7641/* Called after [v]fork() in run_pipe, or from builtin_exec.
7642 * Never returns.
7643 * Don't exit() here. If you don't exec, use _exit instead.
7644 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007645 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007646 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007647static void pseudo_exec_argv(nommu_save_t *nommu_save,
7648 char **argv, int assignment_cnt,
7649 char **argv_expanded) NORETURN;
7650static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7651 char **argv, int assignment_cnt,
7652 char **argv_expanded)
7653{
Denys Vlasenko57000292018-01-12 14:41:45 +01007654 const struct built_in_command *x;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007655 struct variable **sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007656 char **new_env;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007657 IF_HUSH_COMMAND(char opt_vV = 0;)
7658 IF_HUSH_FUNCTIONS(const struct function *funcp;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007659
7660 new_env = expand_assignments(argv, assignment_cnt);
7661 dump_cmd_in_x_mode(new_env);
7662
7663 if (!argv[assignment_cnt]) {
7664 /* Case when we are here: ... | var=val | ...
7665 * (note that we do not exit early, i.e., do not optimize out
7666 * expand_assignments(): think about ... | var=`sleep 1` | ...
7667 */
7668 free_strings(new_env);
7669 _exit(EXIT_SUCCESS);
7670 }
7671
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007672 sv_shadowed = G.shadowed_vars_pp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007673#if BB_MMU
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007674 G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007675#else
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007676 G.shadowed_vars_pp = &nommu_save->old_vars;
Denys Vlasenko9db344a2018-04-09 19:05:11 +02007677 G.var_nest_level++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007678#endif
Denys Vlasenko929a41d2018-04-05 14:09:14 +02007679 set_vars_and_save_old(new_env);
7680 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007681
7682 if (argv_expanded) {
7683 argv = argv_expanded;
7684 } else {
7685 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7686#if !BB_MMU
7687 nommu_save->argv = argv;
7688#endif
7689 }
7690 dump_cmd_in_x_mode(argv);
7691
7692#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7693 if (strchr(argv[0], '/') != NULL)
7694 goto skip;
7695#endif
7696
Denys Vlasenko75481d32017-07-31 05:27:09 +02007697#if ENABLE_HUSH_FUNCTIONS
7698 /* Check if the command matches any functions (this goes before bltins) */
Denys Vlasenko34f6b122018-04-05 11:30:17 +02007699 funcp = find_function(argv[0]);
7700 if (funcp)
7701 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denys Vlasenko75481d32017-07-31 05:27:09 +02007702#endif
7703
Denys Vlasenko57000292018-01-12 14:41:45 +01007704#if ENABLE_HUSH_COMMAND
7705 /* "command BAR": run BAR without looking it up among functions
7706 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7707 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7708 */
7709 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7710 char *p;
7711
7712 argv++;
7713 p = *argv;
7714 if (p[0] != '-' || !p[1])
7715 continue; /* bash allows "command command command [-OPT] BAR" */
7716
7717 for (;;) {
7718 p++;
7719 switch (*p) {
7720 case '\0':
7721 argv++;
7722 p = *argv;
7723 if (p[0] != '-' || !p[1])
7724 goto after_opts;
7725 continue; /* next arg is also -opts, process it too */
7726 case 'v':
7727 case 'V':
7728 opt_vV = *p;
7729 continue;
7730 default:
7731 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7732 }
7733 }
7734 }
7735 after_opts:
7736# if ENABLE_HUSH_FUNCTIONS
7737 if (opt_vV && find_function(argv[0]))
7738 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7739# endif
7740#endif
7741
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007742 /* Check if the command matches any of the builtins.
7743 * Depending on context, this might be redundant. But it's
7744 * easier to waste a few CPU cycles than it is to figure out
7745 * if this is one of those cases.
7746 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007747 /* Why "BB_MMU ? :" difference in logic? -
7748 * On NOMMU, it is more expensive to re-execute shell
7749 * just in order to run echo or test builtin.
7750 * It's better to skip it here and run corresponding
7751 * non-builtin later. */
7752 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7753 if (x) {
7754 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7755 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007756 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007757
7758#if ENABLE_FEATURE_SH_STANDALONE
7759 /* Check if the command matches any busybox applets */
7760 {
7761 int a = find_applet_by_name(argv[0]);
7762 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007763 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007764# if BB_MMU /* see above why on NOMMU it is not allowed */
7765 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007766 /* Do not leak open fds from opened script files etc.
7767 * Testcase: interactive "ls -l /proc/self/fd"
7768 * should not show tty fd open.
7769 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007770 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007771//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007772//This casuses test failures in
7773//redir_children_should_not_see_saved_fd_2.tests
7774//redir_children_should_not_see_saved_fd_3.tests
7775//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007776 /* Without this, "rm -i FILE" can't be ^C'ed: */
7777 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007778 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007779 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007780 }
7781# endif
7782 /* Re-exec ourselves */
7783 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007784 /* Don't propagate SIG_IGN to the child */
7785 if (SPECIAL_JOBSTOP_SIGS != 0)
7786 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007787 execv(bb_busybox_exec_path, argv);
7788 /* If they called chroot or otherwise made the binary no longer
7789 * executable, fall through */
7790 }
7791 }
7792#endif
7793
7794#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7795 skip:
7796#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007797 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007798 execvp_or_die(argv);
7799}
7800
7801/* Called after [v]fork() in run_pipe
7802 */
7803static void pseudo_exec(nommu_save_t *nommu_save,
7804 struct command *command,
7805 char **argv_expanded) NORETURN;
7806static void pseudo_exec(nommu_save_t *nommu_save,
7807 struct command *command,
7808 char **argv_expanded)
7809{
Denys Vlasenko49015a62018-04-03 13:02:43 +02007810#if ENABLE_HUSH_FUNCTIONS
7811 if (command->cmd_type == CMD_FUNCDEF) {
7812 /* Ignore funcdefs in pipes:
7813 * true | f() { cmd }
7814 */
7815 _exit(0);
7816 }
7817#endif
7818
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007819 if (command->argv) {
7820 pseudo_exec_argv(nommu_save, command->argv,
7821 command->assignment_cnt, argv_expanded);
7822 }
7823
7824 if (command->group) {
7825 /* Cases when we are here:
7826 * ( list )
7827 * { list } &
7828 * ... | ( list ) | ...
7829 * ... | { list } | ...
7830 */
7831#if BB_MMU
7832 int rcode;
7833 debug_printf_exec("pseudo_exec: run_list\n");
7834 reset_traps_to_defaults();
7835 rcode = run_list(command->group);
7836 /* OK to leak memory by not calling free_pipe_list,
7837 * since this process is about to exit */
7838 _exit(rcode);
7839#else
7840 re_execute_shell(&nommu_save->argv_from_re_execing,
7841 command->group_as_string,
7842 G.global_argv[0],
7843 G.global_argv + 1,
7844 NULL);
7845#endif
7846 }
7847
7848 /* Case when we are here: ... | >file */
7849 debug_printf_exec("pseudo_exec'ed null command\n");
7850 _exit(EXIT_SUCCESS);
7851}
7852
7853#if ENABLE_HUSH_JOB
7854static const char *get_cmdtext(struct pipe *pi)
7855{
7856 char **argv;
7857 char *p;
7858 int len;
7859
7860 /* This is subtle. ->cmdtext is created only on first backgrounding.
7861 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7862 * On subsequent bg argv is trashed, but we won't use it */
7863 if (pi->cmdtext)
7864 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007865
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007866 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007867 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007868 pi->cmdtext = xzalloc(1);
7869 return pi->cmdtext;
7870 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007871 len = 0;
7872 do {
7873 len += strlen(*argv) + 1;
7874 } while (*++argv);
7875 p = xmalloc(len);
7876 pi->cmdtext = p;
7877 argv = pi->cmds[0].argv;
7878 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007879 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007880 *p++ = ' ';
7881 } while (*++argv);
7882 p[-1] = '\0';
7883 return pi->cmdtext;
7884}
7885
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007886static void remove_job_from_table(struct pipe *pi)
7887{
7888 struct pipe *prev_pipe;
7889
7890 if (pi == G.job_list) {
7891 G.job_list = pi->next;
7892 } else {
7893 prev_pipe = G.job_list;
7894 while (prev_pipe->next != pi)
7895 prev_pipe = prev_pipe->next;
7896 prev_pipe->next = pi->next;
7897 }
7898 G.last_jobid = 0;
7899 if (G.job_list)
7900 G.last_jobid = G.job_list->jobid;
7901}
7902
7903static void delete_finished_job(struct pipe *pi)
7904{
7905 remove_job_from_table(pi);
7906 free_pipe(pi);
7907}
7908
7909static void clean_up_last_dead_job(void)
7910{
7911 if (G.job_list && !G.job_list->alive_cmds)
7912 delete_finished_job(G.job_list);
7913}
7914
Denys Vlasenko16096292017-07-10 10:00:28 +02007915static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007916{
7917 struct pipe *job, **jobp;
7918 int i;
7919
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007920 clean_up_last_dead_job();
7921
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007922 /* Find the end of the list, and find next job ID to use */
7923 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007924 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007925 while ((job = *jobp) != NULL) {
7926 if (job->jobid > i)
7927 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007928 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007929 }
7930 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007931
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007932 /* Create a new job struct at the end */
7933 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007934 job->next = NULL;
7935 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7936 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7937 for (i = 0; i < pi->num_cmds; i++) {
7938 job->cmds[i].pid = pi->cmds[i].pid;
7939 /* all other fields are not used and stay zero */
7940 }
7941 job->cmdtext = xstrdup(get_cmdtext(pi));
7942
7943 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007944 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007945 G.last_jobid = job->jobid;
7946}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007947#endif /* JOB */
7948
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007949static int job_exited_or_stopped(struct pipe *pi)
7950{
7951 int rcode, i;
7952
7953 if (pi->alive_cmds != pi->stopped_cmds)
7954 return -1;
7955
7956 /* All processes in fg pipe have exited or stopped */
7957 rcode = 0;
7958 i = pi->num_cmds;
7959 while (--i >= 0) {
7960 rcode = pi->cmds[i].cmd_exitcode;
7961 /* usually last process gives overall exitstatus,
7962 * but with "set -o pipefail", last *failed* process does */
7963 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7964 break;
7965 }
7966 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7967 return rcode;
7968}
7969
Denys Vlasenko7e675362016-10-28 21:57:31 +02007970static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007971{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007972#if ENABLE_HUSH_JOB
7973 struct pipe *pi;
7974#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007975 int i, dead;
7976
7977 dead = WIFEXITED(status) || WIFSIGNALED(status);
7978
7979#if DEBUG_JOBS
7980 if (WIFSTOPPED(status))
7981 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7982 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7983 if (WIFSIGNALED(status))
7984 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7985 childpid, WTERMSIG(status), WEXITSTATUS(status));
7986 if (WIFEXITED(status))
7987 debug_printf_jobs("pid %d exited, exitcode %d\n",
7988 childpid, WEXITSTATUS(status));
7989#endif
7990 /* Were we asked to wait for a fg pipe? */
7991 if (fg_pipe) {
7992 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007993
Denys Vlasenko7e675362016-10-28 21:57:31 +02007994 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007995 int rcode;
7996
Denys Vlasenko7e675362016-10-28 21:57:31 +02007997 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7998 if (fg_pipe->cmds[i].pid != childpid)
7999 continue;
8000 if (dead) {
8001 int ex;
8002 fg_pipe->cmds[i].pid = 0;
8003 fg_pipe->alive_cmds--;
8004 ex = WEXITSTATUS(status);
8005 /* bash prints killer signal's name for *last*
8006 * process in pipe (prints just newline for SIGINT/SIGPIPE).
8007 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
8008 */
8009 if (WIFSIGNALED(status)) {
8010 int sig = WTERMSIG(status);
8011 if (i == fg_pipe->num_cmds-1)
8012 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
8013 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
8014 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
8015 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
8016 * Maybe we need to use sig | 128? */
8017 ex = sig + 128;
8018 }
8019 fg_pipe->cmds[i].cmd_exitcode = ex;
8020 } else {
8021 fg_pipe->stopped_cmds++;
8022 }
8023 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
8024 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008025 rcode = job_exited_or_stopped(fg_pipe);
8026 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008027/* Note: *non-interactive* bash does not continue if all processes in fg pipe
8028 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
8029 * and "killall -STOP cat" */
8030 if (G_interactive_fd) {
8031#if ENABLE_HUSH_JOB
8032 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02008033 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008034#endif
8035 return rcode;
8036 }
8037 if (fg_pipe->alive_cmds == 0)
8038 return rcode;
8039 }
8040 /* There are still running processes in the fg_pipe */
8041 return -1;
8042 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02008043 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02008044 }
8045
8046#if ENABLE_HUSH_JOB
8047 /* We were asked to wait for bg or orphaned children */
8048 /* No need to remember exitcode in this case */
8049 for (pi = G.job_list; pi; pi = pi->next) {
8050 for (i = 0; i < pi->num_cmds; i++) {
8051 if (pi->cmds[i].pid == childpid)
8052 goto found_pi_and_prognum;
8053 }
8054 }
8055 /* Happens when shell is used as init process (init=/bin/sh) */
8056 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
8057 return -1; /* this wasn't a process from fg_pipe */
8058
8059 found_pi_and_prognum:
8060 if (dead) {
8061 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02008062 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008063 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02008064 rcode = 128 + WTERMSIG(status);
8065 pi->cmds[i].cmd_exitcode = rcode;
8066 if (G.last_bg_pid == pi->cmds[i].pid)
8067 G.last_bg_pid_exitcode = rcode;
8068 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008069 pi->alive_cmds--;
8070 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008071 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008072 printf(JOB_STATUS_FORMAT, pi->jobid,
8073 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02008074 delete_finished_job(pi);
8075 } else {
8076/*
8077 * bash deletes finished jobs from job table only in interactive mode,
8078 * after "jobs" cmd, or if pid of a new process matches one of the old ones
8079 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
8080 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
8081 * We only retain one "dead" job, if it's the single job on the list.
8082 * This covers most of real-world scenarios where this is useful.
8083 */
8084 if (pi != G.job_list)
8085 delete_finished_job(pi);
8086 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008087 }
8088 } else {
8089 /* child stopped */
8090 pi->stopped_cmds++;
8091 }
8092#endif
8093 return -1; /* this wasn't a process from fg_pipe */
8094}
8095
8096/* Check to see if any processes have exited -- if they have,
8097 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008098 *
8099 * If non-NULL fg_pipe: wait for its completion or stop.
8100 * Return its exitcode or zero if stopped.
8101 *
8102 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
8103 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
8104 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8105 * or 0 if no children changed status.
8106 *
8107 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
8108 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
8109 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02008110 */
8111static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
8112{
8113 int attributes;
8114 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008115 int rcode = 0;
8116
8117 debug_printf_jobs("checkjobs %p\n", fg_pipe);
8118
8119 attributes = WUNTRACED;
8120 if (fg_pipe == NULL)
8121 attributes |= WNOHANG;
8122
8123 errno = 0;
8124#if ENABLE_HUSH_FAST
8125 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
8126//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
8127//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8128 /* There was neither fork nor SIGCHLD since last waitpid */
8129 /* Avoid doing waitpid syscall if possible */
8130 if (!G.we_have_children) {
8131 errno = ECHILD;
8132 return -1;
8133 }
8134 if (fg_pipe == NULL) { /* is WNOHANG set? */
8135 /* We have children, but they did not exit
8136 * or stop yet (we saw no SIGCHLD) */
8137 return 0;
8138 }
8139 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8140 }
8141#endif
8142
8143/* Do we do this right?
8144 * bash-3.00# sleep 20 | false
8145 * <ctrl-Z pressed>
8146 * [3]+ Stopped sleep 20 | false
8147 * bash-3.00# echo $?
8148 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8149 * [hush 1.14.0: yes we do it right]
8150 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008151 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008152 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008153#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008154 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008155 i = G.count_SIGCHLD;
8156#endif
8157 childpid = waitpid(-1, &status, attributes);
8158 if (childpid <= 0) {
8159 if (childpid && errno != ECHILD)
8160 bb_perror_msg("waitpid");
8161#if ENABLE_HUSH_FAST
8162 else { /* Until next SIGCHLD, waitpid's are useless */
8163 G.we_have_children = (childpid == 0);
8164 G.handled_SIGCHLD = i;
8165//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8166 }
8167#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008168 /* ECHILD (no children), or 0 (no change in children status) */
8169 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008170 break;
8171 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008172 rcode = process_wait_result(fg_pipe, childpid, status);
8173 if (rcode >= 0) {
8174 /* fg_pipe exited or stopped */
8175 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008176 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008177 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008178 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008179 rcode = WEXITSTATUS(status);
8180 if (WIFSIGNALED(status))
8181 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008182 if (WIFSTOPPED(status))
8183 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8184 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008185 rcode++;
8186 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008187 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008188 /* This wasn't one of our processes, or */
8189 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008190 } /* while (waitpid succeeds)... */
8191
8192 return rcode;
8193}
8194
8195#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008196static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008197{
8198 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008199 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008200 if (G_saved_tty_pgrp) {
8201 /* Job finished, move the shell to the foreground */
8202 p = getpgrp(); /* our process group id */
8203 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8204 tcsetpgrp(G_interactive_fd, p);
8205 }
8206 return rcode;
8207}
8208#endif
8209
8210/* Start all the jobs, but don't wait for anything to finish.
8211 * See checkjobs().
8212 *
8213 * Return code is normally -1, when the caller has to wait for children
8214 * to finish to determine the exit status of the pipe. If the pipe
8215 * is a simple builtin command, however, the action is done by the
8216 * time run_pipe returns, and the exit code is provided as the
8217 * return value.
8218 *
8219 * Returns -1 only if started some children. IOW: we have to
8220 * mask out retvals of builtins etc with 0xff!
8221 *
8222 * The only case when we do not need to [v]fork is when the pipe
8223 * is single, non-backgrounded, non-subshell command. Examples:
8224 * cmd ; ... { list } ; ...
8225 * cmd && ... { list } && ...
8226 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008227 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008228 * or (if SH_STANDALONE) an applet, and we can run the { list }
8229 * with run_list. If it isn't one of these, we fork and exec cmd.
8230 *
8231 * Cases when we must fork:
8232 * non-single: cmd | cmd
8233 * backgrounded: cmd & { list } &
8234 * subshell: ( list ) [&]
8235 */
8236#if !ENABLE_HUSH_MODE_X
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008237#define redirect_and_varexp_helper(old_vars_p, command, squirrel, argv_expanded) \
8238 redirect_and_varexp_helper(old_vars_p, command, squirrel)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008239#endif
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008240static int redirect_and_varexp_helper(
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008241 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008242 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008243 char **argv_expanded)
8244{
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008245 /* Assignments occur before redirects. Try:
8246 * a=`sleep 1` sleep 2 3>/qwe/rty
8247 */
8248
8249 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8250 dump_cmd_in_x_mode(new_env);
8251 dump_cmd_in_x_mode(argv_expanded);
8252 /* this takes ownership of new_env[i] elements, and frees new_env: */
8253 set_vars_and_save_old(new_env);
8254
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008255 /* setup_redirects acts on file descriptors, not FILEs.
8256 * This is perfect for work that comes after exec().
8257 * Is it really safe for inline use? Experimentally,
8258 * things seem to work. */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008259 return setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008260}
8261static NOINLINE int run_pipe(struct pipe *pi)
8262{
8263 static const char *const null_ptr = NULL;
8264
8265 int cmd_no;
8266 int next_infd;
8267 struct command *command;
8268 char **argv_expanded;
8269 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008270 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008271 int rcode;
8272
8273 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8274 debug_enter();
8275
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008276 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8277 * Result should be 3 lines: q w e, qwe, q w e
8278 */
8279 G.ifs = get_local_var_value("IFS");
8280 if (!G.ifs)
8281 G.ifs = defifs;
8282
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008283 IF_HUSH_JOB(pi->pgrp = -1;)
8284 pi->stopped_cmds = 0;
8285 command = &pi->cmds[0];
8286 argv_expanded = NULL;
8287
8288 if (pi->num_cmds != 1
8289 || pi->followup == PIPE_BG
8290 || command->cmd_type == CMD_SUBSHELL
8291 ) {
8292 goto must_fork;
8293 }
8294
8295 pi->alive_cmds = 1;
8296
8297 debug_printf_exec(": group:%p argv:'%s'\n",
8298 command->group, command->argv ? command->argv[0] : "NONE");
8299
8300 if (command->group) {
8301#if ENABLE_HUSH_FUNCTIONS
8302 if (command->cmd_type == CMD_FUNCDEF) {
8303 /* "executing" func () { list } */
8304 struct function *funcp;
8305
8306 funcp = new_function(command->argv[0]);
8307 /* funcp->name is already set to argv[0] */
8308 funcp->body = command->group;
8309# if !BB_MMU
8310 funcp->body_as_string = command->group_as_string;
8311 command->group_as_string = NULL;
8312# endif
8313 command->group = NULL;
8314 command->argv[0] = NULL;
8315 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8316 funcp->parent_cmd = command;
8317 command->child_func = funcp;
8318
8319 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8320 debug_leave();
8321 return EXIT_SUCCESS;
8322 }
8323#endif
8324 /* { list } */
8325 debug_printf("non-subshell group\n");
8326 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008327 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008328 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008329//FIXME: we need to pass squirrel down into run_list()
8330//for SH_STANDALONE case, or else this construct:
8331// { find /proc/self/fd; true; } >FILE; cmd2
8332//has no way of closing saved fd#1 for "find",
8333//and in SH_STANDALONE mode, "find" is not execed,
8334//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008335 rcode = run_list(command->group) & 0xff;
8336 }
8337 restore_redirects(squirrel);
8338 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8339 debug_leave();
8340 debug_printf_exec("run_pipe: return %d\n", rcode);
8341 return rcode;
8342 }
8343
8344 argv = command->argv ? command->argv : (char **) &null_ptr;
8345 {
8346 const struct built_in_command *x;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008347 IF_HUSH_FUNCTIONS(const struct function *funcp;)
8348 IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008349 struct variable **sv_shadowed;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008350 struct variable *old_vars;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008351
Denys Vlasenko5807e182018-02-08 19:19:04 +01008352#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008353 if (G.lineno_var)
8354 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8355#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008356
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008357 if (argv[command->assignment_cnt] == NULL) {
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008358 /* Assignments, but no command.
8359 * Ensure redirects take effect (that is, create files).
8360 * Try "a=t >file"
8361 */
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008362 unsigned i;
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008363 G.expand_exitcode = 0;
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008364 only_assignments:
Denys Vlasenko2db74612017-07-07 22:07:28 +02008365 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008366 restore_redirects(squirrel);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008367
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008368 /* Set shell variables */
8369 if (G_x_mode)
8370 bb_putchar_stderr('+');
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008371 i = 0;
8372 while (i < command->assignment_cnt) {
8373 char *p = expand_string_to_string(argv[i], /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008374 if (G_x_mode)
8375 fprintf(stderr, " %s", p);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008376 debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008377 if (set_local_var(p, /*flag:*/ 0)) {
8378 /* assignment to readonly var / putenv error? */
8379 rcode = 1;
8380 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008381 i++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008382 }
8383 if (G_x_mode)
8384 bb_putchar_stderr('\n');
8385 /* Redirect error sets $? to 1. Otherwise,
8386 * if evaluating assignment value set $?, retain it.
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008387 * Else, clear $?:
8388 * false; q=`exit 2`; echo $? - should print 2
8389 * false; x=1; echo $? - should print 0
8390 * Because of the 2nd case, we can't just use G.last_exitcode.
8391 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008392 if (rcode == 0)
Denys Vlasenko5fa05052018-04-03 11:21:13 +02008393 rcode = G.expand_exitcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008394 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8395 debug_leave();
8396 debug_printf_exec("run_pipe: return %d\n", rcode);
8397 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008398 }
8399
8400 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko11752d42018-04-03 08:20:58 +02008401#if defined(CMD_SINGLEWORD_NOGLOB)
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008402 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008403 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008404 else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008405#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008406 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008407
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008408 /* If someone gives us an empty string: `cmd with empty output` */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008409 if (!argv_expanded[0]) {
8410 free(argv_expanded);
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +02008411 /* `false` still has to set exitcode 1 */
8412 G.expand_exitcode = G.last_exitcode;
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008413 goto only_assignments;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008414 }
8415
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008416 old_vars = NULL;
8417 sv_shadowed = G.shadowed_vars_pp;
8418
Denys Vlasenko75481d32017-07-31 05:27:09 +02008419 /* Check if argv[0] matches any functions (this goes before bltins) */
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008420 IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
8421 IF_HUSH_FUNCTIONS(x = NULL;)
8422 IF_HUSH_FUNCTIONS(if (!funcp))
Denys Vlasenko75481d32017-07-31 05:27:09 +02008423 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008424 if (x || funcp) {
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008425 if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8426 debug_printf("exec with redirects only\n");
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008427 /*
8428 * Variable assignments are executed, but then "forgotten":
8429 * a=`sleep 1;echo A` exec 3>&-; echo $a
8430 * sleeps, but prints nothing.
8431 */
8432 enter_var_nest_level();
8433 G.shadowed_vars_pp = &old_vars;
8434 rcode = redirect_and_varexp_helper(command, /*squirrel:*/ NULL, argv_expanded);
8435 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008436 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008437
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008438 goto clean_up_and_ret1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008439 }
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008440
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008441 /* Bump var nesting, or this will leak exported $a:
Denys Vlasenkod358b0b2018-04-05 00:51:55 +02008442 * a=b true; env | grep ^a=
8443 */
8444 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008445 /* Collect all variables "shadowed" by helper
8446 * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
8447 * into old_vars list:
8448 */
8449 G.shadowed_vars_pp = &old_vars;
8450 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008451 if (rcode == 0) {
8452 if (!funcp) {
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008453 /* Do not collect *to old_vars list* vars shadowed
8454 * by e.g. "local VAR" builtin (collect them
8455 * in the previously nested list instead):
8456 * don't want them to be restored immediately
8457 * after "local" completes.
8458 */
8459 G.shadowed_vars_pp = sv_shadowed;
8460
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008461 debug_printf_exec(": builtin '%s' '%s'...\n",
8462 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008463 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008464 rcode = x->b_function(argv_expanded) & 0xff;
8465 fflush_all();
8466 }
8467#if ENABLE_HUSH_FUNCTIONS
8468 else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008469 debug_printf_exec(": function '%s' '%s'...\n",
8470 funcp->name, argv_expanded[1]);
8471 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008472 /*
8473 * But do collect *to old_vars list* vars shadowed
8474 * within function execution. To that end, restore
8475 * this pointer _after_ function run:
8476 */
8477 G.shadowed_vars_pp = sv_shadowed;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008478 }
8479#endif
8480 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008481 } else
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008482 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008483 int n = find_applet_by_name(argv_expanded[0]);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008484 if (n < 0 || !APPLET_IS_NOFORK(n))
8485 goto must_fork;
8486
8487 enter_var_nest_level();
Denys Vlasenko929a41d2018-04-05 14:09:14 +02008488 /* Collect all variables "shadowed" by helper into old_vars list */
8489 G.shadowed_vars_pp = &old_vars;
8490 rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
8491 G.shadowed_vars_pp = sv_shadowed;
8492
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008493 if (rcode == 0) {
8494 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8495 argv_expanded[0], argv_expanded[1]);
8496 /*
8497 * Note: signals (^C) can't interrupt here.
8498 * We remember them and they will be acted upon
8499 * after applet returns.
8500 * This makes applets which can run for a long time
8501 * and/or wait for user input ineligible for NOFORK:
8502 * for example, "yes" or "rm" (rm -i waits for input).
8503 */
8504 rcode = run_nofork_applet(n, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008505 }
Denys Vlasenko4e1dc532018-04-05 13:10:34 +02008506 } else
8507 goto must_fork;
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008508
Denys Vlasenko41d8f102018-04-05 14:41:21 +02008509 restore_redirects(squirrel);
8510 clean_up_and_ret1:
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008511 leave_var_nest_level();
8512 add_vars(old_vars);
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008513
8514 /*
8515 * Try "usleep 99999999" + ^C + "echo $?"
8516 * with FEATURE_SH_NOFORK=y.
8517 */
8518 if (!funcp) {
8519 /* It was builtin or nofork.
8520 * if this would be a real fork/execed program,
8521 * it should have died if a fatal sig was received.
8522 * But OTOH, there was no separate process,
8523 * the sig was sent to _shell_, not to non-existing
8524 * child.
8525 * Let's just handle ^C only, this one is obvious:
8526 * we aren't ok with exitcode 0 when ^C was pressed
8527 * during builtin/nofork.
8528 */
8529 if (sigismember(&G.pending_set, SIGINT))
8530 rcode = 128 + SIGINT;
8531 }
Denys Vlasenko34f6b122018-04-05 11:30:17 +02008532 free(argv_expanded);
8533 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8534 debug_leave();
8535 debug_printf_exec("run_pipe return %d\n", rcode);
8536 return rcode;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008537 }
8538
8539 must_fork:
8540 /* NB: argv_expanded may already be created, and that
8541 * might include `cmd` runs! Do not rerun it! We *must*
8542 * use argv_expanded if it's non-NULL */
8543
8544 /* Going to fork a child per each pipe member */
8545 pi->alive_cmds = 0;
8546 next_infd = 0;
8547
8548 cmd_no = 0;
8549 while (cmd_no < pi->num_cmds) {
8550 struct fd_pair pipefds;
8551#if !BB_MMU
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008552 int sv_var_nest_level = G.var_nest_level;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008553 volatile nommu_save_t nommu_save;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008554 nommu_save.old_vars = NULL;
8555 nommu_save.argv = NULL;
8556 nommu_save.argv_from_re_execing = NULL;
8557#endif
8558 command = &pi->cmds[cmd_no];
8559 cmd_no++;
8560 if (command->argv) {
8561 debug_printf_exec(": pipe member '%s' '%s'...\n",
8562 command->argv[0], command->argv[1]);
8563 } else {
8564 debug_printf_exec(": pipe member with no argv\n");
8565 }
8566
8567 /* pipes are inserted between pairs of commands */
8568 pipefds.rd = 0;
8569 pipefds.wr = 1;
8570 if (cmd_no < pi->num_cmds)
8571 xpiped_pair(pipefds);
8572
Denys Vlasenko5807e182018-02-08 19:19:04 +01008573#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008574 if (G.lineno_var)
8575 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8576#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008577
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008578 command->pid = BB_MMU ? fork() : vfork();
8579 if (!command->pid) { /* child */
8580#if ENABLE_HUSH_JOB
8581 disable_restore_tty_pgrp_on_exit();
8582 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8583
8584 /* Every child adds itself to new process group
8585 * with pgid == pid_of_first_child_in_pipe */
8586 if (G.run_list_level == 1 && G_interactive_fd) {
8587 pid_t pgrp;
8588 pgrp = pi->pgrp;
8589 if (pgrp < 0) /* true for 1st process only */
8590 pgrp = getpid();
8591 if (setpgid(0, pgrp) == 0
8592 && pi->followup != PIPE_BG
8593 && G_saved_tty_pgrp /* we have ctty */
8594 ) {
8595 /* We do it in *every* child, not just first,
8596 * to avoid races */
8597 tcsetpgrp(G_interactive_fd, pgrp);
8598 }
8599 }
8600#endif
8601 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8602 /* 1st cmd in backgrounded pipe
8603 * should have its stdin /dev/null'ed */
8604 close(0);
8605 if (open(bb_dev_null, O_RDONLY))
8606 xopen("/", O_RDONLY);
8607 } else {
8608 xmove_fd(next_infd, 0);
8609 }
8610 xmove_fd(pipefds.wr, 1);
8611 if (pipefds.rd > 1)
8612 close(pipefds.rd);
8613 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008614 * and the pipe fd (fd#1) is available for dup'ing:
8615 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8616 * of cmd1 goes into pipe.
8617 */
8618 if (setup_redirects(command, NULL)) {
8619 /* Happens when redir file can't be opened:
8620 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8621 * FOO
8622 * hush: can't open '/qwe/rty': No such file or directory
8623 * BAZ
8624 * (echo BAR is not executed, it hits _exit(1) below)
8625 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008626 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008627 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008628
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008629 /* Stores to nommu_save list of env vars putenv'ed
8630 * (NOMMU, on MMU we don't need that) */
8631 /* cast away volatility... */
8632 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8633 /* pseudo_exec() does not return */
8634 }
8635
8636 /* parent or error */
8637#if ENABLE_HUSH_FAST
8638 G.count_SIGCHLD++;
8639//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8640#endif
8641 enable_restore_tty_pgrp_on_exit();
8642#if !BB_MMU
8643 /* Clean up after vforked child */
8644 free(nommu_save.argv);
8645 free(nommu_save.argv_from_re_execing);
Denys Vlasenko9db344a2018-04-09 19:05:11 +02008646 G.var_nest_level = sv_var_nest_level;
8647 remove_nested_vars();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008648 add_vars(nommu_save.old_vars);
8649#endif
8650 free(argv_expanded);
8651 argv_expanded = NULL;
8652 if (command->pid < 0) { /* [v]fork failed */
8653 /* Clearly indicate, was it fork or vfork */
8654 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8655 } else {
8656 pi->alive_cmds++;
8657#if ENABLE_HUSH_JOB
8658 /* Second and next children need to know pid of first one */
8659 if (pi->pgrp < 0)
8660 pi->pgrp = command->pid;
8661#endif
8662 }
8663
8664 if (cmd_no > 1)
8665 close(next_infd);
8666 if (cmd_no < pi->num_cmds)
8667 close(pipefds.wr);
8668 /* Pass read (output) pipe end to next iteration */
8669 next_infd = pipefds.rd;
8670 }
8671
8672 if (!pi->alive_cmds) {
8673 debug_leave();
8674 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8675 return 1;
8676 }
8677
8678 debug_leave();
8679 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8680 return -1;
8681}
8682
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008683/* NB: called by pseudo_exec, and therefore must not modify any
8684 * global data until exec/_exit (we can be a child after vfork!) */
8685static int run_list(struct pipe *pi)
8686{
8687#if ENABLE_HUSH_CASE
8688 char *case_word = NULL;
8689#endif
8690#if ENABLE_HUSH_LOOPS
8691 struct pipe *loop_top = NULL;
8692 char **for_lcur = NULL;
8693 char **for_list = NULL;
8694#endif
8695 smallint last_followup;
8696 smalluint rcode;
8697#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8698 smalluint cond_code = 0;
8699#else
8700 enum { cond_code = 0 };
8701#endif
8702#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008703 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008704 smallint last_rword; /* ditto */
8705#endif
8706
8707 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8708 debug_enter();
8709
8710#if ENABLE_HUSH_LOOPS
8711 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008712 {
8713 struct pipe *cpipe;
8714 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8715 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8716 continue;
8717 /* current word is FOR or IN (BOLD in comments below) */
8718 if (cpipe->next == NULL) {
8719 syntax_error("malformed for");
8720 debug_leave();
8721 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8722 return 1;
8723 }
8724 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8725 if (cpipe->next->res_word == RES_DO)
8726 continue;
8727 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8728 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8729 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8730 ) {
8731 syntax_error("malformed for");
8732 debug_leave();
8733 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8734 return 1;
8735 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008736 }
8737 }
8738#endif
8739
8740 /* Past this point, all code paths should jump to ret: label
8741 * in order to return, no direct "return" statements please.
8742 * This helps to ensure that no memory is leaked. */
8743
8744#if ENABLE_HUSH_JOB
8745 G.run_list_level++;
8746#endif
8747
8748#if HAS_KEYWORDS
8749 rword = RES_NONE;
8750 last_rword = RES_XXXX;
8751#endif
8752 last_followup = PIPE_SEQ;
8753 rcode = G.last_exitcode;
8754
8755 /* Go through list of pipes, (maybe) executing them. */
8756 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008757 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008758 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008759
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008760 if (G.flag_SIGINT)
8761 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008762 if (G_flag_return_in_progress == 1)
8763 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008764
8765 IF_HAS_KEYWORDS(rword = pi->res_word;)
8766 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8767 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008768
8769 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008770 if (
8771#if ENABLE_HUSH_IF
8772 rword == RES_IF || rword == RES_ELIF ||
8773#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008774 pi->followup != PIPE_SEQ
8775 ) {
8776 G.errexit_depth++;
8777 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008778#if ENABLE_HUSH_LOOPS
8779 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8780 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8781 ) {
8782 /* start of a loop: remember where loop starts */
8783 loop_top = pi;
8784 G.depth_of_loop++;
8785 }
8786#endif
8787 /* Still in the same "if...", "then..." or "do..." branch? */
8788 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8789 if ((rcode == 0 && last_followup == PIPE_OR)
8790 || (rcode != 0 && last_followup == PIPE_AND)
8791 ) {
8792 /* It is "<true> || CMD" or "<false> && CMD"
8793 * and we should not execute CMD */
8794 debug_printf_exec("skipped cmd because of || or &&\n");
8795 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008796 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008797 }
8798 }
8799 last_followup = pi->followup;
8800 IF_HAS_KEYWORDS(last_rword = rword;)
8801#if ENABLE_HUSH_IF
8802 if (cond_code) {
8803 if (rword == RES_THEN) {
8804 /* if false; then ... fi has exitcode 0! */
8805 G.last_exitcode = rcode = EXIT_SUCCESS;
8806 /* "if <false> THEN cmd": skip cmd */
8807 continue;
8808 }
8809 } else {
8810 if (rword == RES_ELSE || rword == RES_ELIF) {
8811 /* "if <true> then ... ELSE/ELIF cmd":
8812 * skip cmd and all following ones */
8813 break;
8814 }
8815 }
8816#endif
8817#if ENABLE_HUSH_LOOPS
8818 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8819 if (!for_lcur) {
8820 /* first loop through for */
8821
8822 static const char encoded_dollar_at[] ALIGN1 = {
8823 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8824 }; /* encoded representation of "$@" */
8825 static const char *const encoded_dollar_at_argv[] = {
8826 encoded_dollar_at, NULL
8827 }; /* argv list with one element: "$@" */
8828 char **vals;
8829
8830 vals = (char**)encoded_dollar_at_argv;
8831 if (pi->next->res_word == RES_IN) {
8832 /* if no variable values after "in" we skip "for" */
8833 if (!pi->next->cmds[0].argv) {
8834 G.last_exitcode = rcode = EXIT_SUCCESS;
8835 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8836 break;
8837 }
8838 vals = pi->next->cmds[0].argv;
8839 } /* else: "for var; do..." -> assume "$@" list */
8840 /* create list of variable values */
8841 debug_print_strings("for_list made from", vals);
8842 for_list = expand_strvec_to_strvec(vals);
8843 for_lcur = for_list;
8844 debug_print_strings("for_list", for_list);
8845 }
8846 if (!*for_lcur) {
8847 /* "for" loop is over, clean up */
8848 free(for_list);
8849 for_list = NULL;
8850 for_lcur = NULL;
8851 break;
8852 }
8853 /* Insert next value from for_lcur */
8854 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008855 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008856 continue;
8857 }
8858 if (rword == RES_IN) {
8859 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8860 }
8861 if (rword == RES_DONE) {
8862 continue; /* "done" has no cmds too */
8863 }
8864#endif
8865#if ENABLE_HUSH_CASE
8866 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008867 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkoabf75562018-04-02 17:25:18 +02008868 case_word = expand_string_to_string(pi->cmds->argv[0], 1);
8869 debug_printf_exec("CASE word1:'%s'\n", case_word);
8870 //unbackslash(case_word);
8871 //debug_printf_exec("CASE word2:'%s'\n", case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008872 continue;
8873 }
8874 if (rword == RES_MATCH) {
8875 char **argv;
8876
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008877 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008878 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8879 break;
8880 /* all prev words didn't match, does this one match? */
8881 argv = pi->cmds->argv;
8882 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008883 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008884 /* TODO: which FNM_xxx flags to use? */
8885 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008886 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008887 free(pattern);
8888 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008889 free(case_word);
8890 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008891 break;
8892 }
8893 argv++;
8894 }
8895 continue;
8896 }
8897 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008898 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008899 if (cond_code != 0)
8900 continue; /* not matched yet, skip this pipe */
8901 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008902 if (rword == RES_ESAC) {
8903 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8904 if (case_word) {
8905 /* "case" did not match anything: still set $? (to 0) */
8906 G.last_exitcode = rcode = EXIT_SUCCESS;
8907 }
8908 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008909#endif
8910 /* Just pressing <enter> in shell should check for jobs.
8911 * OTOH, in non-interactive shell this is useless
8912 * and only leads to extra job checks */
8913 if (pi->num_cmds == 0) {
8914 if (G_interactive_fd)
8915 goto check_jobs_and_continue;
8916 continue;
8917 }
8918
8919 /* After analyzing all keywords and conditions, we decided
8920 * to execute this pipe. NB: have to do checkjobs(NULL)
8921 * after run_pipe to collect any background children,
8922 * even if list execution is to be stopped. */
8923 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008924#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008925 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008926#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008927 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8928 if (r != -1) {
8929 /* We ran a builtin, function, or group.
8930 * rcode is already known
8931 * and we don't need to wait for anything. */
8932 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8933 G.last_exitcode = rcode;
8934 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008935#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008936 /* Was it "break" or "continue"? */
8937 if (G.flag_break_continue) {
8938 smallint fbc = G.flag_break_continue;
8939 /* We might fall into outer *loop*,
8940 * don't want to break it too */
8941 if (loop_top) {
8942 G.depth_break_continue--;
8943 if (G.depth_break_continue == 0)
8944 G.flag_break_continue = 0;
8945 /* else: e.g. "continue 2" should *break* once, *then* continue */
8946 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8947 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008948 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008949 break;
8950 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008951 /* "continue": simulate end of loop */
8952 rword = RES_DONE;
8953 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008954 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008955#endif
8956 if (G_flag_return_in_progress == 1) {
8957 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8958 break;
8959 }
8960 } else if (pi->followup == PIPE_BG) {
8961 /* What does bash do with attempts to background builtins? */
8962 /* even bash 3.2 doesn't do that well with nested bg:
8963 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8964 * I'm NOT treating inner &'s as jobs */
8965#if ENABLE_HUSH_JOB
8966 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008967 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008968#endif
8969 /* Last command's pid goes to $! */
8970 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008971 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008972 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008973/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008974 rcode = EXIT_SUCCESS;
8975 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008976 } else {
8977#if ENABLE_HUSH_JOB
8978 if (G.run_list_level == 1 && G_interactive_fd) {
8979 /* Waits for completion, then fg's main shell */
8980 rcode = checkjobs_and_fg_shell(pi);
8981 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008982 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008983 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008984#endif
8985 /* This one just waits for completion */
8986 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8987 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8988 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008989 G.last_exitcode = rcode;
8990 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008991 }
8992
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008993 /* Handle "set -e" */
8994 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8995 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8996 if (G.errexit_depth == 0)
8997 hush_exit(rcode);
8998 }
8999 G.errexit_depth = sv_errexit_depth;
9000
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009001 /* Analyze how result affects subsequent commands */
9002#if ENABLE_HUSH_IF
9003 if (rword == RES_IF || rword == RES_ELIF)
9004 cond_code = rcode;
9005#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02009006 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009007 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02009008 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009009#if ENABLE_HUSH_LOOPS
9010 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009011 if (pi->next
9012 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02009013 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02009014 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009015 if (rword == RES_WHILE) {
9016 if (rcode) {
9017 /* "while false; do...done" - exitcode 0 */
9018 G.last_exitcode = rcode = EXIT_SUCCESS;
9019 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02009020 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009021 }
9022 }
9023 if (rword == RES_UNTIL) {
9024 if (!rcode) {
9025 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009026 break;
9027 }
9028 }
9029 }
9030#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009031 } /* for (pi) */
9032
9033#if ENABLE_HUSH_JOB
9034 G.run_list_level--;
9035#endif
9036#if ENABLE_HUSH_LOOPS
9037 if (loop_top)
9038 G.depth_of_loop--;
9039 free(for_list);
9040#endif
9041#if ENABLE_HUSH_CASE
9042 free(case_word);
9043#endif
9044 debug_leave();
9045 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
9046 return rcode;
9047}
9048
9049/* Select which version we will use */
9050static int run_and_free_list(struct pipe *pi)
9051{
9052 int rcode = 0;
9053 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08009054 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02009055 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
9056 rcode = run_list(pi);
9057 }
9058 /* free_pipe_list has the side effect of clearing memory.
9059 * In the long run that function can be merged with run_list,
9060 * but doing that now would hobble the debugging effort. */
9061 free_pipe_list(pi);
9062 debug_printf_exec("run_and_free_list return %d\n", rcode);
9063 return rcode;
9064}
9065
9066
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009067static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00009068{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009069 sighandler_t old_handler;
9070 unsigned sig = 0;
9071 while ((mask >>= 1) != 0) {
9072 sig++;
9073 if (!(mask & 1))
9074 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02009075 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009076 /* POSIX allows shell to re-enable SIGCHLD
9077 * even if it was SIG_IGN on entry.
9078 * Therefore we skip IGN check for it:
9079 */
9080 if (sig == SIGCHLD)
9081 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02009082 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
9083 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
9084 */
9085 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009086 if (old_handler == SIG_IGN) {
9087 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009088 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009089#if ENABLE_HUSH_TRAP
9090 if (!G_traps)
9091 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9092 free(G_traps[sig]);
9093 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9094#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009095 }
9096 }
9097}
9098
9099/* Called a few times only (or even once if "sh -c") */
9100static void install_special_sighandlers(void)
9101{
Denis Vlasenkof9375282009-04-05 19:13:39 +00009102 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009103
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009104 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009105 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009106 if (G_interactive_fd) {
9107 mask |= SPECIAL_INTERACTIVE_SIGS;
9108 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009109 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009110 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009111 /* Careful, do not re-install handlers we already installed */
9112 if (G.special_sig_mask != mask) {
9113 unsigned diff = mask & ~G.special_sig_mask;
9114 G.special_sig_mask = mask;
9115 install_sighandlers(diff);
9116 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009117}
9118
9119#if ENABLE_HUSH_JOB
9120/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009121/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009122static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00009123{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009124 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009125
9126 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009127 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01009128 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
9129 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009130 + (1 << SIGBUS ) * HUSH_DEBUG
9131 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01009132 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009133 + (1 << SIGABRT)
9134 /* bash 3.2 seems to handle these just like 'fatal' ones */
9135 + (1 << SIGPIPE)
9136 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009137 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009138 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009139 * we never want to restore pgrp on exit, and this fn is not called
9140 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009141 /*+ (1 << SIGHUP )*/
9142 /*+ (1 << SIGTERM)*/
9143 /*+ (1 << SIGINT )*/
9144 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009145 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009146
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009147 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009148}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009149#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009150
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009151static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009152{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009153 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009154 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009155 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009156 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009157 break;
9158 case 'x':
9159 IF_HUSH_MODE_X(G_x_mode = state;)
9160 break;
9161 case 'o':
9162 if (!o_opt) {
9163 /* "set -+o" without parameter.
9164 * in bash, set -o produces this output:
9165 * pipefail off
9166 * and set +o:
9167 * set +o pipefail
9168 * We always use the second form.
9169 */
9170 const char *p = o_opt_strings;
9171 idx = 0;
9172 while (*p) {
9173 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9174 idx++;
9175 p += strlen(p) + 1;
9176 }
9177 break;
9178 }
9179 idx = index_in_strings(o_opt_strings, o_opt);
9180 if (idx >= 0) {
9181 G.o_opt[idx] = state;
9182 break;
9183 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009184 case 'e':
9185 G.o_opt[OPT_O_ERREXIT] = state;
9186 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009187 default:
9188 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009189 }
9190 return EXIT_SUCCESS;
9191}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009192
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009193int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009194int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009195{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009196 enum {
9197 OPT_login = (1 << 0),
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009198 OPT_s = (1 << 1),
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009199 };
9200 unsigned flags;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009201 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009202 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009203 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009204 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009205
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009206 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009207 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009208 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009209
Denys Vlasenko10c01312011-05-11 11:49:21 +02009210#if ENABLE_HUSH_FAST
9211 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9212#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009213#if !BB_MMU
9214 G.argv0_for_re_execing = argv[0];
9215#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009216
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009217 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009218 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9219 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009220 shell_ver = xzalloc(sizeof(*shell_ver));
9221 shell_ver->flg_export = 1;
9222 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009223 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009224 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009225 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009226
Denys Vlasenko605067b2010-09-06 12:10:51 +02009227 /* Create shell local variables from the values
9228 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009229 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009230 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009231 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009232 if (e) while (*e) {
9233 char *value = strchr(*e, '=');
9234 if (value) { /* paranoia */
9235 cur_var->next = xzalloc(sizeof(*cur_var));
9236 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009237 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009238 cur_var->max_len = strlen(*e);
9239 cur_var->flg_export = 1;
9240 }
9241 e++;
9242 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009243 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009244 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9245 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009246
9247 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009248 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009249
Denys Vlasenkof5018da2018-04-06 17:58:21 +02009250#if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
9251 /* Set (but not export) PS1/2 unless already set */
9252 if (!get_local_var_value("PS1"))
9253 set_local_var_from_halves("PS1", "\\w \\$ ");
9254 if (!get_local_var_value("PS2"))
9255 set_local_var_from_halves("PS2", "> ");
9256#endif
9257
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009258#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009259 /* Set (but not export) HOSTNAME unless already set */
9260 if (!get_local_var_value("HOSTNAME")) {
9261 struct utsname uts;
9262 uname(&uts);
9263 set_local_var_from_halves("HOSTNAME", uts.nodename);
9264 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009265 /* bash also exports SHLVL and _,
9266 * and sets (but doesn't export) the following variables:
9267 * BASH=/bin/bash
9268 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9269 * BASH_VERSION='3.2.0(1)-release'
9270 * HOSTTYPE=i386
9271 * MACHTYPE=i386-pc-linux-gnu
9272 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009273 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009274 * EUID=<NNNNN>
9275 * UID=<NNNNN>
9276 * GROUPS=()
9277 * LINES=<NNN>
9278 * COLUMNS=<NNN>
9279 * BASH_ARGC=()
9280 * BASH_ARGV=()
9281 * BASH_LINENO=()
9282 * BASH_SOURCE=()
9283 * DIRSTACK=()
9284 * PIPESTATUS=([0]="0")
9285 * HISTFILE=/<xxx>/.bash_history
9286 * HISTFILESIZE=500
9287 * HISTSIZE=500
9288 * MAILCHECK=60
9289 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9290 * SHELL=/bin/bash
9291 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9292 * TERM=dumb
9293 * OPTERR=1
9294 * OPTIND=1
9295 * IFS=$' \t\n'
Denys Vlasenko6db47842009-09-05 20:15:17 +02009296 * PS4='+ '
9297 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009298#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009299
Denys Vlasenko5807e182018-02-08 19:19:04 +01009300#if ENABLE_HUSH_LINENO_VAR
9301 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009302 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9303 set_local_var(p, /*flags*/ 0);
9304 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9305 }
9306#endif
9307
Denis Vlasenko38f63192007-01-22 09:03:07 +00009308#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009309 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009310#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009311
Eric Andersen94ac2442001-05-22 19:05:18 +00009312 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009313 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009314
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009315 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009316
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009317 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009318 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009319 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009320 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009321 * in order to intercept (more) signals.
9322 */
9323
9324 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009325 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009326 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009327 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009328 while (1) {
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009329 int opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009330#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009331 "<:$:R:V:"
9332# if ENABLE_HUSH_FUNCTIONS
9333 "F:"
9334# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009335#endif
9336 );
9337 if (opt <= 0)
9338 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009339 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009340 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009341 /* Possibilities:
9342 * sh ... -c 'script'
9343 * sh ... -c 'script' ARG0 [ARG1...]
9344 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009345 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009346 * "" needs to be replaced with NULL
9347 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009348 * Note: the form without ARG0 never happens:
9349 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009350 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009351 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009352 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009353 G.root_ppid = getppid();
9354 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009355 G.global_argv = argv + optind;
9356 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009357 if (builtin_argc) {
9358 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9359 const struct built_in_command *x;
9360
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009361 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009362 x = find_builtin(optarg);
9363 if (x) { /* paranoia */
9364 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9365 G.global_argv += builtin_argc;
9366 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009367 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009368 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009369 }
9370 goto final_return;
9371 }
9372 if (!G.global_argv[0]) {
9373 /* -c 'script' (no params): prevent empty $0 */
9374 G.global_argv--; /* points to argv[i] of 'script' */
9375 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009376 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009377 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009378 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009379 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009380 goto final_return;
9381 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009382 /* Well, we cannot just declare interactiveness,
9383 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009384 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009385 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009386 case 's':
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009387 flags |= OPT_s;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009388 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009389 case 'l':
9390 flags |= OPT_login;
9391 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009392#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009393 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009394 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009395 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009396 case '$': {
9397 unsigned long long empty_trap_mask;
9398
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009399 G.root_pid = bb_strtou(optarg, &optarg, 16);
9400 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009401 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9402 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009403 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9404 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009405 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009406 optarg++;
9407 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009408 optarg++;
9409 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9410 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009411 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009412 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009413# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009414 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009415 for (sig = 1; sig < NSIG; sig++) {
9416 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009417 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009418 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009419 }
9420 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009421# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009422 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009423# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009424 optarg++;
9425 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009426# endif
Denys Vlasenkoeb0de052018-04-09 17:54:07 +02009427# if ENABLE_HUSH_FUNCTIONS
9428 /* nommu uses re-exec trick for "... | func | ...",
9429 * should allow "return".
9430 * This accidentally allows returns in subshells.
9431 */
9432 G_flag_return_in_progress = -1;
9433# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009434 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009435 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009436 case 'R':
9437 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009438 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009439 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009440# if ENABLE_HUSH_FUNCTIONS
9441 case 'F': {
9442 struct function *funcp = new_function(optarg);
9443 /* funcp->name is already set to optarg */
9444 /* funcp->body is set to NULL. It's a special case. */
9445 funcp->body_as_string = argv[optind];
9446 optind++;
9447 break;
9448 }
9449# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009450#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009451 case 'n':
9452 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009453 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009454 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009455 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009456 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009457#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009458 fprintf(stderr, "Usage: sh [FILE]...\n"
9459 " or: sh -c command [args]...\n\n");
9460 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009461#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009462 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009463#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009464 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009465 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009466
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009467 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9468 G.global_argc = argc - (optind - 1);
9469 G.global_argv = argv + (optind - 1);
9470 G.global_argv[0] = argv[0];
9471
Denys Vlasenkodea47882009-10-09 15:40:49 +02009472 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009473 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009474 G.root_ppid = getppid();
9475 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009476
9477 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009478 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009479 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009480 debug_printf("sourcing /etc/profile\n");
9481 input = fopen_for_read("/etc/profile");
9482 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009483 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009484 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009485 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009486 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009487 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009488 /* bash: after sourcing /etc/profile,
9489 * tries to source (in the given order):
9490 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009491 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009492 * bash also sources ~/.bash_logout on exit.
9493 * If called as sh, skips .bash_XXX files.
9494 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009495 }
9496
Denys Vlasenkof2ed39b2018-04-05 16:46:49 +02009497 /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
9498 if (!(flags & OPT_s) && G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009499 FILE *input;
9500 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009501 * "bash <script>" (which is never interactive (unless -i?))
9502 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009503 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009504 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009505 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009506 G.global_argc--;
9507 G.global_argv++;
9508 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009509 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009510 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009511 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009512 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009513 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009514 parse_and_run_file(input);
9515#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009516 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009517#endif
9518 goto final_return;
9519 }
9520
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009521 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009522 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009523 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009524
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009525 /* A shell is interactive if the '-i' flag was given,
9526 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009527 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009528 * no arguments remaining or the -s flag given
9529 * standard input is a terminal
9530 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009531 * Refer to Posix.2, the description of the 'sh' utility.
9532 */
9533#if ENABLE_HUSH_JOB
9534 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009535 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9536 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9537 if (G_saved_tty_pgrp < 0)
9538 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009539
9540 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009541 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009542 if (G_interactive_fd < 0) {
9543 /* try to dup to any fd */
9544 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009545 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009546 /* give up */
9547 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009548 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009549 }
9550 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009551// TODO: track & disallow any attempts of user
9552// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009553 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009554 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009555 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009556 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009557
Mike Frysinger38478a62009-05-20 04:48:06 -04009558 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009559 /* If we were run as 'hush &', sleep until we are
9560 * in the foreground (tty pgrp == our pgrp).
9561 * If we get started under a job aware app (like bash),
9562 * make sure we are now in charge so we don't fight over
9563 * who gets the foreground */
9564 while (1) {
9565 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009566 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9567 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009568 break;
9569 /* send TTIN to ourself (should stop us) */
9570 kill(- shell_pgrp, SIGTTIN);
9571 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009572 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009573
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009574 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009575 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009576
Mike Frysinger38478a62009-05-20 04:48:06 -04009577 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009578 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009579 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009580 /* Put ourselves in our own process group
9581 * (bash, too, does this only if ctty is available) */
9582 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9583 /* Grab control of the terminal */
9584 tcsetpgrp(G_interactive_fd, getpid());
9585 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009586 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009587
9588# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9589 {
9590 const char *hp = get_local_var_value("HISTFILE");
9591 if (!hp) {
9592 hp = get_local_var_value("HOME");
9593 if (hp)
9594 hp = concat_path_file(hp, ".hush_history");
9595 } else {
9596 hp = xstrdup(hp);
9597 }
9598 if (hp) {
9599 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009600 //set_local_var(xasprintf("HISTFILE=%s", ...));
9601 }
9602# if ENABLE_FEATURE_SH_HISTFILESIZE
9603 hp = get_local_var_value("HISTFILESIZE");
9604 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9605# endif
9606 }
9607# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009608 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009609 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009610 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009611#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009612 /* No job control compiled in, only prompt/line editing */
9613 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009614 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009615 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009616 /* try to dup to any fd */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009617 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009618 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009619 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009620 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009621 }
9622 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009623 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009624 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009625 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009626 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009627#else
9628 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009629 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009630#endif
9631 /* bash:
9632 * if interactive but not a login shell, sources ~/.bashrc
9633 * (--norc turns this off, --rcfile <file> overrides)
9634 */
9635
9636 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009637 /* note: ash and hush share this string */
9638 printf("\n\n%s %s\n"
9639 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9640 "\n",
9641 bb_banner,
9642 "hush - the humble shell"
9643 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009644 }
9645
Denis Vlasenkof9375282009-04-05 19:13:39 +00009646 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009647
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009648 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009649 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009650}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009651
9652
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009653/*
9654 * Built-ins
9655 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009656static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009657{
9658 return 0;
9659}
9660
Denys Vlasenko265062d2017-01-10 15:13:30 +01009661#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009662static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009663{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009664 int argc = string_array_len(argv);
9665 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009666}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009667#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009668#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009669static int FAST_FUNC builtin_test(char **argv)
9670{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009671 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009672}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009673#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009674#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009675static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009676{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009677 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009678}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009679#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009680#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009681static int FAST_FUNC builtin_printf(char **argv)
9682{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009683 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009684}
9685#endif
9686
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009687#if ENABLE_HUSH_HELP
9688static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9689{
9690 const struct built_in_command *x;
9691
9692 printf(
9693 "Built-in commands:\n"
9694 "------------------\n");
9695 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9696 if (x->b_descr)
9697 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9698 }
9699 return EXIT_SUCCESS;
9700}
9701#endif
9702
9703#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9704static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9705{
9706 show_history(G.line_input_state);
9707 return EXIT_SUCCESS;
9708}
9709#endif
9710
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009711static char **skip_dash_dash(char **argv)
9712{
9713 argv++;
9714 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9715 argv++;
9716 return argv;
9717}
9718
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009719static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009720{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009721 const char *newdir;
9722
9723 argv = skip_dash_dash(argv);
9724 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009725 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009726 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009727 * bash says "bash: cd: HOME not set" and does nothing
9728 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009729 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009730 const char *home = get_local_var_value("HOME");
9731 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009732 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009733 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009734 /* Mimic bash message exactly */
9735 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009736 return EXIT_FAILURE;
9737 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009738 /* Read current dir (get_cwd(1) is inside) and set PWD.
9739 * Note: do not enforce exporting. If PWD was unset or unexported,
9740 * set it again, but do not export. bash does the same.
9741 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009742 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009743 return EXIT_SUCCESS;
9744}
9745
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009746static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9747{
9748 puts(get_cwd(0));
9749 return EXIT_SUCCESS;
9750}
9751
9752static int FAST_FUNC builtin_eval(char **argv)
9753{
9754 int rcode = EXIT_SUCCESS;
9755
9756 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009757 if (argv[0]) {
9758 char *str = NULL;
9759
9760 if (argv[1]) {
9761 /* "The eval utility shall construct a command by
9762 * concatenating arguments together, separating
9763 * each with a <space> character."
9764 */
9765 char *p;
9766 unsigned len = 0;
9767 char **pp = argv;
9768 do
9769 len += strlen(*pp) + 1;
9770 while (*++pp);
9771 str = p = xmalloc(len);
9772 pp = argv;
9773 do {
9774 p = stpcpy(p, *pp);
9775 *p++ = ' ';
9776 } while (*++pp);
9777 p[-1] = '\0';
9778 }
9779
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009780 /* bash:
9781 * eval "echo Hi; done" ("done" is syntax error):
9782 * "echo Hi" will not execute too.
9783 */
Denys Vlasenko1f191122018-01-11 13:17:30 +01009784 parse_and_run_string(str ? str : argv[0]);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009785 free(str);
9786 rcode = G.last_exitcode;
9787 }
9788 return rcode;
9789}
9790
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009791static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009792{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009793 argv = skip_dash_dash(argv);
9794 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009795 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009796
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009797 /* Careful: we can end up here after [v]fork. Do not restore
9798 * tty pgrp then, only top-level shell process does that */
9799 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9800 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9801
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009802 /* Saved-redirect fds, script fds and G_interactive_fd are still
9803 * open here. However, they are all CLOEXEC, and execv below
9804 * closes them. Try interactive "exec ls -l /proc/self/fd",
9805 * it should show no extra open fds in the "ls" process.
9806 * If we'd try to run builtins/NOEXECs, this would need improving.
9807 */
9808 //close_saved_fds_and_FILE_fds();
9809
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009810 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009811 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009812 * and tcsetpgrp, and this is inherently racy.
9813 */
9814 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009815}
9816
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009817static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009818{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009819 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009820
9821 /* interactive bash:
9822 * # trap "echo EEE" EXIT
9823 * # exit
9824 * exit
9825 * There are stopped jobs.
9826 * (if there are _stopped_ jobs, running ones don't count)
9827 * # exit
9828 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009829 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009830 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009831 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009832 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009833
9834 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009835 argv = skip_dash_dash(argv);
9836 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009837 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009838 /* mimic bash: exit 123abc == exit 255 + error msg */
9839 xfunc_error_retval = 255;
9840 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009841 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009842}
9843
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009844#if ENABLE_HUSH_TYPE
9845/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9846static int FAST_FUNC builtin_type(char **argv)
9847{
9848 int ret = EXIT_SUCCESS;
9849
9850 while (*++argv) {
9851 const char *type;
9852 char *path = NULL;
9853
9854 if (0) {} /* make conditional compile easier below */
9855 /*else if (find_alias(*argv))
9856 type = "an alias";*/
9857#if ENABLE_HUSH_FUNCTIONS
9858 else if (find_function(*argv))
9859 type = "a function";
9860#endif
9861 else if (find_builtin(*argv))
9862 type = "a shell builtin";
9863 else if ((path = find_in_path(*argv)) != NULL)
9864 type = path;
9865 else {
9866 bb_error_msg("type: %s: not found", *argv);
9867 ret = EXIT_FAILURE;
9868 continue;
9869 }
9870
9871 printf("%s is %s\n", *argv, type);
9872 free(path);
9873 }
9874
9875 return ret;
9876}
9877#endif
9878
9879#if ENABLE_HUSH_READ
9880/* Interruptibility of read builtin in bash
9881 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9882 *
9883 * Empty trap makes read ignore corresponding signal, for any signal.
9884 *
9885 * SIGINT:
9886 * - terminates non-interactive shell;
9887 * - interrupts read in interactive shell;
9888 * if it has non-empty trap:
9889 * - executes trap and returns to command prompt in interactive shell;
9890 * - executes trap and returns to read in non-interactive shell;
9891 * SIGTERM:
9892 * - is ignored (does not interrupt) read in interactive shell;
9893 * - terminates non-interactive shell;
9894 * if it has non-empty trap:
9895 * - executes trap and returns to read;
9896 * SIGHUP:
9897 * - terminates shell (regardless of interactivity);
9898 * if it has non-empty trap:
9899 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009900 * SIGCHLD from children:
9901 * - does not interrupt read regardless of interactivity:
9902 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009903 */
9904static int FAST_FUNC builtin_read(char **argv)
9905{
9906 const char *r;
9907 char *opt_n = NULL;
9908 char *opt_p = NULL;
9909 char *opt_t = NULL;
9910 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009911 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009912 const char *ifs;
9913 int read_flags;
9914
9915 /* "!": do not abort on errors.
9916 * Option string must start with "sr" to match BUILTIN_READ_xxx
9917 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009918 read_flags = getopt32(argv,
9919#if BASH_READ_D
9920 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9921#else
9922 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9923#endif
9924 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009925 if (read_flags == (uint32_t)-1)
9926 return EXIT_FAILURE;
9927 argv += optind;
9928 ifs = get_local_var_value("IFS"); /* can be NULL */
9929
9930 again:
9931 r = shell_builtin_read(set_local_var_from_halves,
9932 argv,
9933 ifs,
9934 read_flags,
9935 opt_n,
9936 opt_p,
9937 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009938 opt_u,
9939 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009940 );
9941
9942 if ((uintptr_t)r == 1 && errno == EINTR) {
9943 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009944 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009945 goto again;
9946 }
9947
9948 if ((uintptr_t)r > 1) {
9949 bb_error_msg("%s", r);
9950 r = (char*)(uintptr_t)1;
9951 }
9952
9953 return (uintptr_t)r;
9954}
9955#endif
9956
9957#if ENABLE_HUSH_UMASK
9958static int FAST_FUNC builtin_umask(char **argv)
9959{
9960 int rc;
9961 mode_t mask;
9962
9963 rc = 1;
9964 mask = umask(0);
9965 argv = skip_dash_dash(argv);
9966 if (argv[0]) {
9967 mode_t old_mask = mask;
9968
9969 /* numeric umasks are taken as-is */
9970 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9971 if (!isdigit(argv[0][0]))
9972 mask ^= 0777;
9973 mask = bb_parse_mode(argv[0], mask);
9974 if (!isdigit(argv[0][0]))
9975 mask ^= 0777;
9976 if ((unsigned)mask > 0777) {
9977 mask = old_mask;
9978 /* bash messages:
9979 * bash: umask: 'q': invalid symbolic mode operator
9980 * bash: umask: 999: octal number out of range
9981 */
9982 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9983 rc = 0;
9984 }
9985 } else {
9986 /* Mimic bash */
9987 printf("%04o\n", (unsigned) mask);
9988 /* fall through and restore mask which we set to 0 */
9989 }
9990 umask(mask);
9991
9992 return !rc; /* rc != 0 - success */
9993}
9994#endif
9995
Denys Vlasenko41ade052017-01-08 18:56:24 +01009996#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009997static void print_escaped(const char *s)
9998{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009999 if (*s == '\'')
10000 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010001 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020010002 const char *p = strchrnul(s, '\'');
10003 /* print 'xxxx', possibly just '' */
10004 printf("'%.*s'", (int)(p - s), s);
10005 if (*p == '\0')
10006 break;
10007 s = p;
10008 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010009 /* s points to '; print "'''...'''" */
10010 putchar('"');
10011 do putchar('\''); while (*++s == '\'');
10012 putchar('"');
10013 } while (*s);
10014}
Denys Vlasenko41ade052017-01-08 18:56:24 +010010015#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010016
Denys Vlasenko1e660422017-07-17 21:10:50 +020010017#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010018static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010019{
10020 do {
10021 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010022 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +020010023
10024 /* So far we do not check that name is valid (TODO?) */
10025
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010026 if (*name_end == '\0') {
10027 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010028
Denys Vlasenko27c56f12010-09-07 09:56:34 +020010029 vpp = get_ptr_to_local_var(name, name_end - name);
10030 var = vpp ? *vpp : NULL;
10031
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010032 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010033 /* export -n NAME (without =VALUE) */
10034 if (var) {
10035 var->flg_export = 0;
10036 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
10037 unsetenv(name);
10038 } /* else: export -n NOT_EXISTING_VAR: no-op */
10039 continue;
10040 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010041 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +020010042 /* export NAME (without =VALUE) */
10043 if (var) {
10044 var->flg_export = 1;
10045 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
10046 putenv(var->varstr);
10047 continue;
10048 }
10049 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010050 if (flags & SETFLAG_MAKE_RO) {
10051 /* readonly NAME (without =VALUE) */
10052 if (var) {
10053 var->flg_read_only = 1;
10054 continue;
10055 }
10056 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010057# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010058 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010059 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
Denys Vlasenko332e4112018-04-04 22:32:59 +020010060 unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
10061 if (var && var->var_nest_level == lvl) {
Denys Vlasenkob95ee962017-07-17 21:19:53 +020010062 /* "local x=abc; ...; local x" - ignore second local decl */
10063 continue;
10064 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010065 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010066# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010067 /* Exporting non-existing variable.
10068 * bash does not put it in environment,
10069 * but remembers that it is exported,
10070 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +020010071 * We just set it to "" and export.
10072 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010073 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +020010074 * bash sets the value to "".
10075 */
10076 /* Or, it's "readonly NAME" (without =VALUE).
10077 * bash remembers NAME and disallows its creation
10078 * in the future.
10079 */
Denys Vlasenko295fef82009-06-03 12:47:26 +020010080 name = xasprintf("%s=", name);
10081 } else {
10082 /* (Un)exporting/making local NAME=VALUE */
10083 name = xstrdup(name);
10084 }
Denys Vlasenko21b7f1b2018-04-05 15:15:53 +020010085 debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +020010086 if (set_local_var(name, flags))
10087 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010088 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010089 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +020010090}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010091#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +020010092
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010093#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010094static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010095{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +000010096 unsigned opt_unexport;
10097
Denys Vlasenkodf5131c2009-06-07 16:04:17 +020010098#if ENABLE_HUSH_EXPORT_N
10099 /* "!": do not abort on errors */
10100 opt_unexport = getopt32(argv, "!n");
10101 if (opt_unexport == (uint32_t)-1)
10102 return EXIT_FAILURE;
10103 argv += optind;
10104#else
10105 opt_unexport = 0;
10106 argv++;
10107#endif
10108
10109 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010110 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010111 if (e) {
10112 while (*e) {
10113#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010114 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010115#else
10116 /* ash emits: export VAR='VAL'
10117 * bash: declare -x VAR="VAL"
10118 * we follow ash example */
10119 const char *s = *e++;
10120 const char *p = strchr(s, '=');
10121
10122 if (!p) /* wtf? take next variable */
10123 continue;
10124 /* export var= */
10125 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010126 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010127 putchar('\n');
10128#endif
10129 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010130 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +000010131 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010132 return EXIT_SUCCESS;
10133 }
10134
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010135 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010136}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +010010137#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010138
Denys Vlasenko295fef82009-06-03 12:47:26 +020010139#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010140static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +020010141{
10142 if (G.func_nest_level == 0) {
10143 bb_error_msg("%s: not in a function", argv[0]);
10144 return EXIT_FAILURE; /* bash compat */
10145 }
Denys Vlasenko1e660422017-07-17 21:10:50 +020010146 argv++;
Denys Vlasenkod358b0b2018-04-05 00:51:55 +020010147 /* Since all builtins run in a nested variable level,
10148 * need to use level - 1 here. Or else the variable will be removed at once
10149 * after builtin returns.
10150 */
10151 return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +020010152}
10153#endif
10154
Denys Vlasenko1e660422017-07-17 21:10:50 +020010155#if ENABLE_HUSH_READONLY
10156static int FAST_FUNC builtin_readonly(char **argv)
10157{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010158 argv++;
10159 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010160 /* bash: readonly [-p]: list all readonly VARs
10161 * (-p has no effect in bash)
10162 */
10163 struct variable *e;
10164 for (e = G.top_var; e; e = e->next) {
10165 if (e->flg_read_only) {
10166//TODO: quote value: readonly VAR='VAL'
10167 printf("readonly %s\n", e->varstr);
10168 }
10169 }
10170 return EXIT_SUCCESS;
10171 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010172 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010173}
10174#endif
10175
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010176#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010177/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10178static int FAST_FUNC builtin_unset(char **argv)
10179{
10180 int ret;
10181 unsigned opts;
10182
10183 /* "!": do not abort on errors */
10184 /* "+": stop at 1st non-option */
10185 opts = getopt32(argv, "!+vf");
10186 if (opts == (unsigned)-1)
10187 return EXIT_FAILURE;
10188 if (opts == 3) {
10189 bb_error_msg("unset: -v and -f are exclusive");
10190 return EXIT_FAILURE;
10191 }
10192 argv += optind;
10193
10194 ret = EXIT_SUCCESS;
10195 while (*argv) {
10196 if (!(opts & 2)) { /* not -f */
10197 if (unset_local_var(*argv)) {
10198 /* unset <nonexistent_var> doesn't fail.
10199 * Error is when one tries to unset RO var.
10200 * Message was printed by unset_local_var. */
10201 ret = EXIT_FAILURE;
10202 }
10203 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010204# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010205 else {
10206 unset_func(*argv);
10207 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010208# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010209 argv++;
10210 }
10211 return ret;
10212}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010213#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010214
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010215#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010216/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10217 * built-in 'set' handler
10218 * SUSv3 says:
10219 * set [-abCefhmnuvx] [-o option] [argument...]
10220 * set [+abCefhmnuvx] [+o option] [argument...]
10221 * set -- [argument...]
10222 * set -o
10223 * set +o
10224 * Implementations shall support the options in both their hyphen and
10225 * plus-sign forms. These options can also be specified as options to sh.
10226 * Examples:
10227 * Write out all variables and their values: set
10228 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10229 * Turn on the -x and -v options: set -xv
10230 * Unset all positional parameters: set --
10231 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10232 * Set the positional parameters to the expansion of x, even if x expands
10233 * with a leading '-' or '+': set -- $x
10234 *
10235 * So far, we only support "set -- [argument...]" and some of the short names.
10236 */
10237static int FAST_FUNC builtin_set(char **argv)
10238{
10239 int n;
10240 char **pp, **g_argv;
10241 char *arg = *++argv;
10242
10243 if (arg == NULL) {
10244 struct variable *e;
10245 for (e = G.top_var; e; e = e->next)
10246 puts(e->varstr);
10247 return EXIT_SUCCESS;
10248 }
10249
10250 do {
10251 if (strcmp(arg, "--") == 0) {
10252 ++argv;
10253 goto set_argv;
10254 }
10255 if (arg[0] != '+' && arg[0] != '-')
10256 break;
10257 for (n = 1; arg[n]; ++n) {
10258 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10259 goto error;
10260 if (arg[n] == 'o' && argv[1])
10261 argv++;
10262 }
10263 } while ((arg = *++argv) != NULL);
10264 /* Now argv[0] is 1st argument */
10265
10266 if (arg == NULL)
10267 return EXIT_SUCCESS;
10268 set_argv:
10269
10270 /* NB: G.global_argv[0] ($0) is never freed/changed */
10271 g_argv = G.global_argv;
10272 if (G.global_args_malloced) {
10273 pp = g_argv;
10274 while (*++pp)
10275 free(*pp);
10276 g_argv[1] = NULL;
10277 } else {
10278 G.global_args_malloced = 1;
10279 pp = xzalloc(sizeof(pp[0]) * 2);
10280 pp[0] = g_argv[0]; /* retain $0 */
10281 g_argv = pp;
10282 }
10283 /* This realloc's G.global_argv */
10284 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10285
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010286 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010287
10288 return EXIT_SUCCESS;
10289
10290 /* Nothing known, so abort */
10291 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010292 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010293 return EXIT_FAILURE;
10294}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010295#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010296
10297static int FAST_FUNC builtin_shift(char **argv)
10298{
10299 int n = 1;
10300 argv = skip_dash_dash(argv);
10301 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010302 n = bb_strtou(argv[0], NULL, 10);
10303 if (errno || n < 0) {
10304 /* shared string with ash.c */
10305 bb_error_msg("Illegal number: %s", argv[0]);
10306 /*
10307 * ash aborts in this case.
10308 * bash prints error message and set $? to 1.
10309 * Interestingly, for "shift 99999" bash does not
10310 * print error message, but does set $? to 1
10311 * (and does no shifting at all).
10312 */
10313 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010314 }
10315 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010316 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010317 int m = 1;
10318 while (m <= n)
10319 free(G.global_argv[m++]);
10320 }
10321 G.global_argc -= n;
10322 memmove(&G.global_argv[1], &G.global_argv[n+1],
10323 G.global_argc * sizeof(G.global_argv[0]));
10324 return EXIT_SUCCESS;
10325 }
10326 return EXIT_FAILURE;
10327}
10328
Denys Vlasenko74d40582017-08-11 01:32:46 +020010329#if ENABLE_HUSH_GETOPTS
10330static int FAST_FUNC builtin_getopts(char **argv)
10331{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010332/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10333
Denys Vlasenko74d40582017-08-11 01:32:46 +020010334TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010335If a required argument is not found, and getopts is not silent,
10336a question mark (?) is placed in VAR, OPTARG is unset, and a
10337diagnostic message is printed. If getopts is silent, then a
10338colon (:) is placed in VAR and OPTARG is set to the option
10339character found.
10340
10341Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010342
10343"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010344*/
10345 char cbuf[2];
10346 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010347 int c, n, exitcode, my_opterr;
10348 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010349
10350 optstring = *++argv;
10351 if (!optstring || !(var = *++argv)) {
10352 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10353 return EXIT_FAILURE;
10354 }
10355
Denys Vlasenko238ff982017-08-29 13:38:30 +020010356 if (argv[1])
10357 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10358 else
10359 argv = G.global_argv;
10360 cbuf[1] = '\0';
10361
10362 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010363 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010364 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010365 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010366 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010367 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010368
10369 /* getopts stops on first non-option. Add "+" to force that */
10370 /*if (optstring[0] != '+')*/ {
10371 char *s = alloca(strlen(optstring) + 2);
10372 sprintf(s, "+%s", optstring);
10373 optstring = s;
10374 }
10375
Denys Vlasenko238ff982017-08-29 13:38:30 +020010376 /* Naively, now we should just
10377 * cp = get_local_var_value("OPTIND");
10378 * optind = cp ? atoi(cp) : 0;
10379 * optarg = NULL;
10380 * opterr = my_opterr;
10381 * c = getopt(string_array_len(argv), argv, optstring);
10382 * and be done? Not so fast...
10383 * Unlike normal getopt() usage in C programs, here
10384 * each successive call will (usually) have the same argv[] CONTENTS,
10385 * but not the ADDRESSES. Worse yet, it's possible that between
10386 * invocations of "getopts", there will be calls to shell builtins
10387 * which use getopt() internally. Example:
10388 * while getopts "abc" RES -a -bc -abc de; do
10389 * unset -ff func
10390 * done
10391 * This would not work correctly: getopt() call inside "unset"
10392 * modifies internal libc state which is tracking position in
10393 * multi-option strings ("-abc"). At best, it can skip options
10394 * or return the same option infinitely. With glibc implementation
10395 * of getopt(), it would use outright invalid pointers and return
10396 * garbage even _without_ "unset" mangling internal state.
10397 *
10398 * We resort to resetting getopt() state and calling it N times,
10399 * until we get Nth result (or failure).
10400 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10401 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010402 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010403 count = 0;
10404 n = string_array_len(argv);
10405 do {
10406 optarg = NULL;
10407 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10408 c = getopt(n, argv, optstring);
10409 if (c < 0)
10410 break;
10411 count++;
10412 } while (count <= G.getopt_count);
10413
10414 /* Set OPTIND. Prevent resetting of the magic counter! */
10415 set_local_var_from_halves("OPTIND", utoa(optind));
10416 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010417 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010418
10419 /* Set OPTARG */
10420 /* Always set or unset, never left as-is, even on exit/error:
10421 * "If no option was found, or if the option that was found
10422 * does not have an option-argument, OPTARG shall be unset."
10423 */
10424 cp = optarg;
10425 if (c == '?') {
10426 /* If ":optstring" and unknown option is seen,
10427 * it is stored to OPTARG.
10428 */
10429 if (optstring[1] == ':') {
10430 cbuf[0] = optopt;
10431 cp = cbuf;
10432 }
10433 }
10434 if (cp)
10435 set_local_var_from_halves("OPTARG", cp);
10436 else
10437 unset_local_var("OPTARG");
10438
10439 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010440 exitcode = EXIT_SUCCESS;
10441 if (c < 0) { /* -1: end of options */
10442 exitcode = EXIT_FAILURE;
10443 c = '?';
10444 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010445
Denys Vlasenko238ff982017-08-29 13:38:30 +020010446 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010447 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010448 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010449
Denys Vlasenko74d40582017-08-11 01:32:46 +020010450 return exitcode;
10451}
10452#endif
10453
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010454static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010455{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010456 char *arg_path, *filename;
10457 FILE *input;
10458 save_arg_t sv;
10459 char *args_need_save;
10460#if ENABLE_HUSH_FUNCTIONS
10461 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010462#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010463
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010464 argv = skip_dash_dash(argv);
10465 filename = argv[0];
10466 if (!filename) {
10467 /* bash says: "bash: .: filename argument required" */
10468 return 2; /* bash compat */
10469 }
10470 arg_path = NULL;
10471 if (!strchr(filename, '/')) {
10472 arg_path = find_in_path(filename);
10473 if (arg_path)
10474 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010475 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010476 errno = ENOENT;
10477 bb_simple_perror_msg(filename);
10478 return EXIT_FAILURE;
10479 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010480 }
10481 input = remember_FILE(fopen_or_warn(filename, "r"));
10482 free(arg_path);
10483 if (!input) {
10484 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10485 /* POSIX: non-interactive shell should abort here,
10486 * not merely fail. So far no one complained :)
10487 */
10488 return EXIT_FAILURE;
10489 }
10490
10491#if ENABLE_HUSH_FUNCTIONS
10492 sv_flg = G_flag_return_in_progress;
10493 /* "we are inside sourced file, ok to use return" */
10494 G_flag_return_in_progress = -1;
10495#endif
10496 args_need_save = argv[1]; /* used as a boolean variable */
10497 if (args_need_save)
10498 save_and_replace_G_args(&sv, argv);
10499
10500 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10501 G.last_exitcode = 0;
10502 parse_and_run_file(input);
10503 fclose_and_forget(input);
10504
10505 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10506 restore_G_args(&sv, argv);
10507#if ENABLE_HUSH_FUNCTIONS
10508 G_flag_return_in_progress = sv_flg;
10509#endif
10510
10511 return G.last_exitcode;
10512}
10513
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010514#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010515static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010516{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010517 int sig;
10518 char *new_cmd;
10519
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010520 if (!G_traps)
10521 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010522
10523 argv++;
10524 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010525 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010526 /* No args: print all trapped */
10527 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010528 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010529 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010530 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010531 /* note: bash adds "SIG", but only if invoked
10532 * as "bash". If called as "sh", or if set -o posix,
10533 * then it prints short signal names.
10534 * We are printing short names: */
10535 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010536 }
10537 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010538 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010539 return EXIT_SUCCESS;
10540 }
10541
10542 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010543 /* If first arg is a number: reset all specified signals */
10544 sig = bb_strtou(*argv, NULL, 10);
10545 if (errno == 0) {
10546 int ret;
10547 process_sig_list:
10548 ret = EXIT_SUCCESS;
10549 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010550 sighandler_t handler;
10551
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010552 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010553 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010554 ret = EXIT_FAILURE;
10555 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010556 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010557 continue;
10558 }
10559
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010560 free(G_traps[sig]);
10561 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010562
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010563 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010564 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010565
10566 /* There is no signal for 0 (EXIT) */
10567 if (sig == 0)
10568 continue;
10569
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010570 if (new_cmd)
10571 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10572 else
10573 /* We are removing trap handler */
10574 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010575 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010576 }
10577 return ret;
10578 }
10579
10580 if (!argv[1]) { /* no second arg */
10581 bb_error_msg("trap: invalid arguments");
10582 return EXIT_FAILURE;
10583 }
10584
10585 /* First arg is "-": reset all specified to default */
10586 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10587 /* Everything else: set arg as signal handler
10588 * (includes "" case, which ignores signal) */
10589 if (argv[0][0] == '-') {
10590 if (argv[0][1] == '\0') { /* "-" */
10591 /* new_cmd remains NULL: "reset these sigs" */
10592 goto reset_traps;
10593 }
10594 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10595 argv++;
10596 }
10597 /* else: "-something", no special meaning */
10598 }
10599 new_cmd = *argv;
10600 reset_traps:
10601 argv++;
10602 goto process_sig_list;
10603}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010604#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010605
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010606#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010607static struct pipe *parse_jobspec(const char *str)
10608{
10609 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010610 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010611
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010612 if (sscanf(str, "%%%u", &jobnum) != 1) {
10613 if (str[0] != '%'
10614 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10615 ) {
10616 bb_error_msg("bad argument '%s'", str);
10617 return NULL;
10618 }
10619 /* It is "%%", "%+" or "%" - current job */
10620 jobnum = G.last_jobid;
10621 if (jobnum == 0) {
10622 bb_error_msg("no current job");
10623 return NULL;
10624 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010625 }
10626 for (pi = G.job_list; pi; pi = pi->next) {
10627 if (pi->jobid == jobnum) {
10628 return pi;
10629 }
10630 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010631 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010632 return NULL;
10633}
10634
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010635static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10636{
10637 struct pipe *job;
10638 const char *status_string;
10639
10640 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10641 for (job = G.job_list; job; job = job->next) {
10642 if (job->alive_cmds == job->stopped_cmds)
10643 status_string = "Stopped";
10644 else
10645 status_string = "Running";
10646
10647 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10648 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010649
10650 clean_up_last_dead_job();
10651
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010652 return EXIT_SUCCESS;
10653}
10654
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010655/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010656static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010657{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010658 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010659 struct pipe *pi;
10660
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010661 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010662 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010663
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010664 /* If they gave us no args, assume they want the last backgrounded task */
10665 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010666 for (pi = G.job_list; pi; pi = pi->next) {
10667 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010668 goto found;
10669 }
10670 }
10671 bb_error_msg("%s: no current job", argv[0]);
10672 return EXIT_FAILURE;
10673 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010674
10675 pi = parse_jobspec(argv[1]);
10676 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010677 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010678 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010679 /* TODO: bash prints a string representation
10680 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010681 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010682 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010683 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010684 }
10685
10686 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010687 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10688 for (i = 0; i < pi->num_cmds; i++) {
10689 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010690 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010691 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010692
10693 i = kill(- pi->pgrp, SIGCONT);
10694 if (i < 0) {
10695 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010696 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010697 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010698 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010699 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010700 }
10701
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010702 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010703 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010704 return checkjobs_and_fg_shell(pi);
10705 }
10706 return EXIT_SUCCESS;
10707}
10708#endif
10709
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010710#if ENABLE_HUSH_KILL
10711static int FAST_FUNC builtin_kill(char **argv)
10712{
10713 int ret = 0;
10714
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010715# if ENABLE_HUSH_JOB
10716 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10717 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010718
10719 do {
10720 struct pipe *pi;
10721 char *dst;
10722 int j, n;
10723
10724 if (argv[i][0] != '%')
10725 continue;
10726 /*
10727 * "kill %N" - job kill
10728 * Converting to pgrp / pid kill
10729 */
10730 pi = parse_jobspec(argv[i]);
10731 if (!pi) {
10732 /* Eat bad jobspec */
10733 j = i;
10734 do {
10735 j++;
10736 argv[j - 1] = argv[j];
10737 } while (argv[j]);
10738 ret = 1;
10739 i--;
10740 continue;
10741 }
10742 /*
10743 * In jobs started under job control, we signal
10744 * entire process group by kill -PGRP_ID.
10745 * This happens, f.e., in interactive shell.
10746 *
10747 * Otherwise, we signal each child via
10748 * kill PID1 PID2 PID3.
10749 * Testcases:
10750 * sh -c 'sleep 1|sleep 1 & kill %1'
10751 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10752 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10753 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010754 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010755 dst = alloca(n * sizeof(int)*4);
10756 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010757 if (G_interactive_fd)
10758 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010759 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010760 struct command *cmd = &pi->cmds[j];
10761 /* Skip exited members of the job */
10762 if (cmd->pid == 0)
10763 continue;
10764 /*
10765 * kill_main has matching code to expect
10766 * leading space. Needed to not confuse
10767 * negative pids with "kill -SIGNAL_NO" syntax
10768 */
10769 dst += sprintf(dst, " %u", (int)cmd->pid);
10770 }
10771 *dst = '\0';
10772 } while (argv[++i]);
10773 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010774# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010775
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010776 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010777 ret = run_applet_main(argv, kill_main);
10778 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010779 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010780 return ret;
10781}
10782#endif
10783
10784#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010785/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010786#if !ENABLE_HUSH_JOB
10787# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10788#endif
10789static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010790{
10791 int ret = 0;
10792 for (;;) {
10793 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010794 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010795
Denys Vlasenko830ea352016-11-08 04:59:11 +010010796 if (!sigisemptyset(&G.pending_set))
10797 goto check_sig;
10798
Denys Vlasenko7e675362016-10-28 21:57:31 +020010799 /* waitpid is not interruptible by SA_RESTARTed
10800 * signals which we use. Thus, this ugly dance:
10801 */
10802
10803 /* Make sure possible SIGCHLD is stored in kernel's
10804 * pending signal mask before we call waitpid.
10805 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010806 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010807 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010808 sigfillset(&oldset); /* block all signals, remember old set */
10809 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010810
10811 if (!sigisemptyset(&G.pending_set)) {
10812 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010813 goto restore;
10814 }
10815
10816 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010817/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010818 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010819 debug_printf_exec("checkjobs:%d\n", ret);
10820#if ENABLE_HUSH_JOB
10821 if (waitfor_pipe) {
10822 int rcode = job_exited_or_stopped(waitfor_pipe);
10823 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10824 if (rcode >= 0) {
10825 ret = rcode;
10826 sigprocmask(SIG_SETMASK, &oldset, NULL);
10827 break;
10828 }
10829 }
10830#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010831 /* if ECHILD, there are no children (ret is -1 or 0) */
10832 /* if ret == 0, no children changed state */
10833 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010834 if (errno == ECHILD || ret) {
10835 ret--;
10836 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010837 ret = 0;
10838 sigprocmask(SIG_SETMASK, &oldset, NULL);
10839 break;
10840 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010841 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010842 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10843 /* Note: sigsuspend invokes signal handler */
10844 sigsuspend(&oldset);
10845 restore:
10846 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010847 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010848 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010849 sig = check_and_run_traps();
10850 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010851 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010852 ret = 128 + sig;
10853 break;
10854 }
10855 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10856 }
10857 return ret;
10858}
10859
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010860static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010861{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010862 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010863 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010864
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010865 argv = skip_dash_dash(argv);
10866 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010867 /* Don't care about wait results */
10868 /* Note 1: must wait until there are no more children */
10869 /* Note 2: must be interruptible */
10870 /* Examples:
10871 * $ sleep 3 & sleep 6 & wait
10872 * [1] 30934 sleep 3
10873 * [2] 30935 sleep 6
10874 * [1] Done sleep 3
10875 * [2] Done sleep 6
10876 * $ sleep 3 & sleep 6 & wait
10877 * [1] 30936 sleep 3
10878 * [2] 30937 sleep 6
10879 * [1] Done sleep 3
10880 * ^C <-- after ~4 sec from keyboard
10881 * $
10882 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010883 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010884 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010885
Denys Vlasenko7e675362016-10-28 21:57:31 +020010886 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010887 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010888 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010889#if ENABLE_HUSH_JOB
10890 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010891 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010892 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010893 wait_pipe = parse_jobspec(*argv);
10894 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010895 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010896 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010897 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010898 } else {
10899 /* waiting on "last dead job" removes it */
10900 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010901 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010902 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010903 /* else: parse_jobspec() already emitted error msg */
10904 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010905 }
10906#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010907 /* mimic bash message */
10908 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010909 ret = EXIT_FAILURE;
10910 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010911 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010912
Denys Vlasenko7e675362016-10-28 21:57:31 +020010913 /* Do we have such child? */
10914 ret = waitpid(pid, &status, WNOHANG);
10915 if (ret < 0) {
10916 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010917 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010918 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010919 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010920 /* "wait $!" but last bg task has already exited. Try:
10921 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10922 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010923 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010924 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010925 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010926 } else {
10927 /* Example: "wait 1". mimic bash message */
10928 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010929 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010930 } else {
10931 /* ??? */
10932 bb_perror_msg("wait %s", *argv);
10933 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010934 continue; /* bash checks all argv[] */
10935 }
10936 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010937 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010938 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010939 } else {
10940 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010941 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010942 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010943 if (WIFSIGNALED(status))
10944 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010945 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010946 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010947
10948 return ret;
10949}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010950#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010951
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010952#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10953static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10954{
10955 if (argv[1]) {
10956 def = bb_strtou(argv[1], NULL, 10);
10957 if (errno || def < def_min || argv[2]) {
10958 bb_error_msg("%s: bad arguments", argv[0]);
10959 def = UINT_MAX;
10960 }
10961 }
10962 return def;
10963}
10964#endif
10965
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010966#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010967static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010968{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010969 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010970 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010971 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010972 /* if we came from builtin_continue(), need to undo "= 1" */
10973 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010974 return EXIT_SUCCESS; /* bash compat */
10975 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010976 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010977
10978 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10979 if (depth == UINT_MAX)
10980 G.flag_break_continue = BC_BREAK;
10981 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010982 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010983
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010984 return EXIT_SUCCESS;
10985}
10986
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010987static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010988{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010989 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10990 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010991}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010992#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010993
10994#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010995static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010996{
10997 int rc;
10998
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010999 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011000 bb_error_msg("%s: not in a function or sourced script", argv[0]);
11001 return EXIT_FAILURE; /* bash compat */
11002 }
11003
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020011004 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000011005
11006 /* bash:
11007 * out of range: wraps around at 256, does not error out
11008 * non-numeric param:
11009 * f() { false; return qwe; }; f; echo $?
11010 * bash: return: qwe: numeric argument required <== we do this
11011 * 255 <== we also do this
11012 */
11013 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
11014 return rc;
11015}
11016#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011017
Denys Vlasenko11f2e992017-08-10 16:34:03 +020011018#if ENABLE_HUSH_TIMES
11019static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
11020{
11021 static const uint8_t times_tbl[] ALIGN1 = {
11022 ' ', offsetof(struct tms, tms_utime),
11023 '\n', offsetof(struct tms, tms_stime),
11024 ' ', offsetof(struct tms, tms_cutime),
11025 '\n', offsetof(struct tms, tms_cstime),
11026 0
11027 };
11028 const uint8_t *p;
11029 unsigned clk_tck;
11030 struct tms buf;
11031
11032 clk_tck = bb_clk_tck();
11033
11034 times(&buf);
11035 p = times_tbl;
11036 do {
11037 unsigned sec, frac;
11038 unsigned long t;
11039 t = *(clock_t *)(((char *) &buf) + p[1]);
11040 sec = t / clk_tck;
11041 frac = t % clk_tck;
11042 printf("%um%u.%03us%c",
11043 sec / 60, sec % 60,
11044 (frac * 1000) / clk_tck,
11045 p[0]);
11046 p += 2;
11047 } while (*p);
11048
11049 return EXIT_SUCCESS;
11050}
11051#endif
11052
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010011053#if ENABLE_HUSH_MEMLEAK
11054static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
11055{
11056 void *p;
11057 unsigned long l;
11058
11059# ifdef M_TRIM_THRESHOLD
11060 /* Optional. Reduces probability of false positives */
11061 malloc_trim(0);
11062# endif
11063 /* Crude attempt to find where "free memory" starts,
11064 * sans fragmentation. */
11065 p = malloc(240);
11066 l = (unsigned long)p;
11067 free(p);
11068 p = malloc(3400);
11069 if (l < (unsigned long)p) l = (unsigned long)p;
11070 free(p);
11071
11072
11073# if 0 /* debug */
11074 {
11075 struct mallinfo mi = mallinfo();
11076 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
11077 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
11078 }
11079# endif
11080
11081 if (!G.memleak_value)
11082 G.memleak_value = l;
11083
11084 l -= G.memleak_value;
11085 if ((long)l < 0)
11086 l = 0;
11087 l /= 1024;
11088 if (l > 127)
11089 l = 127;
11090
11091 /* Exitcode is "how many kilobytes we leaked since 1st call" */
11092 return l;
11093}
11094#endif