blob: 196bdbe97e0046f00fb287c0253f543b4d535813 [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 Vlasenkobbecd742010-10-03 17:22:52 +020082 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020083 * and therefore expansion of them should be "one-word" expansion:
84 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
85 * compare with:
86 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
87 * ls: cannot access i=a: No such file or directory
88 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020089 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020090 * Note2: bash 3.2.33(1) does this only if export word itself
91 * is not quoted:
92 * $ export i=`echo 'aaa bbb'`; echo "$i"
93 * aaa bbb
94 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
95 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000096 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020098//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020099//config: default y
100//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200101//config: hush is a small shell. It handles the normal flow control
102//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
103//config: case/esac. Redirections, here documents, $((arithmetic))
104//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200107//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200108//config: It does not handle select, aliases, tilde expansion,
109//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200110//config:
111//config:config HUSH_BASH_COMPAT
112//config: bool "bash-compatible extensions"
113//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100114//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200115//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200116//config:config HUSH_BRACE_EXPANSION
117//config: bool "Brace expansion"
118//config: default y
119//config: depends on HUSH_BASH_COMPAT
120//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200121//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200122//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200123//config:config HUSH_INTERACTIVE
124//config: bool "Interactive mode"
125//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100126//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200127//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200128//config: Enable interactive mode (prompt and command editing).
129//config: Without this, hush simply reads and executes commands
130//config: from stdin just like a shell script from a file.
131//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200132//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200133//config:config HUSH_SAVEHISTORY
134//config: bool "Save command history to .hush_history"
135//config: default y
136//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200137//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200138//config:config HUSH_JOB
139//config: bool "Job control"
140//config: default y
141//config: depends on HUSH_INTERACTIVE
142//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200143//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
144//config: command (not entire shell), fg/bg builtins work. Without this option,
145//config: "cmd &" still works by simply spawning a process and immediately
146//config: prompting for next command (or executing next command in a script),
147//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200148//config:
149//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100150//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200151//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100152//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200153//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200154//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200155//config:
156//config:config HUSH_IF
157//config: bool "Support if/then/elif/else/fi"
158//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100159//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200160//config:
161//config:config HUSH_LOOPS
162//config: bool "Support for, while and until loops"
163//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100164//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:
166//config:config HUSH_CASE
167//config: bool "Support case ... esac statement"
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: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200171//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200172//config:
173//config:config HUSH_FUNCTIONS
174//config: bool "Support funcname() { commands; } syntax"
175//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100176//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200177//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200178//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200179//config:
180//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100181//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config: default y
183//config: depends on HUSH_FUNCTIONS
184//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200185//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200186//config:
187//config:config HUSH_RANDOM_SUPPORT
188//config: bool "Pseudorandom generator and $RANDOM variable"
189//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100190//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200191//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200192//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
193//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200194//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200195//config:config HUSH_MODE_X
196//config: bool "Support 'hush -x' option and 'set -x' command"
197//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100198//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200199//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200200//config: This instructs hush to print commands before execution.
201//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200202//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100203//config:config HUSH_ECHO
204//config: bool "echo builtin"
205//config: default y
206//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100207//config:
208//config:config HUSH_PRINTF
209//config: bool "printf builtin"
210//config: default y
211//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100212//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100213//config:config HUSH_TEST
214//config: bool "test builtin"
215//config: default y
216//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
217//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100218//config:config HUSH_HELP
219//config: bool "help builtin"
220//config: default y
221//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100222//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100223//config:config HUSH_EXPORT
224//config: bool "export builtin"
225//config: default y
226//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100227//config:
228//config:config HUSH_EXPORT_N
229//config: bool "Support 'export -n' option"
230//config: default y
231//config: depends on HUSH_EXPORT
232//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200233//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100234//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200235//config:config HUSH_READONLY
236//config: bool "readonly builtin"
237//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200238//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200239//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200240//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200241//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100242//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100243//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100244//config: default y
245//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100246//config:
247//config:config HUSH_WAIT
248//config: bool "wait builtin"
249//config: default y
250//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100251//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100252//config:config HUSH_COMMAND
253//config: bool "command builtin"
254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
256//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100257//config:config HUSH_TRAP
258//config: bool "trap 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:
262//config:config HUSH_TYPE
263//config: bool "type builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100266//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200267//config:config HUSH_TIMES
268//config: bool "times builtin"
269//config: default y
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
271//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100272//config:config HUSH_READ
273//config: bool "read 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 Vlasenko10d5ece2017-01-08 18:28:43 +0100277//config:config HUSH_SET
278//config: bool "set builtin"
279//config: default y
280//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100281//config:
282//config:config HUSH_UNSET
283//config: bool "unset builtin"
284//config: default y
285//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100286//config:
287//config:config HUSH_ULIMIT
288//config: bool "ulimit 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:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100292//config:config HUSH_UMASK
293//config: bool "umask builtin"
294//config: default y
295//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100296//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200297//config:config HUSH_GETOPTS
298//config: bool "getopts builtin"
299//config: default y
300//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
301//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100302//config:config HUSH_MEMLEAK
303//config: bool "memleak builtin (debugging)"
304//config: default n
305//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200306
Denys Vlasenko20704f02011-03-23 17:59:27 +0100307//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100308// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100309//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100310//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100311
312//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100313//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
314//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100315//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
316
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100317/* -i (interactive) and -s (read stdin) are also accepted,
318 * but currently do nothing, therefore aren't shown in help.
319 * NOMMU-specific options are not meant to be used by users,
320 * therefore we don't show them either.
321 */
322//usage:#define hush_trivial_usage
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200323//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100324//usage:#define hush_full_usage "\n\n"
325//usage: "Unix shell interpreter"
326
Denys Vlasenko67047462016-12-22 15:21:58 +0100327#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
328 || defined(__APPLE__) \
329 )
330# include <malloc.h> /* for malloc_trim */
331#endif
332#include <glob.h>
333/* #include <dmalloc.h> */
334#if ENABLE_HUSH_CASE
335# include <fnmatch.h>
336#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200337#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100338#include <sys/utsname.h> /* for setting $HOSTNAME */
339
340#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
341#include "unicode.h"
342#include "shell_common.h"
343#include "math.h"
344#include "match.h"
345#if ENABLE_HUSH_RANDOM_SUPPORT
346# include "random.h"
347#else
348# define CLEAR_RANDOM_T(rnd) ((void)0)
349#endif
350#ifndef F_DUPFD_CLOEXEC
351# define F_DUPFD_CLOEXEC F_DUPFD
352#endif
353#ifndef PIPE_BUF
354# define PIPE_BUF 4096 /* amount of buffering in a pipe */
355#endif
356
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000357
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100358/* So far, all bash compat is controlled by one config option */
359/* Separate defines document which part of code implements what */
360#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
361#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100362#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
363#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200364#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200365#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100366
367
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200368/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000369#define LEAK_HUNTING 0
370#define BUILD_AS_NOMMU 0
371/* Enable/disable sanity checks. Ok to enable in production,
372 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
373 * Keeping 1 for now even in released versions.
374 */
375#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200376/* Slightly bigger (+200 bytes), but faster hush.
377 * So far it only enables a trick with counting SIGCHLDs and forks,
378 * which allows us to do fewer waitpid's.
379 * (we can detect a case where neither forks were done nor SIGCHLDs happened
380 * and therefore waitpid will return the same result as last time)
381 */
382#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200383/* TODO: implement simplified code for users which do not need ${var%...} ops
384 * So far ${var%...} ops are always enabled:
385 */
386#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000387
388
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000389#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000390# undef BB_MMU
391# undef USE_FOR_NOMMU
392# undef USE_FOR_MMU
393# define BB_MMU 0
394# define USE_FOR_NOMMU(...) __VA_ARGS__
395# define USE_FOR_MMU(...)
396#endif
397
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200398#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100399#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000400/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000401# undef CONFIG_FEATURE_SH_STANDALONE
402# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000403# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100404# undef IF_NOT_FEATURE_SH_STANDALONE
405# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000406# define IF_FEATURE_SH_STANDALONE(...)
407# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000408#endif
409
Denis Vlasenko05743d72008-02-10 12:10:08 +0000410#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000411# undef ENABLE_FEATURE_EDITING
412# define ENABLE_FEATURE_EDITING 0
413# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
414# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200415# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
416# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000417#endif
418
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000419/* Do we support ANY keywords? */
420#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000421# define HAS_KEYWORDS 1
422# define IF_HAS_KEYWORDS(...) __VA_ARGS__
423# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000424#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000425# define HAS_KEYWORDS 0
426# define IF_HAS_KEYWORDS(...)
427# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000428#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000429
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000430/* If you comment out one of these below, it will be #defined later
431 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000432#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000433/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000434#define debug_printf_parse(...) do {} while (0)
435#define debug_print_tree(a, b) do {} while (0)
436#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000437#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000438#define debug_printf_jobs(...) do {} while (0)
439#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200440#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000441#define debug_printf_glob(...) do {} while (0)
Denys Vlasenko2db74612017-07-07 22:07:28 +0200442#define debug_printf_redir(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000443#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000444#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000445#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000446
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000447#define ERR_PTR ((void*)(long)1)
448
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100449#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000450
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200451#define _SPECIAL_VARS_STR "_*@$!?#"
452#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
453#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100454#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200455/* Support / and // replace ops */
456/* Note that // is stored as \ in "encoded" string representation */
457# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
458# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
459# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
460#else
461# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
462# define VAR_SUBST_OPS "%#:-=+?"
463# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
464#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200465
Denys Vlasenko932b9972018-01-11 12:39:48 +0100466#define SPECIAL_VAR_SYMBOL_STR "\3"
467#define SPECIAL_VAR_SYMBOL 3
468/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
469#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000470
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200471struct variable;
472
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000473static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
474
475/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000476 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000477 */
478#if !BB_MMU
479typedef struct nommu_save_t {
480 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200481 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000482 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000483 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000484} nommu_save_t;
485#endif
486
Denys Vlasenko9b782552010-09-08 13:33:26 +0200487enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000488 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000489#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000490 RES_IF ,
491 RES_THEN ,
492 RES_ELIF ,
493 RES_ELSE ,
494 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000495#endif
496#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000497 RES_FOR ,
498 RES_WHILE ,
499 RES_UNTIL ,
500 RES_DO ,
501 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000502#endif
503#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000504 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000505#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000506#if ENABLE_HUSH_CASE
507 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200508 /* three pseudo-keywords support contrived "case" syntax: */
509 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
510 RES_MATCH , /* "word)" */
511 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000512 RES_ESAC ,
513#endif
514 RES_XXXX ,
515 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200516};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000517
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000518typedef struct o_string {
519 char *data;
520 int length; /* position where data is appended */
521 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200522 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000523 /* At least some part of the string was inside '' or "",
524 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200525 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000526 smallint has_empty_slot;
527 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
528} o_string;
529enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200530 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
531 EXP_FLAG_GLOB = 0x2,
532 /* Protect newly added chars against globbing
533 * by prepending \ to *, ?, [, \ */
534 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
535};
536enum {
537 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000538 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200539 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200540 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200541 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000542};
543/* Used for initialization: o_string foo = NULL_O_STRING; */
544#define NULL_O_STRING { NULL }
545
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200546#ifndef debug_printf_parse
547static const char *const assignment_flag[] = {
548 "MAYBE_ASSIGNMENT",
549 "DEFINITELY_ASSIGNMENT",
550 "NOT_ASSIGNMENT",
551 "WORD_IS_KEYWORD",
552};
553#endif
554
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000555typedef struct in_str {
556 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000557#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000558 smallint promptmode; /* 0: PS1, 1: PS2 */
559#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200560 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200561 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000562 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000564
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200565/* The descrip member of this structure is only used to make
566 * debugging output pretty */
567static const struct {
568 int mode;
569 signed char default_fd;
570 char descrip[3];
571} redir_table[] = {
572 { O_RDONLY, 0, "<" },
573 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
574 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
575 { O_CREAT|O_RDWR, 1, "<>" },
576 { O_RDONLY, 0, "<<" },
577/* Should not be needed. Bogus default_fd helps in debugging */
578/* { O_RDONLY, 77, "<<" }, */
579};
580
Eric Andersen25f27032001-04-26 23:22:31 +0000581struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000582 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000583 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000584 int rd_fd; /* fd to redirect */
585 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
586 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000587 smallint rd_type; /* (enum redir_type) */
588 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000589 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200590 * bit 0: do we need to trim leading tabs?
591 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000592 */
Eric Andersen25f27032001-04-26 23:22:31 +0000593};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000594typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200595 REDIRECT_INPUT = 0,
596 REDIRECT_OVERWRITE = 1,
597 REDIRECT_APPEND = 2,
598 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000599 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200600 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000601
602 REDIRFD_CLOSE = -3,
603 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000604 REDIRFD_TO_FILE = -1,
605 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000606
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000607 HEREDOC_SKIPTABS = 1,
608 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000609} redir_type;
610
Eric Andersen25f27032001-04-26 23:22:31 +0000611
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000612struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000613 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000614 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200615 smallint cmd_type; /* CMD_xxx */
616#define CMD_NORMAL 0
617#define CMD_SUBSHELL 1
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100618#if BASH_TEST2
Denys Vlasenkod383b492010-09-06 10:22:13 +0200619/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200620# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000621#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200622#if ENABLE_HUSH_FUNCTIONS
623# define CMD_FUNCDEF 3
624#endif
625
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100626 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200627 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
628 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000629#if !BB_MMU
630 char *group_as_string;
631#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000632#if ENABLE_HUSH_FUNCTIONS
633 struct function *child_func;
634/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200635 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000636 * When we execute "f1() {a;}" cmd, we create new function and clear
637 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200638 * When we execute "f1() {b;}", we notice that f1 exists,
639 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000640 * we put those fields back into cmd->xxx
641 * (struct function has ->parent_cmd ptr to facilitate that).
642 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
643 * Without this trick, loop would execute a;b;b;b;...
644 * instead of correct sequence a;b;a;b;...
645 * When command is freed, it severs the link
646 * (sets ->child_func->parent_cmd to NULL).
647 */
648#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000649 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000650/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
651 * and on execution these are substituted with their values.
652 * Substitution can make _several_ words out of one argv[n]!
653 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000654 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000655 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000656 struct redir_struct *redirects; /* I/O redirections */
657};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000658/* Is there anything in this command at all? */
659#define IS_NULL_CMD(cmd) \
660 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
661
Eric Andersen25f27032001-04-26 23:22:31 +0000662struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000663 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000664 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000665 int alive_cmds; /* number of commands running (not exited) */
666 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000667#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100668 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000669 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000670 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000671#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000672 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000673 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000674 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
675 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000676};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000677typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100678 PIPE_SEQ = 0,
679 PIPE_AND = 1,
680 PIPE_OR = 2,
681 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000682} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000683/* Is there anything in this pipe at all? */
684#define IS_NULL_PIPE(pi) \
685 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000686
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000687/* This holds pointers to the various results of parsing */
688struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000689 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000690 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000691 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000692 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000693 /* last command in pipe (being constructed right now) */
694 struct command *command;
695 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000696 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000697#if !BB_MMU
698 o_string as_string;
699#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000700#if HAS_KEYWORDS
701 smallint ctx_res_w;
702 smallint ctx_inverted; /* "! cmd | cmd" */
703#if ENABLE_HUSH_CASE
704 smallint ctx_dsemicolon; /* ";;" seen */
705#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000706 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
707 int old_flag;
708 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000709 * example: "if pipe1; pipe2; then pipe3; fi"
710 * when we see "if" or "then", we malloc and copy current context,
711 * and make ->stack point to it. then we parse pipeN.
712 * when closing "then" / fi" / whatever is found,
713 * we move list_head into ->stack->command->group,
714 * copy ->stack into current context, and delete ->stack.
715 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000716 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000717 struct parse_context *stack;
718#endif
719};
720
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000721/* On program start, environ points to initial environment.
722 * putenv adds new pointers into it, unsetenv removes them.
723 * Neither of these (de)allocates the strings.
724 * setenv allocates new strings in malloc space and does putenv,
725 * and thus setenv is unusable (leaky) for shell's purposes */
726#define setenv(...) setenv_is_leaky_dont_use()
727struct variable {
728 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000729 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200730#if ENABLE_HUSH_LOCAL
731 unsigned func_nest_level;
732#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000733 int max_len; /* if > 0, name is part of initial env; else name is malloced */
734 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000735 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000736};
737
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000738enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000739 BC_BREAK = 1,
740 BC_CONTINUE = 2,
741};
742
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000743#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000744struct function {
745 struct function *next;
746 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000747 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000748 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200749# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000750 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200751# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000752};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000753#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000754
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000755
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100756/* set -/+o OPT support. (TODO: make it optional)
757 * bash supports the following opts:
758 * allexport off
759 * braceexpand on
760 * emacs on
761 * errexit off
762 * errtrace off
763 * functrace off
764 * hashall on
765 * histexpand off
766 * history on
767 * ignoreeof off
768 * interactive-comments on
769 * keyword off
770 * monitor on
771 * noclobber off
772 * noexec off
773 * noglob off
774 * nolog off
775 * notify off
776 * nounset off
777 * onecmd off
778 * physical off
779 * pipefail off
780 * posix off
781 * privileged off
782 * verbose off
783 * vi off
784 * xtrace off
785 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800786static const char o_opt_strings[] ALIGN1 =
787 "pipefail\0"
788 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200789 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800790#if ENABLE_HUSH_MODE_X
791 "xtrace\0"
792#endif
793 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100794enum {
795 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800796 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200797 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800798#if ENABLE_HUSH_MODE_X
799 OPT_O_XTRACE,
800#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100801 NUM_OPT_O
802};
803
804
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200805struct FILE_list {
806 struct FILE_list *next;
807 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200808 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200809};
810
811
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000812/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000813/* Sorted roughly by size (smaller offsets == smaller code) */
814struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000815 /* interactive_fd != 0 means we are an interactive shell.
816 * If we are, then saved_tty_pgrp can also be != 0, meaning
817 * that controlling tty is available. With saved_tty_pgrp == 0,
818 * job control still works, but terminal signals
819 * (^C, ^Z, ^Y, ^\) won't work at all, and background
820 * process groups can only be created with "cmd &".
821 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
822 * to give tty to the foreground process group,
823 * and will take it back when the group is stopped (^Z)
824 * or killed (^C).
825 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000826#if ENABLE_HUSH_INTERACTIVE
827 /* 'interactive_fd' is a fd# open to ctty, if we have one
828 * _AND_ if we decided to act interactively */
829 int interactive_fd;
830 const char *PS1;
831 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000832# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000833#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000834# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000835#endif
836#if ENABLE_FEATURE_EDITING
837 line_input_t *line_input_state;
838#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000839 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200840 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000841 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200842#if ENABLE_HUSH_RANDOM_SUPPORT
843 random_t random_gen;
844#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000845#if ENABLE_HUSH_JOB
846 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100847 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000848 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000849 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400850# define G_saved_tty_pgrp (G.saved_tty_pgrp)
851#else
852# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000853#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200854 /* How deeply are we in context where "set -e" is ignored */
855 int errexit_depth;
856 /* "set -e" rules (do we follow them correctly?):
857 * Exit if pipe, list, or compound command exits with a non-zero status.
858 * Shell does not exit if failed command is part of condition in
859 * if/while, part of && or || list except the last command, any command
860 * in a pipe but the last, or if the command's return value is being
861 * inverted with !. If a compound command other than a subshell returns a
862 * non-zero status because a command failed while -e was being ignored, the
863 * shell does not exit. A trap on ERR, if set, is executed before the shell
864 * exits [ERR is a bashism].
865 *
866 * If a compound command or function executes in a context where -e is
867 * ignored, none of the commands executed within are affected by the -e
868 * setting. If a compound command or function sets -e while executing in a
869 * context where -e is ignored, that setting does not have any effect until
870 * the compound command or the command containing the function call completes.
871 */
872
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100873 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100874#if ENABLE_HUSH_MODE_X
875# define G_x_mode (G.o_opt[OPT_O_XTRACE])
876#else
877# define G_x_mode 0
878#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000879 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000880#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000881 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000882#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000883#if ENABLE_HUSH_FUNCTIONS
884 /* 0: outside of a function (or sourced file)
885 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000886 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000887 */
888 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200889# define G_flag_return_in_progress (G.flag_return_in_progress)
890#else
891# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000892#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000893 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000894 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000895 smalluint last_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200896 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100897#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000898 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000899 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100900# define G_global_args_malloced (G.global_args_malloced)
901#else
902# define G_global_args_malloced 0
903#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000904 /* how many non-NULL argv's we have. NB: $# + 1 */
905 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000906 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000907#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000908 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000909#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000910#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000911 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000912 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000913#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200914#if ENABLE_HUSH_GETOPTS
915 unsigned getopt_count;
916#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000917 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000918 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200919 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200920 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000921#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000922 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200923# if ENABLE_HUSH_LOCAL
924 struct variable **shadowed_vars_pp;
925 unsigned func_nest_level;
926# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000927#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000928 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200929#if ENABLE_HUSH_FAST
930 unsigned count_SIGCHLD;
931 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200932 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200933#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200934 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200935 /* Which signals have non-DFL handler (even with no traps set)?
936 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200937 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200938 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200939 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200940 * Other than these two times, never modified.
941 */
942 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200943#if ENABLE_HUSH_JOB
944 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100945# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200946#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200947# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200948#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100949#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000950 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100951# define G_traps G.traps
952#else
953# define G_traps ((char**)NULL)
954#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200955 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100956#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000957 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100958#endif
959#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000960 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000961#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200962 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200963#if ENABLE_FEATURE_EDITING
964 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
965#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000966};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000967#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000968/* Not #defining name to G.name - this quickly gets unwieldy
969 * (too many defines). Also, I actually prefer to see when a variable
970 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000971#define INIT_G() do { \
972 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200973 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
974 sigfillset(&G.sa.sa_mask); \
975 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000976} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000977
978
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000979/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200980static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100981#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200982static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100983#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200984static int builtin_eval(char **argv) FAST_FUNC;
985static int builtin_exec(char **argv) FAST_FUNC;
986static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100987#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200988static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100989#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +0200990#if ENABLE_HUSH_READONLY
991static int builtin_readonly(char **argv) FAST_FUNC;
992#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000993#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200994static int builtin_fg_bg(char **argv) FAST_FUNC;
995static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000996#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +0200997#if ENABLE_HUSH_GETOPTS
998static int builtin_getopts(char **argv) FAST_FUNC;
999#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001000#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001001static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001002#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001003#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001004static int builtin_history(char **argv) FAST_FUNC;
1005#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001006#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001007static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001008#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001009#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001010static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001011#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001012#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001013static int builtin_printf(char **argv) FAST_FUNC;
1014#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001015static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001016#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001017static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001018#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001019#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001020static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001021#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001022static int builtin_shift(char **argv) FAST_FUNC;
1023static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001024#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001025static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001026#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001027#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001028static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001029#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001030#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001031static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001032#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001033#if ENABLE_HUSH_TIMES
1034static int builtin_times(char **argv) FAST_FUNC;
1035#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001036static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001037#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001038static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001039#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001040#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001041static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001042#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001043#if ENABLE_HUSH_KILL
1044static int builtin_kill(char **argv) FAST_FUNC;
1045#endif
1046#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001047static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001048#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001049#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001050static int builtin_break(char **argv) FAST_FUNC;
1051static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001052#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001053#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001054static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001055#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001056
1057/* Table of built-in functions. They can be forked or not, depending on
1058 * context: within pipes, they fork. As simple commands, they do not.
1059 * When used in non-forking context, they can change global variables
1060 * in the parent shell process. If forked, of course they cannot.
1061 * For example, 'unset foo | whatever' will parse and run, but foo will
1062 * still be set at the end. */
1063struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001064 const char *b_cmd;
1065 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001066#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001067 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001068# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001069#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001070# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001071#endif
1072};
1073
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001074static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001075 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001076 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001077#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001078 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001079#endif
1080#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001081 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001082#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001083 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001084#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001085 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001086#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001087 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1088 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001089 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001090#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001091 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001092#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001093#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001094 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001095#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001096#if ENABLE_HUSH_GETOPTS
1097 BLTIN("getopts" , builtin_getopts , NULL),
1098#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001099#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001100 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001101#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001102#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001103 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001104#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001105#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001106 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001107#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001108#if ENABLE_HUSH_KILL
1109 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1110#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001111#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001112 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001113#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001114#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001115 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001116#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001117#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001118 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001119#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001120#if ENABLE_HUSH_READONLY
1121 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1122#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001123#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001124 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001125#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001126#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001127 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001128#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001129 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001130#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001131 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001132#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001133#if ENABLE_HUSH_TIMES
1134 BLTIN("times" , builtin_times , NULL),
1135#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001136#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001137 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001138#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001139 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001140#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001141 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001142#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001143#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001144 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001145#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001146#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001147 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001148#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001149#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001150 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001151#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001152#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001153 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001154#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001156/* These builtins won't be used if we are on NOMMU and need to re-exec
1157 * (it's cheaper to run an external program in this case):
1158 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001159static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001160#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001161 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001162#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001163#if BASH_TEST2
1164 BLTIN("[[" , builtin_test , NULL),
1165#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001166#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001167 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001168#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001169#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001170 BLTIN("printf" , builtin_printf , NULL),
1171#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001172 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001173#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001174 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001175#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001176};
1177
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001178
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001179/* Debug printouts.
1180 */
1181#if HUSH_DEBUG
1182/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001183# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001184# define debug_enter() (G.debug_indent++)
1185# define debug_leave() (G.debug_indent--)
1186#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001187# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001188# define debug_enter() ((void)0)
1189# define debug_leave() ((void)0)
1190#endif
1191
1192#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001193# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001194#endif
1195
1196#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001197# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001198#endif
1199
1200#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001201#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001202#endif
1203
1204#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001205# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001206#endif
1207
1208#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001209# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001210# define DEBUG_JOBS 1
1211#else
1212# define DEBUG_JOBS 0
1213#endif
1214
1215#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001216# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001217# define DEBUG_EXPAND 1
1218#else
1219# define DEBUG_EXPAND 0
1220#endif
1221
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001222#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001223# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001224#endif
1225
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001226#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001227# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001228# define DEBUG_GLOB 1
1229#else
1230# define DEBUG_GLOB 0
1231#endif
1232
Denys Vlasenko2db74612017-07-07 22:07:28 +02001233#ifndef debug_printf_redir
1234# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1235#endif
1236
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001237#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001238# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001239#endif
1240
1241#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001242# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001243#endif
1244
1245#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001246# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001247# define DEBUG_CLEAN 1
1248#else
1249# define DEBUG_CLEAN 0
1250#endif
1251
1252#if DEBUG_EXPAND
1253static void debug_print_strings(const char *prefix, char **vv)
1254{
1255 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001256 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001257 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001258 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001259}
1260#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001261# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001262#endif
1263
1264
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001265/* Leak hunting. Use hush_leaktool.sh for post-processing.
1266 */
1267#if LEAK_HUNTING
1268static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001269{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001270 void *ptr = xmalloc((size + 0xff) & ~0xff);
1271 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1272 return ptr;
1273}
1274static void *xxrealloc(int lineno, void *ptr, size_t size)
1275{
1276 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1277 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1278 return ptr;
1279}
1280static char *xxstrdup(int lineno, const char *str)
1281{
1282 char *ptr = xstrdup(str);
1283 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1284 return ptr;
1285}
1286static void xxfree(void *ptr)
1287{
1288 fdprintf(2, "free %p\n", ptr);
1289 free(ptr);
1290}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001291# define xmalloc(s) xxmalloc(__LINE__, s)
1292# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1293# define xstrdup(s) xxstrdup(__LINE__, s)
1294# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001295#endif
1296
1297
1298/* Syntax and runtime errors. They always abort scripts.
1299 * In interactive use they usually discard unparsed and/or unexecuted commands
1300 * and return to the prompt.
1301 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1302 */
1303#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001304# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001305# define syntax_error(lineno, msg) syntax_error(msg)
1306# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1307# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1308# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1309# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001310#endif
1311
Denys Vlasenko39701202017-08-02 19:44:05 +02001312static void die_if_script(void)
1313{
1314 if (!G_interactive_fd) {
1315 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1316 xfunc_error_retval = G.last_exitcode;
1317 xfunc_die();
1318 }
1319}
1320
1321static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001322{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001323 va_list p;
1324
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001325#if HUSH_DEBUG >= 2
1326 bb_error_msg("hush.c:%u", lineno);
1327#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001328 va_start(p, fmt);
1329 bb_verror_msg(fmt, p, NULL);
1330 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001331 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001332}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001333
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001334static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001335{
1336 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001337 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001338 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001339 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001340 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001341}
1342
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001343static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001344{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001345 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001346 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001347}
1348
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001349static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001350{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001351 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001352//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1353// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001354}
1355
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001356static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001357{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001358 char msg[2] = { ch, '\0' };
1359 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001360}
1361
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001362static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001363{
1364 char msg[2];
1365 msg[0] = ch;
1366 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001367#if HUSH_DEBUG >= 2
1368 bb_error_msg("hush.c:%u", lineno);
1369#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001370 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001371 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001372}
1373
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001374#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001375# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001376# undef syntax_error
1377# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001378# undef syntax_error_unterm_ch
1379# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001380# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001381#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001382# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001383# define syntax_error(msg) syntax_error(__LINE__, msg)
1384# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1385# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1386# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1387# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001388#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001389
Denis Vlasenko552433b2009-04-04 19:29:21 +00001390
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001391#if ENABLE_HUSH_INTERACTIVE
1392static void cmdedit_update_prompt(void);
1393#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001394# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001395#endif
1396
1397
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001398/* Utility functions
1399 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001400/* Replace each \x with x in place, return ptr past NUL. */
1401static char *unbackslash(char *src)
1402{
Denys Vlasenko71885402009-09-24 01:44:13 +02001403 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001404 while (1) {
1405 if (*src == '\\')
1406 src++;
1407 if ((*dst++ = *src++) == '\0')
1408 break;
1409 }
1410 return dst;
1411}
1412
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001413static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001414{
1415 int i;
1416 unsigned count1;
1417 unsigned count2;
1418 char **v;
1419
1420 v = strings;
1421 count1 = 0;
1422 if (v) {
1423 while (*v) {
1424 count1++;
1425 v++;
1426 }
1427 }
1428 count2 = 0;
1429 v = add;
1430 while (*v) {
1431 count2++;
1432 v++;
1433 }
1434 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1435 v[count1 + count2] = NULL;
1436 i = count2;
1437 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001438 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001439 return v;
1440}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001441#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001442static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1443{
1444 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1445 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1446 return ptr;
1447}
1448#define add_strings_to_strings(strings, add, need_to_dup) \
1449 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1450#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001451
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001452/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001453static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001454{
1455 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001456 v[0] = add;
1457 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001458 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001459}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001460#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001461static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1462{
1463 char **ptr = add_string_to_strings(strings, add);
1464 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1465 return ptr;
1466}
1467#define add_string_to_strings(strings, add) \
1468 xx_add_string_to_strings(__LINE__, strings, add)
1469#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001470
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001471static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001472{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001473 char **v;
1474
1475 if (!strings)
1476 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001477 v = strings;
1478 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001479 free(*v);
1480 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001481 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001482 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001483}
1484
Denys Vlasenko2db74612017-07-07 22:07:28 +02001485static int fcntl_F_DUPFD(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001486{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001487 int newfd;
1488 repeat:
1489 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001490 if (newfd < 0) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001491 if (errno == EBUSY)
1492 goto repeat;
1493 if (errno == EINTR)
1494 goto repeat;
1495 }
1496 return newfd;
1497}
1498
Denys Vlasenko657e9002017-07-30 23:34:04 +02001499static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001500{
1501 int newfd;
1502 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001503 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001504 if (newfd < 0) {
1505 if (errno == EBUSY)
1506 goto repeat;
1507 if (errno == EINTR)
1508 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001509 /* fd was not open? */
1510 if (errno == EBADF)
1511 return fd;
1512 xfunc_die();
1513 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001514 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1515 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001516 close(fd);
1517 return newfd;
1518}
1519
1520
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001521/* Manipulating the list of open FILEs */
1522static FILE *remember_FILE(FILE *fp)
1523{
1524 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001525 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001526 n->next = G.FILE_list;
1527 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001528 n->fp = fp;
1529 n->fd = fileno(fp);
1530 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001531 }
1532 return fp;
1533}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001534static void fclose_and_forget(FILE *fp)
1535{
1536 struct FILE_list **pp = &G.FILE_list;
1537 while (*pp) {
1538 struct FILE_list *cur = *pp;
1539 if (cur->fp == fp) {
1540 *pp = cur->next;
1541 free(cur);
1542 break;
1543 }
1544 pp = &cur->next;
1545 }
1546 fclose(fp);
1547}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001548static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001549{
1550 struct FILE_list *fl = G.FILE_list;
1551 while (fl) {
1552 if (fd == fl->fd) {
1553 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001554 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001555 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 +02001556 return 1;
1557 }
1558 fl = fl->next;
1559 }
1560 return 0;
1561}
1562static void restore_redirected_FILEs(void)
1563{
1564 struct FILE_list *fl = G.FILE_list;
1565 while (fl) {
1566 int should_be = fileno(fl->fp);
1567 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001568 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001569 xmove_fd(fl->fd, should_be);
1570 fl->fd = should_be;
1571 }
1572 fl = fl->next;
1573 }
1574}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001575#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001576static void close_all_FILE_list(void)
1577{
1578 struct FILE_list *fl = G.FILE_list;
1579 while (fl) {
1580 /* fclose would also free FILE object.
1581 * It is disastrous if we share memory with a vforked parent.
1582 * I'm not sure we never come here after vfork.
1583 * Therefore just close fd, nothing more.
1584 */
1585 /*fclose(fl->fp); - unsafe */
1586 close(fl->fd);
1587 fl = fl->next;
1588 }
1589}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001590#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001591static int fd_in_FILEs(int fd)
1592{
1593 struct FILE_list *fl = G.FILE_list;
1594 while (fl) {
1595 if (fl->fd == fd)
1596 return 1;
1597 fl = fl->next;
1598 }
1599 return 0;
1600}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001601
1602
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001603/* Helpers for setting new $n and restoring them back
1604 */
1605typedef struct save_arg_t {
1606 char *sv_argv0;
1607 char **sv_g_argv;
1608 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001609 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001610} save_arg_t;
1611
1612static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1613{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001614 sv->sv_argv0 = argv[0];
1615 sv->sv_g_argv = G.global_argv;
1616 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001617 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001618
1619 argv[0] = G.global_argv[0]; /* retain $0 */
1620 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001621 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001622
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001623 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001624}
1625
1626static void restore_G_args(save_arg_t *sv, char **argv)
1627{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001628#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001629 if (G.global_args_malloced) {
1630 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001631 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001632 while (*++pp) /* note: does not free $0 */
1633 free(*pp);
1634 free(G.global_argv);
1635 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001636#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001637 argv[0] = sv->sv_argv0;
1638 G.global_argv = sv->sv_g_argv;
1639 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001640 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001641}
1642
1643
Denis Vlasenkod5762932009-03-31 11:22:57 +00001644/* Basic theory of signal handling in shell
1645 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001646 * This does not describe what hush does, rather, it is current understanding
1647 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001648 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1649 *
1650 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1651 * is finished or backgrounded. It is the same in interactive and
1652 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001653 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001654 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001655 * backgrounds (i.e. stops) or kills all members of currently running
1656 * pipe.
1657 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001658 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001659 * or by SIGINT in interactive shell.
1660 *
1661 * Trap handlers will execute even within trap handlers. (right?)
1662 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001663 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1664 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001665 *
1666 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001667 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001668 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001669 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001670 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001671 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001672 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001673 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001674 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001675 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001676 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001677 *
1678 * SIGQUIT: ignore
1679 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001680 * SIGHUP (interactive):
1681 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001682 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001683 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1684 * that all pipe members are stopped. Try this in bash:
1685 * while :; do :; done - ^Z does not background it
1686 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001687 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001688 * of the command line, show prompt. NB: ^C does not send SIGINT
1689 * to interactive shell while shell is waiting for a pipe,
1690 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001691 * Example 1: this waits 5 sec, but does not execute ls:
1692 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1693 * Example 2: this does not wait and does not execute ls:
1694 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1695 * Example 3: this does not wait 5 sec, but executes ls:
1696 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001697 * Example 4: this does not wait and does not execute ls:
1698 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001699 *
1700 * (What happens to signals which are IGN on shell start?)
1701 * (What happens with signal mask on shell start?)
1702 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001703 * Old implementation
1704 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001705 * We use in-kernel pending signal mask to determine which signals were sent.
1706 * We block all signals which we don't want to take action immediately,
1707 * i.e. we block all signals which need to have special handling as described
1708 * above, and all signals which have traps set.
1709 * After each pipe execution, we extract any pending signals via sigtimedwait()
1710 * and act on them.
1711 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001712 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001713 * sigset_t blocked_set: current blocked signal set
1714 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001715 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001716 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001717 * "trap 'cmd' SIGxxx":
1718 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001719 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001720 * unblock signals with special interactive handling
1721 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001722 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001723 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001724 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001725 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001726 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001727 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001728 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001729 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001730 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001731 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001732 * Standard says "When a subshell is entered, traps that are not being ignored
1733 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001734 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001735 *
1736 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001737 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001738 * masked signals are not visible!
1739 *
1740 * New implementation
1741 * ==================
1742 * We record each signal we are interested in by installing signal handler
1743 * for them - a bit like emulating kernel pending signal mask in userspace.
1744 * We are interested in: signals which need to have special handling
1745 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001746 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001747 * After each pipe execution, we extract any pending signals
1748 * and act on them.
1749 *
1750 * unsigned special_sig_mask: a mask of shell-special signals.
1751 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1752 * char *traps[sig] if trap for sig is set (even if it's '').
1753 * sigset_t pending_set: set of sigs we received.
1754 *
1755 * "trap - SIGxxx":
1756 * if sig is in special_sig_mask, set handler back to:
1757 * record_pending_signo, or to IGN if it's a tty stop signal
1758 * if sig is in fatal_sig_mask, set handler back to sigexit.
1759 * else: set handler back to SIG_DFL
1760 * "trap 'cmd' SIGxxx":
1761 * set handler to record_pending_signo.
1762 * "trap '' SIGxxx":
1763 * set handler to SIG_IGN.
1764 * after [v]fork, if we plan to be a shell:
1765 * set signals with special interactive handling to SIG_DFL
1766 * (because child shell is not interactive),
1767 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1768 * after [v]fork, if we plan to exec:
1769 * POSIX says fork clears pending signal mask in child - no need to clear it.
1770 *
1771 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1772 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1773 *
1774 * Note (compat):
1775 * Standard says "When a subshell is entered, traps that are not being ignored
1776 * are set to the default actions". bash interprets it so that traps which
1777 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001778 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001779enum {
1780 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001781 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001782 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001783 | (1 << SIGHUP)
1784 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001785 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001786#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001787 | (1 << SIGTTIN)
1788 | (1 << SIGTTOU)
1789 | (1 << SIGTSTP)
1790#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001791 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001792};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001793
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001794static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001795{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001796 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001797#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001798 if (sig == SIGCHLD) {
1799 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001800//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 +02001801 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001802#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001803}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001804
Denys Vlasenko0806e402011-05-12 23:06:20 +02001805static sighandler_t install_sighandler(int sig, sighandler_t handler)
1806{
1807 struct sigaction old_sa;
1808
1809 /* We could use signal() to install handlers... almost:
1810 * except that we need to mask ALL signals while handlers run.
1811 * I saw signal nesting in strace, race window isn't small.
1812 * SA_RESTART is also needed, but in Linux, signal()
1813 * sets SA_RESTART too.
1814 */
1815 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1816 /* sigfillset(&G.sa.sa_mask); - already done */
1817 /* G.sa.sa_flags = SA_RESTART; - already done */
1818 G.sa.sa_handler = handler;
1819 sigaction(sig, &G.sa, &old_sa);
1820 return old_sa.sa_handler;
1821}
1822
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001823static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001824
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001825static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001826static void restore_ttypgrp_and__exit(void)
1827{
1828 /* xfunc has failed! die die die */
1829 /* no EXIT traps, this is an escape hatch! */
1830 G.exiting = 1;
1831 hush_exit(xfunc_error_retval);
1832}
1833
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001834#if ENABLE_HUSH_JOB
1835
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001836/* Needed only on some libc:
1837 * It was observed that on exit(), fgetc'ed buffered data
1838 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1839 * With the net effect that even after fork(), not vfork(),
1840 * exit() in NOEXECed applet in "sh SCRIPT":
1841 * noexec_applet_here
1842 * echo END_OF_SCRIPT
1843 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1844 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001845 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001846 * and in `cmd` handling.
1847 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1848 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001849static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001850static void fflush_and__exit(void)
1851{
1852 fflush_all();
1853 _exit(xfunc_error_retval);
1854}
1855
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001856/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001857# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001858/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001859# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001860
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001861/* Restores tty foreground process group, and exits.
1862 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001863 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001864 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001865 * We also call it if xfunc is exiting.
1866 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001867static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001868static void sigexit(int sig)
1869{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001870 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001871 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001872 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1873 /* Disable all signals: job control, SIGPIPE, etc.
1874 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1875 */
1876 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001877 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001878 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001879
1880 /* Not a signal, just exit */
1881 if (sig <= 0)
1882 _exit(- sig);
1883
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001884 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001885}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001886#else
1887
Denys Vlasenko8391c482010-05-22 17:50:43 +02001888# define disable_restore_tty_pgrp_on_exit() ((void)0)
1889# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001890
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001891#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001892
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001893static sighandler_t pick_sighandler(unsigned sig)
1894{
1895 sighandler_t handler = SIG_DFL;
1896 if (sig < sizeof(unsigned)*8) {
1897 unsigned sigmask = (1 << sig);
1898
1899#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001900 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001901 if (G_fatal_sig_mask & sigmask)
1902 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001903 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001904#endif
1905 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001906 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001907 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001908 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001909 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001910 * in an endless loop when we try to do some
1911 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001912 */
1913 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1914 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001915 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001916 }
1917 return handler;
1918}
1919
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001920/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001921static void hush_exit(int exitcode)
1922{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001923#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1924 save_history(G.line_input_state);
1925#endif
1926
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001927 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001928 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001929 char *argv[3];
1930 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001931 argv[1] = G_traps[0];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001932 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001933 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001934 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001935 * "trap" will still show it, if executed
1936 * in the handler */
1937 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001938 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001939
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001940#if ENABLE_FEATURE_CLEAN_UP
1941 {
1942 struct variable *cur_var;
1943 if (G.cwd != bb_msg_unknown)
1944 free((char*)G.cwd);
1945 cur_var = G.top_var;
1946 while (cur_var) {
1947 struct variable *tmp = cur_var;
1948 if (!cur_var->max_len)
1949 free(cur_var->varstr);
1950 cur_var = cur_var->next;
1951 free(tmp);
1952 }
1953 }
1954#endif
1955
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001956 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001957#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001958 sigexit(- (exitcode & 0xff));
1959#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001960 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001961#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001962}
1963
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001964
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001965//TODO: return a mask of ALL handled sigs?
1966static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001967{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001968 int last_sig = 0;
1969
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001970 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001971 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001972
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001973 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001974 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001975 sig = 0;
1976 do {
1977 sig++;
1978 if (sigismember(&G.pending_set, sig)) {
1979 sigdelset(&G.pending_set, sig);
1980 goto got_sig;
1981 }
1982 } while (sig < NSIG);
1983 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001984 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001985 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001986 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001987 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001988 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001989 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001990 char *argv[3];
1991 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001992 argv[1] = G_traps[sig];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001993 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001994 save_rcode = G.last_exitcode;
1995 builtin_eval(argv);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01001996//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001997 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001998 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001999 } /* else: "" trap, ignoring signal */
2000 continue;
2001 }
2002 /* not a trap: special action */
2003 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002004 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002005 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002006 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002007 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002008 break;
2009#if ENABLE_HUSH_JOB
2010 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002011//TODO: why are we doing this? ash and dash don't do this,
2012//they have no handler for SIGHUP at all,
2013//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002014 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002015 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002016 /* bash is observed to signal whole process groups,
2017 * not individual processes */
2018 for (job = G.job_list; job; job = job->next) {
2019 if (job->pgrp <= 0)
2020 continue;
2021 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2022 if (kill(- job->pgrp, SIGHUP) == 0)
2023 kill(- job->pgrp, SIGCONT);
2024 }
2025 sigexit(SIGHUP);
2026 }
2027#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002028#if ENABLE_HUSH_FAST
2029 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002030 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002031 G.count_SIGCHLD++;
2032//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2033 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002034 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002035 * This simplifies wait builtin a bit.
2036 */
2037 break;
2038#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002039 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002040 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002041 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002042 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002043 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002044 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002045 * in interactive shell, because TERM is ignored.
2046 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002047 break;
2048 }
2049 }
2050 return last_sig;
2051}
2052
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002053
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002054static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002055{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002056 if (force || G.cwd == NULL) {
2057 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2058 * we must not try to free(bb_msg_unknown) */
2059 if (G.cwd == bb_msg_unknown)
2060 G.cwd = NULL;
2061 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2062 if (!G.cwd)
2063 G.cwd = bb_msg_unknown;
2064 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002065 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002066}
2067
Denis Vlasenko83506862007-11-23 13:11:42 +00002068
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002069/*
2070 * Shell and environment variable support
2071 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002072static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002073{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002074 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002075 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002076
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002077 pp = &G.top_var;
2078 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002079 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002080 return pp;
2081 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002082 }
2083 return NULL;
2084}
2085
Denys Vlasenko03dad222010-01-12 23:29:57 +01002086static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002087{
Denys Vlasenko29082232010-07-16 13:52:32 +02002088 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002089 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002090
2091 if (G.expanded_assignments) {
2092 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002093 while (*cpp) {
2094 char *cp = *cpp;
2095 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2096 return cp + len + 1;
2097 cpp++;
2098 }
2099 }
2100
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002101 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002102 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002103 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002104
Denys Vlasenkodea47882009-10-09 15:40:49 +02002105 if (strcmp(name, "PPID") == 0)
2106 return utoa(G.root_ppid);
2107 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002108#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002109 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002110 return utoa(next_random(&G.random_gen));
2111#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002112 return NULL;
2113}
2114
2115/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002116 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002117 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002118#define SETFLAG_EXPORT (1 << 0)
2119#define SETFLAG_UNEXPORT (1 << 1)
2120#define SETFLAG_MAKE_RO (1 << 2)
2121#define SETFLAG_LOCAL_SHIFT 3
2122static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002123{
Denys Vlasenko295fef82009-06-03 12:47:26 +02002124 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002125 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002126 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002127 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002128 int name_len;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002129 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002130
Denis Vlasenko950bd722009-04-21 11:23:56 +00002131 eq_sign = strchr(str, '=');
2132 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002133 free(str);
2134 return -1;
2135 }
2136
Denis Vlasenko950bd722009-04-21 11:23:56 +00002137 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002138 var_pp = &G.top_var;
2139 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002140 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002141 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002142 continue;
2143 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002144
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002145 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002146 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002147 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002148 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002149//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2150//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002151 return -1;
2152 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002153 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002154 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2155 *eq_sign = '\0';
2156 unsetenv(str);
2157 *eq_sign = '=';
2158 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002159#if ENABLE_HUSH_LOCAL
2160 if (cur->func_nest_level < local_lvl) {
2161 /* New variable is declared as local,
2162 * and existing one is global, or local
2163 * from enclosing function.
2164 * Remove and save old one: */
2165 *var_pp = cur->next;
2166 cur->next = *G.shadowed_vars_pp;
2167 *G.shadowed_vars_pp = cur;
2168 /* bash 3.2.33(1) and exported vars:
2169 * # export z=z
2170 * # f() { local z=a; env | grep ^z; }
2171 * # f
2172 * z=a
2173 * # env | grep ^z
2174 * z=z
2175 */
2176 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002177 flags |= SETFLAG_EXPORT;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002178 break;
2179 }
2180#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00002181 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002182 free_and_exp:
2183 free(str);
2184 goto exp;
2185 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002186 if (cur->max_len != 0) {
2187 if (cur->max_len >= strlen(str)) {
2188 /* This one is from startup env, reuse space */
2189 strcpy(cur->varstr, str);
2190 goto free_and_exp;
2191 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002192 /* Can't reuse */
2193 cur->max_len = 0;
2194 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002195 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002196 /* max_len == 0 signifies "malloced" var, which we can
2197 * (and have to) free. But we can't free(cur->varstr) here:
2198 * if cur->flg_export is 1, it is in the environment.
2199 * We should either unsetenv+free, or wait until putenv,
2200 * then putenv(new)+free(old).
2201 */
2202 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002203 goto set_str_and_exp;
2204 }
2205
Denys Vlasenko295fef82009-06-03 12:47:26 +02002206 /* Not found - create new variable struct */
2207 cur = xzalloc(sizeof(*cur));
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002208 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
Denys Vlasenko295fef82009-06-03 12:47:26 +02002209 cur->next = *var_pp;
2210 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002211
2212 set_str_and_exp:
2213 cur->varstr = str;
2214 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002215#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002216 if (flags & SETFLAG_MAKE_RO) {
2217 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002218 }
2219#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002220 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002221 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002222 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2223 cmdedit_update_prompt();
Denys Vlasenko238ff982017-08-29 13:38:30 +02002224#if ENABLE_HUSH_GETOPTS
Denys Vlasenko55af51c2017-08-29 13:48:49 +02002225 /* defoptindvar is a "OPTIND=..." constant string */
2226 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
Denys Vlasenko238ff982017-08-29 13:38:30 +02002227 G.getopt_count = 0;
2228#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002229 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002230 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002231 cur->flg_export = 0;
2232 /* unsetenv was already done */
2233 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002234 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002235 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002236 i = putenv(cur->varstr);
2237 /* only now we can free old exported malloced string */
2238 free(free_me);
2239 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002240 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002241 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002242 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002243 return 0;
2244}
2245
Denys Vlasenko6db47842009-09-05 20:15:17 +02002246/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002247static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002248{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002249 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002250}
2251
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002252static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002253{
2254 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002255 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002256
2257 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002258 return EXIT_SUCCESS;
Denys Vlasenko238ff982017-08-29 13:38:30 +02002259#if ENABLE_HUSH_GETOPTS
2260 if (name_len == 6 && strncmp(name, "OPTIND", 6) == 0)
2261 G.getopt_count = 0;
2262#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002263 var_pp = &G.top_var;
2264 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002265 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2266 if (cur->flg_read_only) {
2267 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002268 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002269 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002270 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002271 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2272 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002273 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2274 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002275 if (!cur->max_len)
2276 free(cur->varstr);
2277 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002278 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002279 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002280 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002281 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002282 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002283}
2284
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002285#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002286static int unset_local_var(const char *name)
2287{
2288 return unset_local_var_len(name, strlen(name));
2289}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002290#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002291
2292static void unset_vars(char **strings)
2293{
2294 char **v;
2295
2296 if (!strings)
2297 return;
2298 v = strings;
2299 while (*v) {
2300 const char *eq = strchrnul(*v, '=');
2301 unset_local_var_len(*v, (int)(eq - *v));
2302 v++;
2303 }
2304 free(strings);
2305}
2306
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002307#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002308static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002309{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002310 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002311 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002312}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002313#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002314
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002315
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002316/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002317 * Helpers for "var1=val1 var2=val2 cmd" feature
2318 */
2319static void add_vars(struct variable *var)
2320{
2321 struct variable *next;
2322
2323 while (var) {
2324 next = var->next;
2325 var->next = G.top_var;
2326 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002327 if (var->flg_export) {
2328 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002329 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002330 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002331 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002332 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002333 var = next;
2334 }
2335}
2336
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002337static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002338{
2339 char **s;
2340 struct variable *old = NULL;
2341
2342 if (!strings)
2343 return old;
2344 s = strings;
2345 while (*s) {
2346 struct variable *var_p;
2347 struct variable **var_pp;
2348 char *eq;
2349
2350 eq = strchr(*s, '=');
2351 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002352 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002353 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002354 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002355 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002356 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002357 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002358 /*
2359 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2360 * If VAR is readonly, leaving it in the list
2361 * after asssignment error (msg above)
2362 * causes doubled error message later, on unset.
2363 */
2364 debug_printf_env("removing/freeing '%s' element\n", *s);
2365 free(*s);
2366 p = s;
2367 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002368 goto next;
2369 }
2370 /* Remove variable from global linked list */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002371 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002372 *var_pp = var_p->next;
2373 /* Add it to returned list */
2374 var_p->next = old;
2375 old = var_p;
2376 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002377 set_local_var(*s, SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002378 }
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002379 next:
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002380 s++;
2381 }
2382 return old;
2383}
2384
2385
2386/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002387 * Unicode helper
2388 */
2389static void reinit_unicode_for_hush(void)
2390{
2391 /* Unicode support should be activated even if LANG is set
2392 * _during_ shell execution, not only if it was set when
2393 * shell was started. Therefore, re-check LANG every time:
2394 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002395 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2396 || ENABLE_UNICODE_USING_LOCALE
2397 ) {
2398 const char *s = get_local_var_value("LC_ALL");
2399 if (!s) s = get_local_var_value("LC_CTYPE");
2400 if (!s) s = get_local_var_value("LANG");
2401 reinit_unicode(s);
2402 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002403}
2404
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002405/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002406 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002407 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002408
2409#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002410/* To test correct lineedit/interactive behavior, type from command line:
2411 * echo $P\
2412 * \
2413 * AT\
2414 * H\
2415 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002416 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002417 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002418static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002419{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002420 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002421 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002422 if (G.PS1 == NULL)
2423 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002424 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002425 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002426 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002427 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002428 if (G.PS2 == NULL)
2429 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002430}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002431static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002432{
2433 const char *prompt_str;
2434 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002435 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2436 /* Set up the prompt */
2437 if (promptmode == 0) { /* PS1 */
2438 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002439 /* bash uses $PWD value, even if it is set by user.
2440 * It uses current dir only if PWD is unset.
2441 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002442 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002443 prompt_str = G.PS1;
2444 } else
2445 prompt_str = G.PS2;
2446 } else
2447 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002448 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002449 return prompt_str;
2450}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002451static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002452{
2453 int r;
2454 const char *prompt_str;
2455
2456 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002457# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002458 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002459 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002460 if (G.flag_SIGINT) {
2461 /* There was ^C'ed, make it look prettier: */
2462 bb_putchar('\n');
2463 G.flag_SIGINT = 0;
2464 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002465 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002466 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002467 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002468 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002469 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002470 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002471 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002472 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002473 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002474 if (r != 0 && !G.flag_SIGINT)
2475 break;
2476 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002477 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2478 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002479 G.last_exitcode = 128 + SIGINT;
2480 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002481 if (r < 0) {
2482 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002483 i->p = NULL;
2484 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002485 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002486 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002487 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002488 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002489# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002490 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002491 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002492 if (i->last_char == '\0' || i->last_char == '\n') {
2493 /* Why check_and_run_traps here? Try this interactively:
2494 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2495 * $ <[enter], repeatedly...>
2496 * Without check_and_run_traps, handler never runs.
2497 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002498 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002499 fputs(prompt_str, stdout);
2500 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002501 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002502//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002503 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002504 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2505 * no ^C masking happens during fgetc, no special code for ^C:
2506 * it generates SIGINT as usual.
2507 */
2508 check_and_run_traps();
2509 if (G.flag_SIGINT)
2510 G.last_exitcode = 128 + SIGINT;
2511 if (r != '\0')
2512 break;
2513 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002514 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002515# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002516}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002517/* This is the magic location that prints prompts
2518 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002519static int fgetc_interactive(struct in_str *i)
2520{
2521 int ch;
2522 /* If it's interactive stdin, get new line. */
2523 if (G_interactive_fd && i->file == stdin) {
2524 /* Returns first char (or EOF), the rest is in i->p[] */
2525 ch = get_user_input(i);
2526 i->promptmode = 1; /* PS2 */
2527 } else {
2528 /* Not stdin: script file, sourced file, etc */
2529 do ch = fgetc(i->file); while (ch == '\0');
2530 }
2531 return ch;
2532}
2533#else
2534static inline int fgetc_interactive(struct in_str *i)
2535{
2536 int ch;
2537 do ch = fgetc(i->file); while (ch == '\0');
2538 return ch;
2539}
2540#endif /* INTERACTIVE */
2541
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002542static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002543{
2544 int ch;
2545
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002546 if (!i->file) {
2547 /* string-based in_str */
2548 ch = (unsigned char)*i->p;
2549 if (ch != '\0') {
2550 i->p++;
2551 i->last_char = ch;
2552 return ch;
2553 }
2554 return EOF;
2555 }
2556
2557 /* FILE-based in_str */
2558
Denys Vlasenko4074d492016-09-30 01:49:53 +02002559#if ENABLE_FEATURE_EDITING
2560 /* This can be stdin, check line editing char[] buffer */
2561 if (i->p && *i->p != '\0') {
2562 ch = (unsigned char)*i->p++;
2563 goto out;
2564 }
2565#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002566 /* peek_buf[] is an int array, not char. Can contain EOF. */
2567 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002568 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002569 int ch2 = i->peek_buf[1];
2570 i->peek_buf[0] = ch2;
2571 if (ch2 == 0) /* very likely, avoid redundant write */
2572 goto out;
2573 i->peek_buf[1] = 0;
2574 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002575 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002576
Denys Vlasenko4074d492016-09-30 01:49:53 +02002577 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002578 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002579 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002580 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002581 return ch;
2582}
2583
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002584static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002585{
2586 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002587
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002588 if (!i->file) {
2589 /* string-based in_str */
2590 /* Doesn't report EOF on NUL. None of the callers care. */
2591 return (unsigned char)*i->p;
2592 }
2593
2594 /* FILE-based in_str */
2595
Denys Vlasenko4074d492016-09-30 01:49:53 +02002596#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002597 /* This can be stdin, check line editing char[] buffer */
2598 if (i->p && *i->p != '\0')
2599 return (unsigned char)*i->p;
2600#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002601 /* peek_buf[] is an int array, not char. Can contain EOF. */
2602 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002603 if (ch != 0)
2604 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002605
Denys Vlasenko4074d492016-09-30 01:49:53 +02002606 /* Need to get a new char */
2607 ch = fgetc_interactive(i);
2608 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2609
2610 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2611#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2612 if (i->p) {
2613 i->p -= 1;
2614 return ch;
2615 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002616#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002617 i->peek_buf[0] = ch;
2618 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002619 return ch;
2620}
2621
Denys Vlasenko4074d492016-09-30 01:49:53 +02002622/* Only ever called if i_peek() was called, and did not return EOF.
2623 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2624 * not end-of-line. Therefore we never need to read a new editing line here.
2625 */
2626static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002627{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002628 int ch;
2629
2630 /* There are two cases when i->p[] buffer exists.
2631 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002632 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002633 * In both cases, we know that i->p[0] exists and not NUL, and
2634 * the peek2 result is in i->p[1].
2635 */
2636 if (i->p)
2637 return (unsigned char)i->p[1];
2638
2639 /* Now we know it is a file-based in_str. */
2640
2641 /* peek_buf[] is an int array, not char. Can contain EOF. */
2642 /* Is there 2nd char? */
2643 ch = i->peek_buf[1];
2644 if (ch == 0) {
2645 /* We did not read it yet, get it now */
2646 do ch = fgetc(i->file); while (ch == '\0');
2647 i->peek_buf[1] = ch;
2648 }
2649
2650 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2651 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002652}
2653
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002654static void setup_file_in_str(struct in_str *i, FILE *f)
2655{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002656 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002657 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002658 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002659 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002660}
2661
2662static void setup_string_in_str(struct in_str *i, const char *s)
2663{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002664 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002665 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002666 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002667 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002668}
2669
2670
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002671/*
2672 * o_string support
2673 */
2674#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002675
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002676static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002677{
2678 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002679 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002680 if (o->data)
2681 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002682}
2683
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002684static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002685{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002686 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002687 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002688}
2689
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002690static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2691{
2692 free(o->data);
2693}
2694
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002695static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002696{
2697 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002698 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002699 o->data = xrealloc(o->data, 1 + o->maxlen);
2700 }
2701}
2702
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002703static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002704{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002705 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002706 if (o->length < o->maxlen) {
2707 /* likely. avoid o_grow_by() call */
2708 add:
2709 o->data[o->length] = ch;
2710 o->length++;
2711 o->data[o->length] = '\0';
2712 return;
2713 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002714 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002715 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002716}
2717
Denys Vlasenko657086a2016-09-29 18:07:42 +02002718#if 0
2719/* Valid only if we know o_string is not empty */
2720static void o_delchr(o_string *o)
2721{
2722 o->length--;
2723 o->data[o->length] = '\0';
2724}
2725#endif
2726
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002727static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002728{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002729 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002730 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002731 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002732}
2733
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002734static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002735{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002736 o_addblock(o, str, strlen(str));
2737}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002738
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002739#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002740static void nommu_addchr(o_string *o, int ch)
2741{
2742 if (o)
2743 o_addchr(o, ch);
2744}
2745#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002746# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002747#endif
2748
2749static void o_addstr_with_NUL(o_string *o, const char *str)
2750{
2751 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002752}
2753
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002754/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002755 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002756 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2757 * Apparently, on unquoted $v bash still does globbing
2758 * ("v='*.txt'; echo $v" prints all .txt files),
2759 * but NOT brace expansion! Thus, there should be TWO independent
2760 * quoting mechanisms on $v expansion side: one protects
2761 * $v from brace expansion, and other additionally protects "$v" against globbing.
2762 * We have only second one.
2763 */
2764
Denys Vlasenko9e800222010-10-03 14:28:04 +02002765#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002766# define MAYBE_BRACES "{}"
2767#else
2768# define MAYBE_BRACES ""
2769#endif
2770
Eric Andersen25f27032001-04-26 23:22:31 +00002771/* My analysis of quoting semantics tells me that state information
2772 * is associated with a destination, not a source.
2773 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002774static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002775{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002776 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002777 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002778 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002779 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002780 o_grow_by(o, sz);
2781 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002782 o->data[o->length] = '\\';
2783 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002784 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002785 o->data[o->length] = ch;
2786 o->length++;
2787 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002788}
2789
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002790static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002791{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002792 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002793 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2794 && strchr("*?[\\" MAYBE_BRACES, ch)
2795 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002796 sz++;
2797 o->data[o->length] = '\\';
2798 o->length++;
2799 }
2800 o_grow_by(o, sz);
2801 o->data[o->length] = ch;
2802 o->length++;
2803 o->data[o->length] = '\0';
2804}
2805
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002806static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002807{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002808 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002809 char ch;
2810 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002811 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002812 if (ordinary_cnt > len) /* paranoia */
2813 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002814 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002815 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002816 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002817 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002818 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002819
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002820 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002821 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002822 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002823 sz++;
2824 o->data[o->length] = '\\';
2825 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002826 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002827 o_grow_by(o, sz);
2828 o->data[o->length] = ch;
2829 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002830 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002831 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002832}
2833
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002834static void o_addQblock(o_string *o, const char *str, int len)
2835{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002836 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002837 o_addblock(o, str, len);
2838 return;
2839 }
2840 o_addqblock(o, str, len);
2841}
2842
Denys Vlasenko38292b62010-09-05 14:49:40 +02002843static void o_addQstr(o_string *o, const char *str)
2844{
2845 o_addQblock(o, str, strlen(str));
2846}
2847
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002848/* A special kind of o_string for $VAR and `cmd` expansion.
2849 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002850 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002851 * list[i] contains an INDEX (int!) into this string data.
2852 * It means that if list[] needs to grow, data needs to be moved higher up
2853 * but list[i]'s need not be modified.
2854 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002855 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002856 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2857 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002858#if DEBUG_EXPAND || DEBUG_GLOB
2859static void debug_print_list(const char *prefix, o_string *o, int n)
2860{
2861 char **list = (char**)o->data;
2862 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2863 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002864
2865 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002866 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 +02002867 prefix, list, n, string_start, o->length, o->maxlen,
2868 !!(o->o_expflags & EXP_FLAG_GLOB),
2869 o->has_quoted_part,
2870 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002871 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002872 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002873 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2874 o->data + (int)(uintptr_t)list[i] + string_start,
2875 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002876 i++;
2877 }
2878 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002879 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002880 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002881 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002882 }
2883}
2884#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002885# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002886#endif
2887
2888/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2889 * in list[n] so that it points past last stored byte so far.
2890 * It returns n+1. */
2891static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002892{
2893 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002894 int string_start;
2895 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002896
2897 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002898 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2899 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002900 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002901 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002902 /* list[n] points to string_start, make space for 16 more pointers */
2903 o->maxlen += 0x10 * sizeof(list[0]);
2904 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002905 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002906 memmove(list + n + 0x10, list + n, string_len);
2907 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002908 } else {
2909 debug_printf_list("list[%d]=%d string_start=%d\n",
2910 n, string_len, string_start);
2911 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002912 } else {
2913 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002914 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2915 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002916 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2917 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002918 o->has_empty_slot = 0;
2919 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002920 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002921 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002922 return n + 1;
2923}
2924
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002925/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002926static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002927{
2928 char **list = (char**)o->data;
2929 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2930
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002931 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002932}
2933
Denys Vlasenko9e800222010-10-03 14:28:04 +02002934#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002935/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2936 * first, it processes even {a} (no commas), second,
2937 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002938 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002939 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002940
2941/* Helper */
2942static int glob_needed(const char *s)
2943{
2944 while (*s) {
2945 if (*s == '\\') {
2946 if (!s[1])
2947 return 0;
2948 s += 2;
2949 continue;
2950 }
2951 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2952 return 1;
2953 s++;
2954 }
2955 return 0;
2956}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002957/* Return pointer to next closing brace or to comma */
2958static const char *next_brace_sub(const char *cp)
2959{
2960 unsigned depth = 0;
2961 cp++;
2962 while (*cp != '\0') {
2963 if (*cp == '\\') {
2964 if (*++cp == '\0')
2965 break;
2966 cp++;
2967 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002968 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002969 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002970 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002971 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002972 depth++;
2973 }
2974
2975 return *cp != '\0' ? cp : NULL;
2976}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002977/* Recursive brace globber. Note: may garble pattern[]. */
2978static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002979{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002980 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002981 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002982 const char *next;
2983 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002984 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002985 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002986
2987 debug_printf_glob("glob_brace('%s')\n", pattern);
2988
2989 begin = pattern;
2990 while (1) {
2991 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002992 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002993 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002994 /* Find the first sub-pattern and at the same time
2995 * find the rest after the closing brace */
2996 next = next_brace_sub(begin);
2997 if (next == NULL) {
2998 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002999 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003000 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003001 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003002 /* "{abc}" with no commas - illegal
3003 * brace expr, disregard and skip it */
3004 begin = next + 1;
3005 continue;
3006 }
3007 break;
3008 }
3009 if (*begin == '\\' && begin[1] != '\0')
3010 begin++;
3011 begin++;
3012 }
3013 debug_printf_glob("begin:%s\n", begin);
3014 debug_printf_glob("next:%s\n", next);
3015
3016 /* Now find the end of the whole brace expression */
3017 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003018 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003019 rest = next_brace_sub(rest);
3020 if (rest == NULL) {
3021 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003022 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003023 }
3024 debug_printf_glob("rest:%s\n", rest);
3025 }
3026 rest_len = strlen(++rest) + 1;
3027
3028 /* We are sure the brace expression is well-formed */
3029
3030 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003031 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003032
3033 /* We have a brace expression. BEGIN points to the opening {,
3034 * NEXT points past the terminator of the first element, and REST
3035 * points past the final }. We will accumulate result names from
3036 * recursive runs for each brace alternative in the buffer using
3037 * GLOB_APPEND. */
3038
3039 p = begin + 1;
3040 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003041 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003042 memcpy(
3043 mempcpy(
3044 mempcpy(new_pattern_buf,
3045 /* We know the prefix for all sub-patterns */
3046 pattern, begin - pattern),
3047 p, next - p),
3048 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003049
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003050 /* Note: glob_brace() may garble new_pattern_buf[].
3051 * That's why we re-copy prefix every time (1st memcpy above).
3052 */
3053 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003054 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003055 /* We saw the last entry */
3056 break;
3057 }
3058 p = next + 1;
3059 next = next_brace_sub(next);
3060 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003061 free(new_pattern_buf);
3062 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003063
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003064 simple_glob:
3065 {
3066 int gr;
3067 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003068
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003069 memset(&globdata, 0, sizeof(globdata));
3070 gr = glob(pattern, 0, NULL, &globdata);
3071 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3072 if (gr != 0) {
3073 if (gr == GLOB_NOMATCH) {
3074 globfree(&globdata);
3075 /* NB: garbles parameter */
3076 unbackslash(pattern);
3077 o_addstr_with_NUL(o, pattern);
3078 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3079 return o_save_ptr_helper(o, n);
3080 }
3081 if (gr == GLOB_NOSPACE)
3082 bb_error_msg_and_die(bb_msg_memory_exhausted);
3083 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3084 * but we didn't specify it. Paranoia again. */
3085 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3086 }
3087 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3088 char **argv = globdata.gl_pathv;
3089 while (1) {
3090 o_addstr_with_NUL(o, *argv);
3091 n = o_save_ptr_helper(o, n);
3092 argv++;
3093 if (!*argv)
3094 break;
3095 }
3096 }
3097 globfree(&globdata);
3098 }
3099 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003100}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003101/* Performs globbing on last list[],
3102 * saving each result as a new list[].
3103 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003104static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003105{
3106 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003107
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003108 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003109 if (!o->data)
3110 return o_save_ptr_helper(o, n);
3111 pattern = o->data + o_get_last_ptr(o, n);
3112 debug_printf_glob("glob pattern '%s'\n", pattern);
3113 if (!glob_needed(pattern)) {
3114 /* unbackslash last string in o in place, fix length */
3115 o->length = unbackslash(pattern) - o->data;
3116 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3117 return o_save_ptr_helper(o, n);
3118 }
3119
3120 copy = xstrdup(pattern);
3121 /* "forget" pattern in o */
3122 o->length = pattern - o->data;
3123 n = glob_brace(copy, o, n);
3124 free(copy);
3125 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003126 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003127 return n;
3128}
3129
Denys Vlasenko238081f2010-10-03 14:26:26 +02003130#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003131
3132/* Helper */
3133static int glob_needed(const char *s)
3134{
3135 while (*s) {
3136 if (*s == '\\') {
3137 if (!s[1])
3138 return 0;
3139 s += 2;
3140 continue;
3141 }
3142 if (*s == '*' || *s == '[' || *s == '?')
3143 return 1;
3144 s++;
3145 }
3146 return 0;
3147}
3148/* Performs globbing on last list[],
3149 * saving each result as a new list[].
3150 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003151static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003152{
3153 glob_t globdata;
3154 int gr;
3155 char *pattern;
3156
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003157 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003158 if (!o->data)
3159 return o_save_ptr_helper(o, n);
3160 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003161 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003162 if (!glob_needed(pattern)) {
3163 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003164 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003165 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003166 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003167 return o_save_ptr_helper(o, n);
3168 }
3169
3170 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003171 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3172 * If we glob "*.\*" and don't find anything, we need
3173 * to fall back to using literal "*.*", but GLOB_NOCHECK
3174 * will return "*.\*"!
3175 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003176 gr = glob(pattern, 0, NULL, &globdata);
3177 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003178 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003179 if (gr == GLOB_NOMATCH) {
3180 globfree(&globdata);
3181 goto literal;
3182 }
3183 if (gr == GLOB_NOSPACE)
3184 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003185 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3186 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003187 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003188 }
3189 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3190 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003191 /* "forget" pattern in o */
3192 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003193 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003194 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003195 n = o_save_ptr_helper(o, n);
3196 argv++;
3197 if (!*argv)
3198 break;
3199 }
3200 }
3201 globfree(&globdata);
3202 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003203 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003204 return n;
3205}
3206
Denys Vlasenko238081f2010-10-03 14:26:26 +02003207#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003208
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003209/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003210 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003211static int o_save_ptr(o_string *o, int n)
3212{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003213 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003214 /* If o->has_empty_slot, list[n] was already globbed
3215 * (if it was requested back then when it was filled)
3216 * so don't do that again! */
3217 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003218 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003219 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003220 return o_save_ptr_helper(o, n);
3221}
3222
3223/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003224static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003225{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003226 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003227 int string_start;
3228
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003229 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3230 if (DEBUG_EXPAND)
3231 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003232 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003233 list = (char**)o->data;
3234 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3235 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003236 while (n) {
3237 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003238 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003239 }
3240 return list;
3241}
3242
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003243static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003244
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003245/* Returns pi->next - next pipe in the list */
3246static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003247{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003248 struct pipe *next;
3249 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003250
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003251 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003252 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003253 struct command *command;
3254 struct redir_struct *r, *rnext;
3255
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003256 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003257 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003258 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003259 if (DEBUG_CLEAN) {
3260 int a;
3261 char **p;
3262 for (a = 0, p = command->argv; *p; a++, p++) {
3263 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3264 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003265 }
3266 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003267 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003268 }
3269 /* not "else if": on syntax error, we may have both! */
3270 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003271 debug_printf_clean(" begin group (cmd_type:%d)\n",
3272 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003273 free_pipe_list(command->group);
3274 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003275 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003276 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003277 /* else is crucial here.
3278 * If group != NULL, child_func is meaningless */
3279#if ENABLE_HUSH_FUNCTIONS
3280 else if (command->child_func) {
3281 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3282 command->child_func->parent_cmd = NULL;
3283 }
3284#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003285#if !BB_MMU
3286 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003287 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003288#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003289 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003290 debug_printf_clean(" redirect %d%s",
3291 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003292 /* guard against the case >$FOO, where foo is unset or blank */
3293 if (r->rd_filename) {
3294 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3295 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003296 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003297 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003298 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003299 rnext = r->next;
3300 free(r);
3301 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003302 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003303 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003304 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003305 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003306#if ENABLE_HUSH_JOB
3307 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003308 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003309#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003310
3311 next = pi->next;
3312 free(pi);
3313 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003314}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003315
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003316static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003317{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003318 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003319#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003320 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003321#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003322 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003323 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003324 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003325}
3326
3327
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003328/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003329
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003330#ifndef debug_print_tree
3331static void debug_print_tree(struct pipe *pi, int lvl)
3332{
3333 static const char *const PIPE[] = {
3334 [PIPE_SEQ] = "SEQ",
3335 [PIPE_AND] = "AND",
3336 [PIPE_OR ] = "OR" ,
3337 [PIPE_BG ] = "BG" ,
3338 };
3339 static const char *RES[] = {
3340 [RES_NONE ] = "NONE" ,
3341# if ENABLE_HUSH_IF
3342 [RES_IF ] = "IF" ,
3343 [RES_THEN ] = "THEN" ,
3344 [RES_ELIF ] = "ELIF" ,
3345 [RES_ELSE ] = "ELSE" ,
3346 [RES_FI ] = "FI" ,
3347# endif
3348# if ENABLE_HUSH_LOOPS
3349 [RES_FOR ] = "FOR" ,
3350 [RES_WHILE] = "WHILE",
3351 [RES_UNTIL] = "UNTIL",
3352 [RES_DO ] = "DO" ,
3353 [RES_DONE ] = "DONE" ,
3354# endif
3355# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3356 [RES_IN ] = "IN" ,
3357# endif
3358# if ENABLE_HUSH_CASE
3359 [RES_CASE ] = "CASE" ,
3360 [RES_CASE_IN ] = "CASE_IN" ,
3361 [RES_MATCH] = "MATCH",
3362 [RES_CASE_BODY] = "CASE_BODY",
3363 [RES_ESAC ] = "ESAC" ,
3364# endif
3365 [RES_XXXX ] = "XXXX" ,
3366 [RES_SNTX ] = "SNTX" ,
3367 };
3368 static const char *const CMDTYPE[] = {
3369 "{}",
3370 "()",
3371 "[noglob]",
3372# if ENABLE_HUSH_FUNCTIONS
3373 "func()",
3374# endif
3375 };
3376
3377 int pin, prn;
3378
3379 pin = 0;
3380 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003381 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003382 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3383 prn = 0;
3384 while (prn < pi->num_cmds) {
3385 struct command *command = &pi->cmds[prn];
3386 char **argv = command->argv;
3387
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003388 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003389 lvl*2, "", prn,
3390 command->assignment_cnt);
3391 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003392 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003393 CMDTYPE[command->cmd_type],
3394 argv
3395# if !BB_MMU
3396 , " group_as_string:", command->group_as_string
3397# else
3398 , "", ""
3399# endif
3400 );
3401 debug_print_tree(command->group, lvl+1);
3402 prn++;
3403 continue;
3404 }
3405 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003406 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003407 argv++;
3408 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003409 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003410 prn++;
3411 }
3412 pi = pi->next;
3413 pin++;
3414 }
3415}
3416#endif /* debug_print_tree */
3417
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003418static struct pipe *new_pipe(void)
3419{
Eric Andersen25f27032001-04-26 23:22:31 +00003420 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003421 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003422 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003423 return pi;
3424}
3425
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003426/* Command (member of a pipe) is complete, or we start a new pipe
3427 * if ctx->command is NULL.
3428 * No errors possible here.
3429 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003430static int done_command(struct parse_context *ctx)
3431{
3432 /* The command is really already in the pipe structure, so
3433 * advance the pipe counter and make a new, null command. */
3434 struct pipe *pi = ctx->pipe;
3435 struct command *command = ctx->command;
3436
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003437#if 0 /* Instead we emit error message at run time */
3438 if (ctx->pending_redirect) {
3439 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003440 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003441 ctx->pending_redirect = NULL;
3442 }
3443#endif
3444
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003445 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003446 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003447 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003448 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003449 }
3450 pi->num_cmds++;
3451 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003452 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003453 } else {
3454 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3455 }
3456
3457 /* Only real trickiness here is that the uncommitted
3458 * command structure is not counted in pi->num_cmds. */
3459 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003460 ctx->command = command = &pi->cmds[pi->num_cmds];
3461 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003462 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003463 return pi->num_cmds; /* used only for 0/nonzero check */
3464}
3465
3466static void done_pipe(struct parse_context *ctx, pipe_style type)
3467{
3468 int not_null;
3469
3470 debug_printf_parse("done_pipe entered, followup %d\n", type);
3471 /* Close previous command */
3472 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003473#if HAS_KEYWORDS
3474 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3475 ctx->ctx_inverted = 0;
3476 ctx->pipe->res_word = ctx->ctx_res_w;
3477#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003478 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3479 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003480 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3481 * in a backgrounded subshell.
3482 */
3483 struct pipe *pi;
3484 struct command *command;
3485
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003486 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003487 pi = ctx->list_head;
3488 while (pi != ctx->pipe) {
3489 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3490 goto no_conv;
3491 pi = pi->next;
3492 }
3493
3494 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3495 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3496 pi = xzalloc(sizeof(*pi));
3497 pi->followup = PIPE_BG;
3498 pi->num_cmds = 1;
3499 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3500 command = &pi->cmds[0];
3501 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3502 command->cmd_type = CMD_NORMAL;
3503 command->group = ctx->list_head;
3504#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003505 command->group_as_string = xstrndup(
3506 ctx->as_string.data,
3507 ctx->as_string.length - 1 /* do not copy last char, "&" */
3508 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003509#endif
3510 /* Replace all pipes in ctx with one newly created */
3511 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003512 } else {
3513 no_conv:
3514 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003515 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003516
3517 /* Without this check, even just <enter> on command line generates
3518 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003519 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003520 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003521#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003522 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003523#endif
3524#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003525 || ctx->ctx_res_w == RES_DONE
3526 || ctx->ctx_res_w == RES_FOR
3527 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003528#endif
3529#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003530 || ctx->ctx_res_w == RES_ESAC
3531#endif
3532 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003533 struct pipe *new_p;
3534 debug_printf_parse("done_pipe: adding new pipe: "
3535 "not_null:%d ctx->ctx_res_w:%d\n",
3536 not_null, ctx->ctx_res_w);
3537 new_p = new_pipe();
3538 ctx->pipe->next = new_p;
3539 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003540 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003541 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003542 * This is used to control execution.
3543 * RES_FOR and RES_IN are NOT sticky (needed to support
3544 * cases where variable or value happens to match a keyword):
3545 */
3546#if ENABLE_HUSH_LOOPS
3547 if (ctx->ctx_res_w == RES_FOR
3548 || ctx->ctx_res_w == RES_IN)
3549 ctx->ctx_res_w = RES_NONE;
3550#endif
3551#if ENABLE_HUSH_CASE
3552 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003553 ctx->ctx_res_w = RES_CASE_BODY;
3554 if (ctx->ctx_res_w == RES_CASE)
3555 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003556#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003557 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003558 /* Create the memory for command, roughly:
3559 * ctx->pipe->cmds = new struct command;
3560 * ctx->command = &ctx->pipe->cmds[0];
3561 */
3562 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003563 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003564 }
3565 debug_printf_parse("done_pipe return\n");
3566}
3567
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003568static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003569{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003570 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003571 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003572 /* Create the memory for command, roughly:
3573 * ctx->pipe->cmds = new struct command;
3574 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003575 */
3576 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003577}
3578
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003579/* If a reserved word is found and processed, parse context is modified
3580 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003581 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003582#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003583struct reserved_combo {
3584 char literal[6];
3585 unsigned char res;
3586 unsigned char assignment_flag;
3587 int flag;
3588};
3589enum {
3590 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003591# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003592 FLAG_IF = (1 << RES_IF ),
3593 FLAG_THEN = (1 << RES_THEN ),
3594 FLAG_ELIF = (1 << RES_ELIF ),
3595 FLAG_ELSE = (1 << RES_ELSE ),
3596 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003597# endif
3598# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003599 FLAG_FOR = (1 << RES_FOR ),
3600 FLAG_WHILE = (1 << RES_WHILE),
3601 FLAG_UNTIL = (1 << RES_UNTIL),
3602 FLAG_DO = (1 << RES_DO ),
3603 FLAG_DONE = (1 << RES_DONE ),
3604 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003605# endif
3606# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003607 FLAG_MATCH = (1 << RES_MATCH),
3608 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003609# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003610 FLAG_START = (1 << RES_XXXX ),
3611};
3612
3613static const struct reserved_combo* match_reserved_word(o_string *word)
3614{
Eric Andersen25f27032001-04-26 23:22:31 +00003615 /* Mostly a list of accepted follow-up reserved words.
3616 * FLAG_END means we are done with the sequence, and are ready
3617 * to turn the compound list into a command.
3618 * FLAG_START means the word must start a new compound list.
3619 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003620 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003621# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003622 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3623 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3624 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3625 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3626 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3627 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003628# endif
3629# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003630 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3631 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3632 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3633 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3634 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3635 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003636# endif
3637# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003638 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3639 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003640# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003641 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003642 const struct reserved_combo *r;
3643
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003644 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003645 if (strcmp(word->data, r->literal) == 0)
3646 return r;
3647 }
3648 return NULL;
3649}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003650/* Return 0: not a keyword, 1: keyword
3651 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003652static int reserved_word(o_string *word, struct parse_context *ctx)
3653{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003654# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003655 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003656 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003657 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003658# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003659 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003660
Denys Vlasenko38292b62010-09-05 14:49:40 +02003661 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003662 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003663 r = match_reserved_word(word);
3664 if (!r)
3665 return 0;
3666
3667 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003668# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003669 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3670 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003671 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003672 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003673# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003674 if (r->flag == 0) { /* '!' */
3675 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003676 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003677 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003678 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003679 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003680 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003681 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003682 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003683 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003684
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003685 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003686 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003687 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003688 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003689 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003690 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003691 ctx->ctx_res_w = RES_SNTX;
3692 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003693 } else {
3694 /* "{...} fi" is ok. "{...} if" is not
3695 * Example:
3696 * if { echo foo; } then { echo bar; } fi */
3697 if (ctx->command->group)
3698 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003699 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003700
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003701 ctx->ctx_res_w = r->res;
3702 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003703 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003704 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003705
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003706 if (ctx->old_flag & FLAG_END) {
3707 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003708
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003709 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003710 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003711 old = ctx->stack;
3712 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003713 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003714# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003715 /* At this point, the compound command's string is in
3716 * ctx->as_string... except for the leading keyword!
3717 * Consider this example: "echo a | if true; then echo a; fi"
3718 * ctx->as_string will contain "true; then echo a; fi",
3719 * with "if " remaining in old->as_string!
3720 */
3721 {
3722 char *str;
3723 int len = old->as_string.length;
3724 /* Concatenate halves */
3725 o_addstr(&old->as_string, ctx->as_string.data);
3726 o_free_unsafe(&ctx->as_string);
3727 /* Find where leading keyword starts in first half */
3728 str = old->as_string.data + len;
3729 if (str > old->as_string.data)
3730 str--; /* skip whitespace after keyword */
3731 while (str > old->as_string.data && isalpha(str[-1]))
3732 str--;
3733 /* Ugh, we're done with this horrid hack */
3734 old->command->group_as_string = xstrdup(str);
3735 debug_printf_parse("pop, remembering as:'%s'\n",
3736 old->command->group_as_string);
3737 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003738# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003739 *ctx = *old; /* physical copy */
3740 free(old);
3741 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003742 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003743}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003744#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003745
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003746/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003747 * Normal return is 0. Syntax errors return 1.
3748 * Note: on return, word is reset, but not o_free'd!
3749 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003750static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003751{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003752 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003753
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003754 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003755 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003756 debug_printf_parse("done_word return 0: true null, ignored\n");
3757 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003758 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003759
Eric Andersen25f27032001-04-26 23:22:31 +00003760 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003761 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3762 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003763 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3764 * "2.7 Redirection
3765 * ...the word that follows the redirection operator
3766 * shall be subjected to tilde expansion, parameter expansion,
3767 * command substitution, arithmetic expansion, and quote
3768 * removal. Pathname expansion shall not be performed
3769 * on the word by a non-interactive shell; an interactive
3770 * shell may perform it, but shall do so only when
3771 * the expansion would result in one word."
3772 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003773 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003774 /* Cater for >\file case:
3775 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3776 * Same with heredocs:
3777 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3778 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003779 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3780 unbackslash(ctx->pending_redirect->rd_filename);
3781 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003782 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003783 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3784 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003785 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003786 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003787 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003788 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003789#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003790# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003791 if (ctx->ctx_dsemicolon
3792 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3793 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003794 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003795 /* ctx->ctx_res_w = RES_MATCH; */
3796 ctx->ctx_dsemicolon = 0;
3797 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003798# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003799 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003800# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003801 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3802 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003803# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003804# if ENABLE_HUSH_CASE
3805 && ctx->ctx_res_w != RES_CASE
3806# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003807 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003808 int reserved = reserved_word(word, ctx);
3809 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3810 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003811 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003812 debug_printf_parse("done_word return %d\n",
3813 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003814 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003815 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01003816# if BASH_TEST2
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003817 if (strcmp(word->data, "[[") == 0) {
3818 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3819 }
3820 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003821# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003822 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003823#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003824 if (command->group) {
3825 /* "{ echo foo; } echo bar" - bad */
3826 syntax_error_at(word->data);
3827 debug_printf_parse("done_word return 1: syntax error, "
3828 "groups and arglists don't mix\n");
3829 return 1;
3830 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003831
3832 /* If this word wasn't an assignment, next ones definitely
3833 * can't be assignments. Even if they look like ones. */
3834 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3835 && word->o_assignment != WORD_IS_KEYWORD
3836 ) {
3837 word->o_assignment = NOT_ASSIGNMENT;
3838 } else {
3839 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3840 command->assignment_cnt++;
3841 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3842 }
3843 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3844 word->o_assignment = MAYBE_ASSIGNMENT;
3845 }
3846 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003847 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003848 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003849 }
Eric Andersen25f27032001-04-26 23:22:31 +00003850
Denis Vlasenko06810332007-05-21 23:30:54 +00003851#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003852 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003853 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003854 || !is_well_formed_var_name(command->argv[0], '\0')
3855 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003856 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003857 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003858 return 1;
3859 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003860 /* Force FOR to have just one word (variable name) */
3861 /* NB: basically, this makes hush see "for v in ..."
3862 * syntax as if it is "for v; in ...". FOR and IN become
3863 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003864 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003865 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003866#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003867#if ENABLE_HUSH_CASE
3868 /* Force CASE to have just one word */
3869 if (ctx->ctx_res_w == RES_CASE) {
3870 done_pipe(ctx, PIPE_SEQ);
3871 }
3872#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003873
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003874 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003875
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003876 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003877 return 0;
3878}
3879
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003880
3881/* Peek ahead in the input to find out if we have a "&n" construct,
3882 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003883 * Return:
3884 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3885 * REDIRFD_SYNTAX_ERR if syntax error,
3886 * REDIRFD_TO_FILE if no & was seen,
3887 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003888 */
3889#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003890#define parse_redir_right_fd(as_string, input) \
3891 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003892#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003893static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003894{
3895 int ch, d, ok;
3896
3897 ch = i_peek(input);
3898 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003899 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003900
3901 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003902 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003903 ch = i_peek(input);
3904 if (ch == '-') {
3905 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003906 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003907 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003908 }
3909 d = 0;
3910 ok = 0;
3911 while (ch != EOF && isdigit(ch)) {
3912 d = d*10 + (ch-'0');
3913 ok = 1;
3914 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003915 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003916 ch = i_peek(input);
3917 }
3918 if (ok) return d;
3919
3920//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3921
3922 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003923 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003924}
3925
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003926/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003927 */
3928static int parse_redirect(struct parse_context *ctx,
3929 int fd,
3930 redir_type style,
3931 struct in_str *input)
3932{
3933 struct command *command = ctx->command;
3934 struct redir_struct *redir;
3935 struct redir_struct **redirp;
3936 int dup_num;
3937
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003938 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003939 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003940 /* Check for a '>&1' type redirect */
3941 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3942 if (dup_num == REDIRFD_SYNTAX_ERR)
3943 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003944 } else {
3945 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003946 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003947 if (dup_num) { /* <<-... */
3948 ch = i_getch(input);
3949 nommu_addchr(&ctx->as_string, ch);
3950 ch = i_peek(input);
3951 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003952 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003953
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003954 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003955 int ch = i_peek(input);
3956 if (ch == '|') {
3957 /* >|FILE redirect ("clobbering" >).
3958 * Since we do not support "set -o noclobber" yet,
3959 * >| and > are the same for now. Just eat |.
3960 */
3961 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003962 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003963 }
3964 }
3965
3966 /* Create a new redir_struct and append it to the linked list */
3967 redirp = &command->redirects;
3968 while ((redir = *redirp) != NULL) {
3969 redirp = &(redir->next);
3970 }
3971 *redirp = redir = xzalloc(sizeof(*redir));
3972 /* redir->next = NULL; */
3973 /* redir->rd_filename = NULL; */
3974 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003975 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003976
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003977 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3978 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003979
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003980 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003981 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003982 /* Erik had a check here that the file descriptor in question
3983 * is legit; I postpone that to "run time"
3984 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003985 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3986 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003987 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003988#if 0 /* Instead we emit error message at run time */
3989 if (ctx->pending_redirect) {
3990 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02003991 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003992 }
3993#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003994 /* Set ctx->pending_redirect, so we know what to do at the
3995 * end of the next parsed word. */
3996 ctx->pending_redirect = redir;
3997 }
3998 return 0;
3999}
4000
Eric Andersen25f27032001-04-26 23:22:31 +00004001/* If a redirect is immediately preceded by a number, that number is
4002 * supposed to tell which file descriptor to redirect. This routine
4003 * looks for such preceding numbers. In an ideal world this routine
4004 * needs to handle all the following classes of redirects...
4005 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4006 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4007 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4008 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004009 *
4010 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4011 * "2.7 Redirection
4012 * ... If n is quoted, the number shall not be recognized as part of
4013 * the redirection expression. For example:
4014 * echo \2>a
4015 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004016 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004017 *
4018 * A -1 return means no valid number was found,
4019 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004020 */
4021static int redirect_opt_num(o_string *o)
4022{
4023 int num;
4024
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004025 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004026 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004027 num = bb_strtou(o->data, NULL, 10);
4028 if (errno || num < 0)
4029 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004030 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004031 return num;
4032}
4033
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004034#if BB_MMU
4035#define fetch_till_str(as_string, input, word, skip_tabs) \
4036 fetch_till_str(input, word, skip_tabs)
4037#endif
4038static char *fetch_till_str(o_string *as_string,
4039 struct in_str *input,
4040 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004041 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004042{
4043 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004044 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004045 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004046 int ch;
4047
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004048 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004049
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004050 while (1) {
4051 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004052 if (ch != EOF)
4053 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004054 if (ch == '\n' || ch == EOF) {
4055 check_heredoc_end:
4056 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4057 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4058 heredoc.data[past_EOL] = '\0';
4059 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4060 return heredoc.data;
4061 }
4062 if (ch == '\n') {
4063 /* This is a new line.
4064 * Remember position and backslash-escaping status.
4065 */
4066 o_addchr(&heredoc, ch);
4067 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004068 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004069 past_EOL = heredoc.length;
4070 /* Get 1st char of next line, possibly skipping leading tabs */
4071 do {
4072 ch = i_getch(input);
4073 if (ch != EOF)
4074 nommu_addchr(as_string, ch);
4075 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4076 /* If this immediately ended the line,
4077 * go back to end-of-line checks.
4078 */
4079 if (ch == '\n')
4080 goto check_heredoc_end;
4081 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004082 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004083 }
4084 if (ch == EOF) {
4085 o_free_unsafe(&heredoc);
4086 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004087 }
4088 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004089 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004090 if (prev == '\\' && ch == '\\')
4091 /* Correctly handle foo\\<eol> (not a line cont.) */
4092 prev = 0; /* not \ */
4093 else
4094 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004095 }
4096}
4097
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004098/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4099 * and load them all. There should be exactly heredoc_cnt of them.
4100 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004101static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4102{
4103 struct pipe *pi = ctx->list_head;
4104
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004105 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004106 int i;
4107 struct command *cmd = pi->cmds;
4108
4109 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4110 pi->num_cmds,
4111 cmd->argv ? cmd->argv[0] : "NONE");
4112 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004113 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004114
4115 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4116 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004117 while (redir) {
4118 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004119 char *p;
4120
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004121 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004122 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004123 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004124 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004125 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004126 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004127 return 1;
4128 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004129 free(redir->rd_filename);
4130 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004131 heredoc_cnt--;
4132 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004133 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004134 }
4135 cmd++;
4136 }
4137 pi = pi->next;
4138 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004139#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004140 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004141 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004142 bb_error_msg_and_die("heredoc BUG 2");
4143#endif
4144 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004145}
4146
4147
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004148static int run_list(struct pipe *pi);
4149#if BB_MMU
4150#define parse_stream(pstring, input, end_trigger) \
4151 parse_stream(input, end_trigger)
4152#endif
4153static struct pipe *parse_stream(char **pstring,
4154 struct in_str *input,
4155 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004156
Eric Andersen25f27032001-04-26 23:22:31 +00004157
Denys Vlasenkoc2704542009-11-20 19:14:19 +01004158#if !ENABLE_HUSH_FUNCTIONS
4159#define parse_group(dest, ctx, input, ch) \
4160 parse_group(ctx, input, ch)
4161#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004162static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004163 struct in_str *input, int ch)
4164{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004165 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004166 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004167 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004168 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004169 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004170 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004171
4172 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004173#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02004174 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004175 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004176 if (done_word(dest, ctx))
4177 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004178 if (!command->argv)
4179 goto skip; /* (... */
4180 if (command->argv[1]) { /* word word ... (... */
4181 syntax_error_unexpected_ch('(');
4182 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004183 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004184 /* it is "word(..." or "word (..." */
4185 do
4186 ch = i_getch(input);
4187 while (ch == ' ' || ch == '\t');
4188 if (ch != ')') {
4189 syntax_error_unexpected_ch(ch);
4190 return 1;
4191 }
4192 nommu_addchr(&ctx->as_string, ch);
4193 do
4194 ch = i_getch(input);
4195 while (ch == ' ' || ch == '\t' || ch == '\n');
4196 if (ch != '{') {
4197 syntax_error_unexpected_ch(ch);
4198 return 1;
4199 }
4200 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004201 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004202 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004203 }
4204#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004205
4206#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004207 if (command->argv /* word [word]{... */
4208 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004209 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004210 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004211 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004212 debug_printf_parse("parse_group return 1: "
4213 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004214 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004215 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004216#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004217
4218#if ENABLE_HUSH_FUNCTIONS
4219 skip:
4220#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004221 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004222 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004223 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004224 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004225 } else {
4226 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004227 ch = i_peek(input);
4228 if (ch != ' ' && ch != '\t' && ch != '\n'
4229 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4230 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004231 syntax_error_unexpected_ch(ch);
4232 return 1;
4233 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004234 if (ch != '(') {
4235 ch = i_getch(input);
4236 nommu_addchr(&ctx->as_string, ch);
4237 }
Eric Andersen25f27032001-04-26 23:22:31 +00004238 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004239
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004240 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004241#if BB_MMU
4242# define as_string NULL
4243#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004244 char *as_string = NULL;
4245#endif
4246 pipe_list = parse_stream(&as_string, input, endch);
4247#if !BB_MMU
4248 if (as_string)
4249 o_addstr(&ctx->as_string, as_string);
4250#endif
4251 /* empty ()/{} or parse error? */
4252 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00004253 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004254 if (!BB_MMU)
4255 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004256 debug_printf_parse("parse_group return 1: "
4257 "parse_stream returned %p\n", pipe_list);
4258 return 1;
4259 }
4260 command->group = pipe_list;
4261#if !BB_MMU
4262 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4263 command->group_as_string = as_string;
4264 debug_printf_parse("end of group, remembering as:'%s'\n",
4265 command->group_as_string);
4266#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004267#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004268 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004269 debug_printf_parse("parse_group return 0\n");
4270 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004271 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004272}
4273
Denys Vlasenko46e64982016-09-29 19:50:55 +02004274static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4275{
4276 for (;;) {
4277 int ch, ch2;
4278
4279 ch = i_getch(input);
4280 if (ch != '\\')
4281 return ch;
4282 ch2 = i_peek(input);
4283 if (ch2 != '\n')
4284 return ch;
4285 /* backslash+newline, skip it */
4286 i_getch(input);
4287 }
4288}
4289
Denys Vlasenko657086a2016-09-29 18:07:42 +02004290static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4291{
4292 for (;;) {
4293 int ch, ch2;
4294
4295 ch = i_peek(input);
4296 if (ch != '\\')
4297 return ch;
4298 ch2 = i_peek2(input);
4299 if (ch2 != '\n')
4300 return ch;
4301 /* backslash+newline, skip it */
4302 i_getch(input);
4303 i_getch(input);
4304 }
4305}
4306
Denys Vlasenko0b883582016-12-23 16:49:07 +01004307#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004308/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004309static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004310/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004311static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004312{
4313 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004314 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004315 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004316 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004317 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004318 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004319 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004320 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004321 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004322 }
4323}
4324/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004325static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004326{
4327 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004328 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004329 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004330 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004331 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004332 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004333 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004334 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004335 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004336 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004337 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004338 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004339 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004340 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004341 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4342 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004343 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004344 continue;
4345 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004346 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004347 }
4348}
4349/* Process `cmd` - copy contents until "`" is seen. Complicated by
4350 * \` quoting.
4351 * "Within the backquoted style of command substitution, backslash
4352 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4353 * The search for the matching backquote shall be satisfied by the first
4354 * backquote found without a preceding backslash; during this search,
4355 * if a non-escaped backquote is encountered within a shell comment,
4356 * a here-document, an embedded command substitution of the $(command)
4357 * form, or a quoted string, undefined results occur. A single-quoted
4358 * or double-quoted string that begins, but does not end, within the
4359 * "`...`" sequence produces undefined results."
4360 * Example Output
4361 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4362 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004363static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004364{
4365 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004366 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004367 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004368 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004369 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004370 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4371 ch = i_getch(input);
4372 if (ch != '`'
4373 && ch != '$'
4374 && ch != '\\'
4375 && (!in_dquote || ch != '"')
4376 ) {
4377 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004378 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004379 }
4380 if (ch == EOF) {
4381 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004382 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004383 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004384 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004385 }
4386}
4387/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4388 * quoting and nested ()s.
4389 * "With the $(command) style of command substitution, all characters
4390 * following the open parenthesis to the matching closing parenthesis
4391 * constitute the command. Any valid shell script can be used for command,
4392 * except a script consisting solely of redirections which produces
4393 * unspecified results."
4394 * Example Output
4395 * echo $(echo '(TEST)' BEST) (TEST) BEST
4396 * echo $(echo 'TEST)' BEST) TEST) BEST
4397 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004398 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004399 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004400 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004401 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4402 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004403 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004404#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004405static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004406{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004407 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004408 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004409# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004410 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004411# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004412 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4413
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004414 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004415 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004416 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004417 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004418 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004419 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004420 if (ch == end_ch
4421# if BASH_SUBSTR || BASH_PATTERN_SUBST
4422 || ch == end_char2
4423# endif
4424 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004425 if (!dbl)
4426 break;
4427 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004428 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004429 i_getch(input); /* eat second ')' */
4430 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004431 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004432 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004433 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004434 if (ch == '(' || ch == '{') {
4435 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004436 if (!add_till_closing_bracket(dest, input, ch))
4437 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004438 o_addchr(dest, ch);
4439 continue;
4440 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004441 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004442 if (!add_till_single_quote(dest, input))
4443 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004444 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004445 continue;
4446 }
4447 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004448 if (!add_till_double_quote(dest, input))
4449 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004450 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004451 continue;
4452 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004453 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004454 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4455 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004456 o_addchr(dest, ch);
4457 continue;
4458 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004459 if (ch == '\\') {
4460 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004461 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004462 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004463 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004464 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004465 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004466#if 0
4467 if (ch == '\n') {
4468 /* "backslash+newline", ignore both */
4469 o_delchr(dest); /* undo insertion of '\' */
4470 continue;
4471 }
4472#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004473 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004474 continue;
4475 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004476 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004477 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004478}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004479#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004480
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004481/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004482#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004483#define parse_dollar(as_string, dest, input, quote_mask) \
4484 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004485#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004486#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004487static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004488 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004489 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004490{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004491 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004492
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004493 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004494 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004495 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004496 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004497 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004498 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004499 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004500 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004501 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004502 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004503 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004504 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004505 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004506 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004507 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004508 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004509 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004510 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004511 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004512 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004513 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004514 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004515 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004516 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004517 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004518 o_addchr(dest, ch | quote_mask);
4519 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004520 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004521 case '$': /* pid */
4522 case '!': /* last bg pid */
4523 case '?': /* last exit code */
4524 case '#': /* number of args */
4525 case '*': /* args */
4526 case '@': /* args */
4527 goto make_one_char_var;
4528 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004529 char len_single_ch;
4530
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004531 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4532
Denys Vlasenko74369502010-05-21 19:52:01 +02004533 ch = i_getch(input); /* eat '{' */
4534 nommu_addchr(as_string, ch);
4535
Denys Vlasenko46e64982016-09-29 19:50:55 +02004536 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004537 /* It should be ${?}, or ${#var},
4538 * or even ${?+subst} - operator acting on a special variable,
4539 * or the beginning of variable name.
4540 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004541 if (ch == EOF
4542 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4543 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004544 bad_dollar_syntax:
4545 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004546 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4547 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004548 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004549 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004550 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004551 ch |= quote_mask;
4552
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004553 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004554 * However, this regresses some of our testsuite cases
4555 * which check invalid constructs like ${%}.
4556 * Oh well... let's check that the var name part is fine... */
4557
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004558 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004559 unsigned pos;
4560
Denys Vlasenko74369502010-05-21 19:52:01 +02004561 o_addchr(dest, ch);
4562 debug_printf_parse(": '%c'\n", ch);
4563
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004564 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004565 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004566 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004567 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004568
Denys Vlasenko74369502010-05-21 19:52:01 +02004569 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004570 unsigned end_ch;
4571 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004572 /* handle parameter expansions
4573 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4574 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004575 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4576 if (len_single_ch != '#'
4577 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4578 || i_peek(input) != '}'
4579 ) {
4580 goto bad_dollar_syntax;
4581 }
4582 /* else: it's "length of C" ${#C} op,
4583 * where C is a single char
4584 * special var name, e.g. ${#!}.
4585 */
4586 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004587 /* Eat everything until closing '}' (or ':') */
4588 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004589 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004590 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004591 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004592 ) {
4593 /* It's ${var:N[:M]} thing */
4594 end_ch = '}' * 0x100 + ':';
4595 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004596 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004597 && ch == '/'
4598 ) {
4599 /* It's ${var/[/]pattern[/repl]} thing */
4600 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4601 i_getch(input);
4602 nommu_addchr(as_string, '/');
4603 ch = '\\';
4604 }
4605 end_ch = '}' * 0x100 + '/';
4606 }
4607 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004608 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004609 if (!BB_MMU)
4610 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004611#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004612 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004613 if (last_ch == 0) /* error? */
4614 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004615#else
4616#error Simple code to only allow ${var} is not implemented
4617#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004618 if (as_string) {
4619 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004620 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004621 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004622
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004623 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4624 && (end_ch & 0xff00)
4625 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004626 /* close the first block: */
4627 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004628 /* while parsing N from ${var:N[:M]}
4629 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004630 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004631 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004632 end_ch = '}';
4633 goto again;
4634 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004635 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004636 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004637 /* it's ${var:N} - emulate :999999999 */
4638 o_addstr(dest, "999999999");
4639 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004640 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004641 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004642 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004643 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004644 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004645 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4646 break;
4647 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004648#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004649 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004650 unsigned pos;
4651
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004652 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004653 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004654# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004655 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004656 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004657 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004658 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4659 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004660 if (!BB_MMU)
4661 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004662 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4663 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004664 if (as_string) {
4665 o_addstr(as_string, dest->data + pos);
4666 o_addchr(as_string, ')');
4667 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004668 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004669 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004670 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004671 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004672# endif
4673# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004674 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4675 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004676 if (!BB_MMU)
4677 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004678 if (!add_till_closing_bracket(dest, input, ')'))
4679 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004680 if (as_string) {
4681 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004682 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004683 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004684 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004685# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004686 break;
4687 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004688#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004689 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004690 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004691 nommu_addchr(as_string, ch);
Denys Vlasenko657086a2016-09-29 18:07:42 +02004692 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004693 if (isalnum(ch)) { /* it's $_name or $_123 */
4694 ch = '_';
4695 goto make_var;
4696 }
4697 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004698 /* TODO: $_ and $-: */
4699 /* $_ Shell or shell script name; or last argument of last command
4700 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4701 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004702 /* $- Option flags set by set builtin or shell options (-i etc) */
4703 default:
4704 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004705 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004706 debug_printf_parse("parse_dollar return 1 (ok)\n");
4707 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004708#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004709}
4710
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004711#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004712# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004713#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4714 encode_string(dest, input, dquote_end, process_bkslash)
4715# else
4716/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4717#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4718 encode_string(dest, input, dquote_end)
4719# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004720#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004721
4722#else /* !MMU */
4723
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004724# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004725/* all parameters are needed, no macro tricks */
4726# else
4727#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4728 encode_string(as_string, dest, input, dquote_end)
4729# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004730#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004731static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004732 o_string *dest,
4733 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004734 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004735 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004736{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004737#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004738 const int process_bkslash = 1;
4739#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004740 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004741 int next;
4742
4743 again:
4744 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004745 if (ch != EOF)
4746 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004747 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004748 debug_printf_parse("encode_string return 1 (ok)\n");
4749 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004750 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004751 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004752 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004753 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004754 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004755 }
4756 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004757 if (ch != '\n') {
4758 next = i_peek(input);
4759 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004760 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004761 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004762 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004763 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004764 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004765 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004766 }
4767 /* bash:
4768 * "The backslash retains its special meaning [in "..."]
4769 * only when followed by one of the following characters:
4770 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004771 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004772 * NB: in (unquoted) heredoc, above does not apply to ",
4773 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004774 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004775 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004776 ch = i_getch(input); /* eat next */
4777 if (ch == '\n')
4778 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004779 } /* else: ch remains == '\\', and we double it below: */
4780 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004781 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004782 goto again;
4783 }
4784 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004785 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4786 debug_printf_parse("encode_string return 0: "
4787 "parse_dollar returned 0 (error)\n");
4788 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004789 }
4790 goto again;
4791 }
4792#if ENABLE_HUSH_TICK
4793 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004794 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004795 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4796 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004797 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4798 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004799 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4800 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004801 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004802 }
4803#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004804 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004805 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004806#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004807}
4808
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004809/*
4810 * Scan input until EOF or end_trigger char.
4811 * Return a list of pipes to execute, or NULL on EOF
4812 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004813 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004814 * reset parsing machinery and start parsing anew,
4815 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004816 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004817static struct pipe *parse_stream(char **pstring,
4818 struct in_str *input,
4819 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004820{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004821 struct parse_context ctx;
4822 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004823 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004824
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004825 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004826 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004827 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004828 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004829 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004830 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004831
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004832 /* If very first arg is "" or '', dest.data may end up NULL.
4833 * Preventing this: */
4834 o_addchr(&dest, '\0');
4835 dest.length = 0;
4836
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004837 /* We used to separate words on $IFS here. This was wrong.
4838 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004839 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004840 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004841
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004842 if (MAYBE_ASSIGNMENT != 0)
4843 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004844 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004845 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004846 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004847 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004848 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004849 int ch;
4850 int next;
4851 int redir_fd;
4852 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004853
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004854 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004855 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004856 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004857 if (ch == EOF) {
4858 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004859
4860 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004861 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004862 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004863 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004864 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004865 syntax_error_unterm_ch('(');
4866 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004867 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004868 if (end_trigger == '}') {
4869 syntax_error_unterm_ch('{');
4870 goto parse_error;
4871 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004872
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004873 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004874 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004875 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004876 o_free(&dest);
4877 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004878 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004879 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004880 /* (this makes bare "&" cmd a no-op.
4881 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004882 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004883 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004884 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004885 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004886 pi = NULL;
4887 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004888#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004889 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004890 if (pstring)
4891 *pstring = ctx.as_string.data;
4892 else
4893 o_free_unsafe(&ctx.as_string);
4894#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004895 debug_leave();
4896 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004897 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004898 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004899 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004900
4901 next = '\0';
4902 if (ch != '\n')
4903 next = i_peek(input);
4904
4905 is_special = "{}<>;&|()#'" /* special outside of "str" */
Denys Vlasenko932b9972018-01-11 12:39:48 +01004906 "\\$\"" IF_HUSH_TICK("`") /* always special */
4907 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004908 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004909 if (ctx.command->argv /* word [word]{... - non-special */
4910 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004911 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004912 || (next != ';' /* }; - special */
4913 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004914 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004915 && next != '&' /* }& and }&& ... - special */
4916 && next != '|' /* }|| ... - special */
4917 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004918 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004919 ) {
4920 /* They are not special, skip "{}" */
4921 is_special += 2;
4922 }
4923 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004924 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004925
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004926 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004927 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004928 o_addQchr(&dest, ch);
4929 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4930 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004931 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004932 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004933 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004934 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004935 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004936 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004937 continue;
4938 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004939
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004940 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004941 if (done_word(&dest, &ctx)) {
4942 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004943 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004944 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004945 /* Is this a case when newline is simply ignored?
4946 * Some examples:
4947 * "cmd | <newline> cmd ..."
4948 * "case ... in <newline> word) ..."
4949 */
4950 if (IS_NULL_CMD(ctx.command)
4951 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004952 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004953 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004954 * Without check #1, interactive shell
4955 * ignores even bare <newline>,
4956 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004957 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004958 * ps2> _ <=== wrong, should be ps1
4959 * Without check #2, "cmd & <newline>"
4960 * is similarly mistreated.
4961 * (BTW, this makes "cmd & cmd"
4962 * and "cmd && cmd" non-orthogonal.
4963 * Really, ask yourself, why
4964 * "cmd && <newline>" doesn't start
4965 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02004966 * The only reason is that it might be
4967 * a "cmd1 && <nl> cmd2 &" construct,
4968 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004969 */
4970 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004971 if (pi->num_cmds != 0 /* check #1 */
4972 && pi->followup != PIPE_BG /* check #2 */
4973 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004974 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004975 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004976 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004977 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004978 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004979 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4980 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004981 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004982 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004983 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004984 heredoc_cnt = 0;
4985 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004986 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004987 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004988 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004989 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004990 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004991 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004992 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004993
4994 /* "cmd}" or "cmd }..." without semicolon or &:
4995 * } is an ordinary char in this case, even inside { cmd; }
4996 * Pathological example: { ""}; } should exec "}" cmd
4997 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004998 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004999 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005000 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005001 ) {
5002 goto ordinary_char;
5003 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005004 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5005 /* Generally, there should be semicolon: "cmd; }"
5006 * However, bash allows to omit it if "cmd" is
5007 * a group. Examples:
5008 * { { echo 1; } }
5009 * {(echo 1)}
5010 * { echo 0 >&2 | { echo 1; } }
5011 * { while false; do :; done }
5012 * { case a in b) ;; esac }
5013 */
5014 if (ctx.command->group)
5015 goto term_group;
5016 goto ordinary_char;
5017 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005018 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005019 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005020 goto skip_end_trigger;
5021 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005022 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005023 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005024 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005025 && (ch != ';' || heredoc_cnt == 0)
5026#if ENABLE_HUSH_CASE
5027 && (ch != ')'
5028 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02005029 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005030 )
5031#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005032 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005033 if (heredoc_cnt) {
5034 /* This is technically valid:
5035 * { cat <<HERE; }; echo Ok
5036 * heredoc
5037 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005038 * HERE
5039 * but we don't support this.
5040 * We require heredoc to be in enclosing {}/(),
5041 * if any.
5042 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005043 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005044 goto parse_error;
5045 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005046 if (done_word(&dest, &ctx)) {
5047 goto parse_error;
5048 }
5049 done_pipe(&ctx, PIPE_SEQ);
5050 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005051 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005052 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005053 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005054 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005055 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005056 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005057#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005058 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005059 if (pstring)
5060 *pstring = ctx.as_string.data;
5061 else
5062 o_free_unsafe(&ctx.as_string);
5063#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005064 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5065 /* Example: bare "{ }", "()" */
5066 G.last_exitcode = 2; /* bash compat */
5067 syntax_error_unexpected_ch(ch);
5068 goto parse_error2;
5069 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005070 debug_printf_parse("parse_stream return %p: "
5071 "end_trigger char found\n",
5072 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005073 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005074 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005075 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005076 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005077 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005078 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005079 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005080
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005081 /* Catch <, > before deciding whether this word is
5082 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5083 switch (ch) {
5084 case '>':
5085 redir_fd = redirect_opt_num(&dest);
5086 if (done_word(&dest, &ctx)) {
5087 goto parse_error;
5088 }
5089 redir_style = REDIRECT_OVERWRITE;
5090 if (next == '>') {
5091 redir_style = REDIRECT_APPEND;
5092 ch = i_getch(input);
5093 nommu_addchr(&ctx.as_string, ch);
5094 }
5095#if 0
5096 else if (next == '(') {
5097 syntax_error(">(process) not supported");
5098 goto parse_error;
5099 }
5100#endif
5101 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5102 goto parse_error;
5103 continue; /* back to top of while (1) */
5104 case '<':
5105 redir_fd = redirect_opt_num(&dest);
5106 if (done_word(&dest, &ctx)) {
5107 goto parse_error;
5108 }
5109 redir_style = REDIRECT_INPUT;
5110 if (next == '<') {
5111 redir_style = REDIRECT_HEREDOC;
5112 heredoc_cnt++;
5113 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5114 ch = i_getch(input);
5115 nommu_addchr(&ctx.as_string, ch);
5116 } else if (next == '>') {
5117 redir_style = REDIRECT_IO;
5118 ch = i_getch(input);
5119 nommu_addchr(&ctx.as_string, ch);
5120 }
5121#if 0
5122 else if (next == '(') {
5123 syntax_error("<(process) not supported");
5124 goto parse_error;
5125 }
5126#endif
5127 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5128 goto parse_error;
5129 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005130 case '#':
5131 if (dest.length == 0 && !dest.has_quoted_part) {
5132 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005133 /* note: we do not add it to &ctx.as_string */
5134/* TODO: in bash:
5135 * comment inside $() goes to the next \n, even inside quoted string (!):
5136 * cmd "$(cmd2 #comment)" - syntax error
5137 * cmd "`cmd2 #comment`" - ok
5138 * We accept both (comment ends where command subst ends, in both cases).
5139 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005140 while (1) {
5141 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005142 if (ch == '\n') {
5143 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005144 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005145 }
5146 ch = i_getch(input);
5147 if (ch == EOF)
5148 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005149 }
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005150 continue; /* back to top of while (1) */
5151 }
5152 break;
5153 case '\\':
5154 if (next == '\n') {
5155 /* It's "\<newline>" */
5156#if !BB_MMU
5157 /* Remove trailing '\' from ctx.as_string */
5158 ctx.as_string.data[--ctx.as_string.length] = '\0';
5159#endif
5160 ch = i_getch(input); /* eat it */
5161 continue; /* back to top of while (1) */
5162 }
5163 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005164 }
5165
5166 if (dest.o_assignment == MAYBE_ASSIGNMENT
5167 /* check that we are not in word in "a=1 2>word b=1": */
5168 && !ctx.pending_redirect
5169 ) {
5170 /* ch is a special char and thus this word
5171 * cannot be an assignment */
5172 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005173 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005174 }
5175
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005176 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5177
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005178 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005179 case SPECIAL_VAR_SYMBOL:
5180 /* Convert raw ^C to corresponding special variable reference */
5181 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5182 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5183 /* fall through */
5184 case '#':
5185 /* non-comment #: "echo a#b" etc */
5186 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005187 break;
5188 case '\\':
5189 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005190 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005191 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005192 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005193 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005194 /* note: ch != '\n' (that case does not reach this place) */
5195 o_addchr(&dest, '\\');
5196 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5197 o_addchr(&dest, ch);
5198 nommu_addchr(&ctx.as_string, ch);
5199 /* Example: echo Hello \2>file
5200 * we need to know that word 2 is quoted */
5201 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005202 break;
5203 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005204 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005205 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005206 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005207 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005208 }
Eric Andersen25f27032001-04-26 23:22:31 +00005209 break;
5210 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005211 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005212 if (next == '\'' && !ctx.pending_redirect) {
5213 insert_empty_quoted_str_marker:
5214 nommu_addchr(&ctx.as_string, next);
5215 i_getch(input); /* eat second ' */
5216 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5217 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5218 } else {
5219 while (1) {
5220 ch = i_getch(input);
5221 if (ch == EOF) {
5222 syntax_error_unterm_ch('\'');
5223 goto parse_error;
5224 }
5225 nommu_addchr(&ctx.as_string, ch);
5226 if (ch == '\'')
5227 break;
5228 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005229 }
Eric Andersen25f27032001-04-26 23:22:31 +00005230 }
Eric Andersen25f27032001-04-26 23:22:31 +00005231 break;
5232 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005233 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005234 if (next == '"' && !ctx.pending_redirect)
5235 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005236 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005237 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005238 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005239 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005240 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00005241 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005242#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005243 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005244 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005245
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005246 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5247 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02005248 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005249 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5250 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005251# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005252 o_addstr(&ctx.as_string, dest.data + pos);
5253 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005254# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005255 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5256 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005257 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005258 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005259#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005260 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005261#if ENABLE_HUSH_CASE
5262 case_semi:
5263#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005264 if (done_word(&dest, &ctx)) {
5265 goto parse_error;
5266 }
5267 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005268#if ENABLE_HUSH_CASE
5269 /* Eat multiple semicolons, detect
5270 * whether it means something special */
5271 while (1) {
5272 ch = i_peek(input);
5273 if (ch != ';')
5274 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005275 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005276 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005277 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005278 ctx.ctx_dsemicolon = 1;
5279 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005280 break;
5281 }
5282 }
5283#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005284 new_cmd:
5285 /* We just finished a cmd. New one may start
5286 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005287 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005288 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00005289 break;
5290 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005291 if (done_word(&dest, &ctx)) {
5292 goto parse_error;
5293 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005294 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005295 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005296 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005297 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005298 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005299 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005300 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005301 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005302 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005303 if (done_word(&dest, &ctx)) {
5304 goto parse_error;
5305 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005306#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005307 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005308 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005309#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005310 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005311 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005312 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005313 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005314 } else {
5315 /* we could pick up a file descriptor choice here
5316 * with redirect_opt_num(), but bash doesn't do it.
5317 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005318 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005319 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005320 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005321 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005322#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005323 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005324 if (ctx.ctx_res_w == RES_MATCH
5325 && ctx.command->argv == NULL /* not (word|(... */
5326 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005327 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005328 ) {
5329 continue;
5330 }
5331#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005332 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005333 if (parse_group(&dest, &ctx, input, ch) != 0) {
5334 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005335 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005336 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005337 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005338#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005339 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005340 goto case_semi;
5341#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005342 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005343 /* proper use of this character is caught by end_trigger:
5344 * if we see {, we call parse_group(..., end_trigger='}')
5345 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005346 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005347 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005348 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005349 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005350 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005351 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005352 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005353 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005354
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005355 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005356 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005357 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005358 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005359 struct parse_context *pctx;
5360 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005361
5362 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005363 * Sample for finding leaks on syntax error recovery path.
5364 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005365 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005366 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005367 * while if (true | { true;}); then echo ok; fi; do break; done
5368 * 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 +00005369 */
5370 pctx = &ctx;
5371 do {
5372 /* Update pipe/command counts,
5373 * otherwise freeing may miss some */
5374 done_pipe(pctx, PIPE_SEQ);
5375 debug_printf_clean("freeing list %p from ctx %p\n",
5376 pctx->list_head, pctx);
5377 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005378 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005379 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005380#if !BB_MMU
5381 o_free_unsafe(&pctx->as_string);
5382#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005383 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005384 if (pctx != &ctx) {
5385 free(pctx);
5386 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005387 IF_HAS_KEYWORDS(pctx = p2;)
5388 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005389
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005390 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005391#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005392 if (pstring)
5393 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005394#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005395 debug_leave();
5396 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005397 }
Eric Andersen25f27032001-04-26 23:22:31 +00005398}
5399
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005400
5401/*** Execution routines ***/
5402
5403/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005404#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005405/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5406#define expand_string_to_string(str, do_unbackslash) \
5407 expand_string_to_string(str)
5408#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005409static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005410#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005411static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005412#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005413
5414/* expand_strvec_to_strvec() takes a list of strings, expands
5415 * all variable references within and returns a pointer to
5416 * a list of expanded strings, possibly with larger number
5417 * of strings. (Think VAR="a b"; echo $VAR).
5418 * This new list is allocated as a single malloc block.
5419 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005420 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005421 * Caller can deallocate entire list by single free(list). */
5422
Denys Vlasenko238081f2010-10-03 14:26:26 +02005423/* A horde of its helpers come first: */
5424
5425static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5426{
5427 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005428 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005429
Denys Vlasenko9e800222010-10-03 14:28:04 +02005430#if ENABLE_HUSH_BRACE_EXPANSION
5431 if (c == '{' || c == '}') {
5432 /* { -> \{, } -> \} */
5433 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005434 /* And now we want to add { or } and continue:
5435 * o_addchr(o, c);
5436 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005437 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005438 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005439 }
5440#endif
5441 o_addchr(o, c);
5442 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005443 /* \z -> \\\z; \<eol> -> \\<eol> */
5444 o_addchr(o, '\\');
5445 if (len) {
5446 len--;
5447 o_addchr(o, '\\');
5448 o_addchr(o, *str++);
5449 }
5450 }
5451 }
5452}
5453
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005454/* Store given string, finalizing the word and starting new one whenever
5455 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005456 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5457 * Return in *ended_with_ifs:
5458 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5459 */
5460static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005461{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005462 int last_is_ifs = 0;
5463
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005464 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005465 int word_len;
5466
5467 if (!*str) /* EOL - do not finalize word */
5468 break;
5469 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005470 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005471 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005472 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005473 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005474 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005475 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005476 * Example: "v='\*'; echo b$v" prints "b\*"
5477 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005478 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005479 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005480 /*/ Why can't we do it easier? */
5481 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5482 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5483 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005484 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005485 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005486 if (!*str) /* EOL - do not finalize word */
5487 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005488 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005489
5490 /* We know str here points to at least one IFS char */
5491 last_is_ifs = 1;
5492 str += strspn(str, G.ifs); /* skip IFS chars */
5493 if (!*str) /* EOL - do not finalize word */
5494 break;
5495
5496 /* Start new word... but not always! */
5497 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005498 if (output->has_quoted_part
5499 /* Case "v=' a'; echo $v":
5500 * here nothing precedes the space in $v expansion,
5501 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005502 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005503 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005504 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005505 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005506 o_addchr(output, '\0');
5507 debug_print_list("expand_on_ifs", output, n);
5508 n = o_save_ptr(output, n);
5509 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005510 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005511
5512 if (ended_with_ifs)
5513 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005514 debug_print_list("expand_on_ifs[1]", output, n);
5515 return n;
5516}
5517
5518/* Helper to expand $((...)) and heredoc body. These act as if
5519 * they are in double quotes, with the exception that they are not :).
5520 * Just the rules are similar: "expand only $var and `cmd`"
5521 *
5522 * Returns malloced string.
5523 * As an optimization, we return NULL if expansion is not needed.
5524 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005525#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005526/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5527#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5528 encode_then_expand_string(str)
5529#endif
5530static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005531{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005532#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005533 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005534#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005535 char *exp_str;
5536 struct in_str input;
5537 o_string dest = NULL_O_STRING;
5538
5539 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005540 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005541#if ENABLE_HUSH_TICK
5542 && !strchr(str, '`')
5543#endif
5544 ) {
5545 return NULL;
5546 }
5547
5548 /* We need to expand. Example:
5549 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5550 */
5551 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005552 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005553//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005554 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005555 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005556 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5557 o_free_unsafe(&dest);
5558 return exp_str;
5559}
5560
Denys Vlasenko0b883582016-12-23 16:49:07 +01005561#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005562static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005563{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005564 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005565 arith_t res;
5566 char *exp_str;
5567
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005568 math_state.lookupvar = get_local_var_value;
5569 math_state.setvar = set_local_var_from_halves;
5570 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005571 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005572 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005573 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005574 if (errmsg_p)
5575 *errmsg_p = math_state.errmsg;
5576 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005577 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005578 return res;
5579}
5580#endif
5581
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005582#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005583/* ${var/[/]pattern[/repl]} helpers */
5584static char *strstr_pattern(char *val, const char *pattern, int *size)
5585{
5586 while (1) {
5587 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5588 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5589 if (end) {
5590 *size = end - val;
5591 return val;
5592 }
5593 if (*val == '\0')
5594 return NULL;
5595 /* Optimization: if "*pat" did not match the start of "string",
5596 * we know that "tring", "ring" etc will not match too:
5597 */
5598 if (pattern[0] == '*')
5599 return NULL;
5600 val++;
5601 }
5602}
5603static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5604{
5605 char *result = NULL;
5606 unsigned res_len = 0;
5607 unsigned repl_len = strlen(repl);
5608
5609 while (1) {
5610 int size;
5611 char *s = strstr_pattern(val, pattern, &size);
5612 if (!s)
5613 break;
5614
5615 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005616 strcpy(mempcpy(result + res_len, val, s - val), repl);
5617 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005618 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5619
5620 val = s + size;
5621 if (exp_op == '/')
5622 break;
5623 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005624 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005625 result = xrealloc(result, res_len + strlen(val) + 1);
5626 strcpy(result + res_len, val);
5627 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5628 }
5629 debug_printf_varexp("result:'%s'\n", result);
5630 return result;
5631}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005632#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005633
5634/* Helper:
5635 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5636 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005637static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005638{
5639 const char *val = NULL;
5640 char *to_be_freed = NULL;
5641 char *p = *pp;
5642 char *var;
5643 char first_char;
5644 char exp_op;
5645 char exp_save = exp_save; /* for compiler */
5646 char *exp_saveptr; /* points to expansion operator */
5647 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005648 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005649
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005650 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005651 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005652 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005653 arg0 = arg[0];
5654 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005655 exp_op = 0;
5656
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005657 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5658 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5659 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5660 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005661 ) {
5662 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005663 var++;
5664 exp_op = 'L';
5665 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005666 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005667 if (exp_saveptr /* if 2nd char is one of expansion operators */
5668 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5669 ) {
5670 /* ${?:0}, ${#[:]%0} etc */
5671 exp_saveptr = var + 1;
5672 } else {
5673 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5674 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5675 }
5676 exp_op = exp_save = *exp_saveptr;
5677 if (exp_op) {
5678 exp_word = exp_saveptr + 1;
5679 if (exp_op == ':') {
5680 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005681//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005682 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005683 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005684 ) {
5685 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5686 exp_op = ':';
5687 exp_word--;
5688 }
5689 }
5690 *exp_saveptr = '\0';
5691 } /* else: it's not an expansion op, but bare ${var} */
5692 }
5693
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005694 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005695 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005696 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005697 int n = xatoi_positive(var);
5698 if (n < G.global_argc)
5699 val = G.global_argv[n];
5700 /* else val remains NULL: $N with too big N */
5701 } else {
5702 switch (var[0]) {
5703 case '$': /* pid */
5704 val = utoa(G.root_pid);
5705 break;
5706 case '!': /* bg pid */
5707 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5708 break;
5709 case '?': /* exitcode */
5710 val = utoa(G.last_exitcode);
5711 break;
5712 case '#': /* argc */
5713 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5714 break;
5715 default:
5716 val = get_local_var_value(var);
5717 }
5718 }
5719
5720 /* Handle any expansions */
5721 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005722 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005723 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005724 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005725 debug_printf_expand("%s\n", val);
5726 } else if (exp_op) {
5727 if (exp_op == '%' || exp_op == '#') {
5728 /* Standard-mandated substring removal ops:
5729 * ${parameter%word} - remove smallest suffix pattern
5730 * ${parameter%%word} - remove largest suffix pattern
5731 * ${parameter#word} - remove smallest prefix pattern
5732 * ${parameter##word} - remove largest prefix pattern
5733 *
5734 * Word is expanded to produce a glob pattern.
5735 * Then var's value is matched to it and matching part removed.
5736 */
5737 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005738 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005739 char *exp_exp_word;
5740 char *loc;
5741 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005742 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005743 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005744 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005745 if (exp_exp_word)
5746 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005747 /* HACK ALERT. We depend here on the fact that
5748 * G.global_argv and results of utoa and get_local_var_value
5749 * are actually in writable memory:
5750 * scan_and_match momentarily stores NULs there. */
5751 t = (char*)val;
5752 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005753 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005754 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005755 free(exp_exp_word);
5756 if (loc) { /* match was found */
5757 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005758 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005759 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005760 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005761 }
5762 }
5763 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005764#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005765 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005766 /* It's ${var/[/]pattern[/repl]} thing.
5767 * Note that in encoded form it has TWO parts:
5768 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005769 * and if // is used, it is encoded as \:
5770 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005771 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005772 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005773 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005774 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005775 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005776 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005777 * by the usual expansion rules:
5778 * >az; >bz;
5779 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5780 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5781 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5782 * v='a bz'; echo ${v/a*z/\z} prints "z"
5783 * (note that a*z _pattern_ is never globbed!)
5784 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005785 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005786 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005787 if (!pattern)
5788 pattern = xstrdup(exp_word);
5789 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5790 *p++ = SPECIAL_VAR_SYMBOL;
5791 exp_word = p;
5792 p = strchr(p, SPECIAL_VAR_SYMBOL);
5793 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005794 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005795 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5796 /* HACK ALERT. We depend here on the fact that
5797 * G.global_argv and results of utoa and get_local_var_value
5798 * are actually in writable memory:
5799 * replace_pattern momentarily stores NULs there. */
5800 t = (char*)val;
5801 to_be_freed = replace_pattern(t,
5802 pattern,
5803 (repl ? repl : exp_word),
5804 exp_op);
5805 if (to_be_freed) /* at least one replace happened */
5806 val = to_be_freed;
5807 free(pattern);
5808 free(repl);
5809 }
5810 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005811#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005812 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005813#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005814 /* It's ${var:N[:M]} bashism.
5815 * Note that in encoded form it has TWO parts:
5816 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5817 */
5818 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005819 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005820
Denys Vlasenko063847d2010-09-15 13:33:02 +02005821 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5822 if (errmsg)
5823 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005824 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5825 *p++ = SPECIAL_VAR_SYMBOL;
5826 exp_word = p;
5827 p = strchr(p, SPECIAL_VAR_SYMBOL);
5828 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005829 len = expand_and_evaluate_arith(exp_word, &errmsg);
5830 if (errmsg)
5831 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005832 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005833 if (beg < 0) {
5834 /* negative beg counts from the end */
5835 beg = (arith_t)strlen(val) + beg;
5836 if (beg < 0) /* ${v: -999999} is "" */
5837 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005838 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005839 debug_printf_varexp("from val:'%s'\n", val);
5840 if (len < 0) {
5841 /* in bash, len=-n means strlen()-n */
5842 len = (arith_t)strlen(val) - beg + len;
5843 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02005844 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005845 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02005846 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005847 arith_err:
5848 val = NULL;
5849 } else {
5850 /* Paranoia. What if user entered 9999999999999
5851 * which fits in arith_t but not int? */
5852 if (len >= INT_MAX)
5853 len = INT_MAX;
5854 val = to_be_freed = xstrndup(val + beg, len);
5855 }
5856 debug_printf_varexp("val:'%s'\n", val);
5857#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02005858 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005859 val = NULL;
5860#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005861 } else { /* one of "-=+?" */
5862 /* Standard-mandated substitution ops:
5863 * ${var?word} - indicate error if unset
5864 * If var is unset, word (or a message indicating it is unset
5865 * if word is null) is written to standard error
5866 * and the shell exits with a non-zero exit status.
5867 * Otherwise, the value of var is substituted.
5868 * ${var-word} - use default value
5869 * If var is unset, word is substituted.
5870 * ${var=word} - assign and use default value
5871 * If var is unset, word is assigned to var.
5872 * In all cases, final value of var is substituted.
5873 * ${var+word} - use alternative value
5874 * If var is unset, null is substituted.
5875 * Otherwise, word is substituted.
5876 *
5877 * Word is subjected to tilde expansion, parameter expansion,
5878 * command substitution, and arithmetic expansion.
5879 * If word is not needed, it is not expanded.
5880 *
5881 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5882 * but also treat null var as if it is unset.
5883 */
5884 int use_word = (!val || ((exp_save == ':') && !val[0]));
5885 if (exp_op == '+')
5886 use_word = !use_word;
5887 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5888 (exp_save == ':') ? "true" : "false", use_word);
5889 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005890 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005891 if (to_be_freed)
5892 exp_word = to_be_freed;
5893 if (exp_op == '?') {
5894 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02005895 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005896 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02005897 exp_word[0]
5898 ? exp_word
5899 : "parameter null or not set"
5900 /* ash has more specific messages, a-la: */
5901 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005902 );
5903//TODO: how interactive bash aborts expansion mid-command?
5904 } else {
5905 val = exp_word;
5906 }
5907
5908 if (exp_op == '=') {
5909 /* ${var=[word]} or ${var:=[word]} */
5910 if (isdigit(var[0]) || var[0] == '#') {
5911 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02005912 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005913 val = NULL;
5914 } else {
5915 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02005916 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005917 }
5918 }
5919 }
5920 } /* one of "-=+?" */
5921
5922 *exp_saveptr = exp_save;
5923 } /* if (exp_op) */
5924
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005925 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005926
5927 *pp = p;
5928 *to_be_freed_pp = to_be_freed;
5929 return val;
5930}
5931
5932/* Expand all variable references in given string, adding words to list[]
5933 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5934 * to be filled). This routine is extremely tricky: has to deal with
5935 * variables/parameters with whitespace, $* and $@, and constructs like
5936 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005937static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005938{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005939 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005940 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005941 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005942 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005943 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005944 char *p;
5945
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005946 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5947 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005948 debug_print_list("expand_vars_to_list", output, n);
5949 n = o_save_ptr(output, n);
5950 debug_print_list("expand_vars_to_list[0]", output, n);
5951
5952 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5953 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005954 char *to_be_freed = NULL;
5955 const char *val = NULL;
5956#if ENABLE_HUSH_TICK
5957 o_string subst_result = NULL_O_STRING;
5958#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01005959#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005960 char arith_buf[sizeof(arith_t)*3 + 2];
5961#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005962
5963 if (ended_in_ifs) {
5964 o_addchr(output, '\0');
5965 n = o_save_ptr(output, n);
5966 ended_in_ifs = 0;
5967 }
5968
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005969 o_addblock(output, arg, p - arg);
5970 debug_print_list("expand_vars_to_list[1]", output, n);
5971 arg = ++p;
5972 p = strchr(p, SPECIAL_VAR_SYMBOL);
5973
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005974 /* Fetch special var name (if it is indeed one of them)
5975 * and quote bit, force the bit on if singleword expansion -
5976 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005977 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005978
5979 /* Is this variable quoted and thus expansion can't be null?
5980 * "$@" is special. Even if quoted, it can still
5981 * expand to nothing (not even an empty string),
5982 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005983 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005984 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005985
5986 switch (first_ch & 0x7f) {
5987 /* Highest bit in first_ch indicates that var is double-quoted */
5988 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005989 case '@': {
5990 int i;
5991 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005992 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005993 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005994 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005995 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005996 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005997 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005998 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5999 if (G.global_argv[i++][0] && G.global_argv[i]) {
6000 /* this argv[] is not empty and not last:
6001 * put terminating NUL, start new word */
6002 o_addchr(output, '\0');
6003 debug_print_list("expand_vars_to_list[2]", output, n);
6004 n = o_save_ptr(output, n);
6005 debug_print_list("expand_vars_to_list[3]", output, n);
6006 }
6007 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006008 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006009 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006010 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006011 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006012 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006013 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006014 while (1) {
6015 o_addQstr(output, G.global_argv[i]);
6016 if (++i >= G.global_argc)
6017 break;
6018 o_addchr(output, '\0');
6019 debug_print_list("expand_vars_to_list[4]", output, n);
6020 n = o_save_ptr(output, n);
6021 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006022 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006023 while (1) {
6024 o_addQstr(output, G.global_argv[i]);
6025 if (!G.global_argv[++i])
6026 break;
6027 if (G.ifs[0])
6028 o_addchr(output, G.ifs[0]);
6029 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006030 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006031 }
6032 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006033 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006034 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6035 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006036 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006037 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006038 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006039 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006040 case SPECIAL_VAR_QUOTED_SVS:
6041 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6042 arg++;
6043 val = SPECIAL_VAR_SYMBOL_STR;
6044 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006045#if ENABLE_HUSH_TICK
6046 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006047 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006048 arg++;
6049 /* Can't just stuff it into output o_string,
6050 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006051 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006052 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6053 G.last_exitcode = process_command_subs(&subst_result, arg);
6054 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6055 val = subst_result.data;
6056 goto store_val;
6057#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006058#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006059 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6060 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006061
6062 arg++; /* skip '+' */
6063 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6064 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006065 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006066 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6067 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006068 val = arith_buf;
6069 break;
6070 }
6071#endif
6072 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006073 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006074 IF_HUSH_TICK(store_val:)
6075 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006076 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6077 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006078 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006079 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006080 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006081 }
6082 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006083 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006084 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6085 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006086 }
6087 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006088 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6089
6090 if (val && val[0]) {
6091 o_addQstr(output, val);
6092 }
6093 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006094
6095 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6096 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006097 if (*p != SPECIAL_VAR_SYMBOL)
6098 *p = SPECIAL_VAR_SYMBOL;
6099
6100#if ENABLE_HUSH_TICK
6101 o_free(&subst_result);
6102#endif
6103 arg = ++p;
6104 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6105
6106 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006107 if (ended_in_ifs) {
6108 o_addchr(output, '\0');
6109 n = o_save_ptr(output, n);
6110 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006111 debug_print_list("expand_vars_to_list[a]", output, n);
6112 /* this part is literal, and it was already pre-quoted
6113 * if needed (much earlier), do not use o_addQstr here! */
6114 o_addstr_with_NUL(output, arg);
6115 debug_print_list("expand_vars_to_list[b]", output, n);
6116 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006117 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006118 ) {
6119 n--;
6120 /* allow to reuse list[n] later without re-growth */
6121 output->has_empty_slot = 1;
6122 } else {
6123 o_addchr(output, '\0');
6124 }
6125
6126 return n;
6127}
6128
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006129static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006130{
6131 int n;
6132 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006133 o_string output = NULL_O_STRING;
6134
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006135 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006136
6137 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006138 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006139 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006140 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006141 }
6142 debug_print_list("expand_variables", &output, n);
6143
6144 /* output.data (malloced in one block) gets returned in "list" */
6145 list = o_finalize_list(&output, n);
6146 debug_print_strings("expand_variables[1]", list);
6147 return list;
6148}
6149
6150static char **expand_strvec_to_strvec(char **argv)
6151{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006152 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006153}
6154
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006155#if BASH_TEST2
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006156static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6157{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006158 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006159}
6160#endif
6161
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006162/* Used for expansion of right hand of assignments,
6163 * $((...)), heredocs, variable espansion parts.
6164 *
6165 * NB: should NOT do globbing!
6166 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6167 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006168static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006169{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006170#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006171 const int do_unbackslash = 1;
6172#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006173 char *argv[2], **list;
6174
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006175 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006176 /* This is generally an optimization, but it also
6177 * handles "", which otherwise trips over !list[0] check below.
6178 * (is this ever happens that we actually get str="" here?)
6179 */
6180 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6181 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006182 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006183 return xstrdup(str);
6184 }
6185
6186 argv[0] = (char*)str;
6187 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006188 list = expand_variables(argv, do_unbackslash
6189 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6190 : EXP_FLAG_SINGLEWORD
6191 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006192 if (HUSH_DEBUG)
6193 if (!list[0] || list[1])
6194 bb_error_msg_and_die("BUG in varexp2");
6195 /* actually, just move string 2*sizeof(char*) bytes back */
6196 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006197 if (do_unbackslash)
6198 unbackslash((char*)list);
6199 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006200 return (char*)list;
6201}
6202
Denys Vlasenko1f191122018-01-11 13:17:30 +01006203#if ENABLE_HUSH_CASE
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006204static char* expand_strvec_to_string(char **argv)
6205{
6206 char **list;
6207
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006208 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006209 /* Convert all NULs to spaces */
6210 if (list[0]) {
6211 int n = 1;
6212 while (list[n]) {
6213 if (HUSH_DEBUG)
6214 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6215 bb_error_msg_and_die("BUG in varexp3");
6216 /* bash uses ' ' regardless of $IFS contents */
6217 list[n][-1] = ' ';
6218 n++;
6219 }
6220 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006221 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006222 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6223 return (char*)list;
6224}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006225#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006226
6227static char **expand_assignments(char **argv, int count)
6228{
6229 int i;
6230 char **p;
6231
6232 G.expanded_assignments = p = NULL;
6233 /* Expand assignments into one string each */
6234 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006235 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006236 }
6237 G.expanded_assignments = NULL;
6238 return p;
6239}
6240
6241
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006242static void switch_off_special_sigs(unsigned mask)
6243{
6244 unsigned sig = 0;
6245 while ((mask >>= 1) != 0) {
6246 sig++;
6247 if (!(mask & 1))
6248 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006249#if ENABLE_HUSH_TRAP
6250 if (G_traps) {
6251 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006252 /* trap is '', has to remain SIG_IGN */
6253 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006254 free(G_traps[sig]);
6255 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006256 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006257#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006258 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006259 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006260 }
6261}
6262
Denys Vlasenkob347df92011-08-09 22:49:15 +02006263#if BB_MMU
6264/* never called */
6265void re_execute_shell(char ***to_free, const char *s,
6266 char *g_argv0, char **g_argv,
6267 char **builtin_argv) NORETURN;
6268
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006269static void reset_traps_to_defaults(void)
6270{
6271 /* This function is always called in a child shell
6272 * after fork (not vfork, NOMMU doesn't use this function).
6273 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006274 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006275 unsigned mask;
6276
6277 /* Child shells are not interactive.
6278 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6279 * Testcase: (while :; do :; done) + ^Z should background.
6280 * Same goes for SIGTERM, SIGHUP, SIGINT.
6281 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006282 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006283 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006284 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006285
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006286 /* Switch off special sigs */
6287 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006288# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006289 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006290# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006291 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006292 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6293 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006294
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006295# if ENABLE_HUSH_TRAP
6296 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006297 return;
6298
6299 /* Reset all sigs to default except ones with empty traps */
6300 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006301 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006302 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006303 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006304 continue; /* empty trap: has to remain SIG_IGN */
6305 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006306 free(G_traps[sig]);
6307 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006308 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006309 if (sig == 0)
6310 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006311 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006312 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006313# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006314}
6315
6316#else /* !BB_MMU */
6317
6318static void re_execute_shell(char ***to_free, const char *s,
6319 char *g_argv0, char **g_argv,
6320 char **builtin_argv) NORETURN;
6321static void re_execute_shell(char ***to_free, const char *s,
6322 char *g_argv0, char **g_argv,
6323 char **builtin_argv)
6324{
6325# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6326 /* delims + 2 * (number of bytes in printed hex numbers) */
6327 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6328 char *heredoc_argv[4];
6329 struct variable *cur;
6330# if ENABLE_HUSH_FUNCTIONS
6331 struct function *funcp;
6332# endif
6333 char **argv, **pp;
6334 unsigned cnt;
6335 unsigned long long empty_trap_mask;
6336
6337 if (!g_argv0) { /* heredoc */
6338 argv = heredoc_argv;
6339 argv[0] = (char *) G.argv0_for_re_execing;
6340 argv[1] = (char *) "-<";
6341 argv[2] = (char *) s;
6342 argv[3] = NULL;
6343 pp = &argv[3]; /* used as pointer to empty environment */
6344 goto do_exec;
6345 }
6346
6347 cnt = 0;
6348 pp = builtin_argv;
6349 if (pp) while (*pp++)
6350 cnt++;
6351
6352 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006353 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006354 int sig;
6355 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006356 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006357 empty_trap_mask |= 1LL << sig;
6358 }
6359 }
6360
6361 sprintf(param_buf, NOMMU_HACK_FMT
6362 , (unsigned) G.root_pid
6363 , (unsigned) G.root_ppid
6364 , (unsigned) G.last_bg_pid
6365 , (unsigned) G.last_exitcode
6366 , cnt
6367 , empty_trap_mask
6368 IF_HUSH_LOOPS(, G.depth_of_loop)
6369 );
6370# undef NOMMU_HACK_FMT
6371 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6372 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6373 */
6374 cnt += 6;
6375 for (cur = G.top_var; cur; cur = cur->next) {
6376 if (!cur->flg_export || cur->flg_read_only)
6377 cnt += 2;
6378 }
6379# if ENABLE_HUSH_FUNCTIONS
6380 for (funcp = G.top_func; funcp; funcp = funcp->next)
6381 cnt += 3;
6382# endif
6383 pp = g_argv;
6384 while (*pp++)
6385 cnt++;
6386 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6387 *pp++ = (char *) G.argv0_for_re_execing;
6388 *pp++ = param_buf;
6389 for (cur = G.top_var; cur; cur = cur->next) {
6390 if (strcmp(cur->varstr, hush_version_str) == 0)
6391 continue;
6392 if (cur->flg_read_only) {
6393 *pp++ = (char *) "-R";
6394 *pp++ = cur->varstr;
6395 } else if (!cur->flg_export) {
6396 *pp++ = (char *) "-V";
6397 *pp++ = cur->varstr;
6398 }
6399 }
6400# if ENABLE_HUSH_FUNCTIONS
6401 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6402 *pp++ = (char *) "-F";
6403 *pp++ = funcp->name;
6404 *pp++ = funcp->body_as_string;
6405 }
6406# endif
6407 /* We can pass activated traps here. Say, -Tnn:trap_string
6408 *
6409 * However, POSIX says that subshells reset signals with traps
6410 * to SIG_DFL.
6411 * I tested bash-3.2 and it not only does that with true subshells
6412 * of the form ( list ), but with any forked children shells.
6413 * I set trap "echo W" WINCH; and then tried:
6414 *
6415 * { echo 1; sleep 20; echo 2; } &
6416 * while true; do echo 1; sleep 20; echo 2; break; done &
6417 * true | { echo 1; sleep 20; echo 2; } | cat
6418 *
6419 * In all these cases sending SIGWINCH to the child shell
6420 * did not run the trap. If I add trap "echo V" WINCH;
6421 * _inside_ group (just before echo 1), it works.
6422 *
6423 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006424 */
6425 *pp++ = (char *) "-c";
6426 *pp++ = (char *) s;
6427 if (builtin_argv) {
6428 while (*++builtin_argv)
6429 *pp++ = *builtin_argv;
6430 *pp++ = (char *) "";
6431 }
6432 *pp++ = g_argv0;
6433 while (*g_argv)
6434 *pp++ = *g_argv++;
6435 /* *pp = NULL; - is already there */
6436 pp = environ;
6437
6438 do_exec:
6439 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006440 /* Don't propagate SIG_IGN to the child */
6441 if (SPECIAL_JOBSTOP_SIGS != 0)
6442 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006443 execve(bb_busybox_exec_path, argv, pp);
6444 /* Fallback. Useful for init=/bin/hush usage etc */
6445 if (argv[0][0] == '/')
6446 execve(argv[0], argv, pp);
6447 xfunc_error_retval = 127;
6448 bb_error_msg_and_die("can't re-execute the shell");
6449}
6450#endif /* !BB_MMU */
6451
6452
6453static int run_and_free_list(struct pipe *pi);
6454
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006455/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006456 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6457 * end_trigger controls how often we stop parsing
6458 * NUL: parse all, execute, return
6459 * ';': parse till ';' or newline, execute, repeat till EOF
6460 */
6461static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006462{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006463 /* Why we need empty flag?
6464 * An obscure corner case "false; ``; echo $?":
6465 * empty command in `` should still set $? to 0.
6466 * But we can't just set $? to 0 at the start,
6467 * this breaks "false; echo `echo $?`" case.
6468 */
6469 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006470 while (1) {
6471 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006472
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006473#if ENABLE_HUSH_INTERACTIVE
6474 if (end_trigger == ';')
6475 inp->promptmode = 0; /* PS1 */
6476#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006477 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006478 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6479 /* If we are in "big" script
6480 * (not in `cmd` or something similar)...
6481 */
6482 if (pipe_list == ERR_PTR && end_trigger == ';') {
6483 /* Discard cached input (rest of line) */
6484 int ch = inp->last_char;
6485 while (ch != EOF && ch != '\n') {
6486 //bb_error_msg("Discarded:'%c'", ch);
6487 ch = i_getch(inp);
6488 }
6489 /* Force prompt */
6490 inp->p = NULL;
6491 /* This stream isn't empty */
6492 empty = 0;
6493 continue;
6494 }
6495 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006496 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006497 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006498 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006499 debug_print_tree(pipe_list, 0);
6500 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6501 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006502 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006503 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006504 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006505 }
Eric Andersen25f27032001-04-26 23:22:31 +00006506}
6507
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006508static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006509{
6510 struct in_str input;
6511 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006512 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006513}
6514
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006515static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006516{
Eric Andersen25f27032001-04-26 23:22:31 +00006517 struct in_str input;
6518 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006519 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006520}
6521
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006522#if ENABLE_HUSH_TICK
6523static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6524{
6525 pid_t pid;
6526 int channel[2];
6527# if !BB_MMU
6528 char **to_free = NULL;
6529# endif
6530
6531 xpipe(channel);
6532 pid = BB_MMU ? xfork() : xvfork();
6533 if (pid == 0) { /* child */
6534 disable_restore_tty_pgrp_on_exit();
6535 /* Process substitution is not considered to be usual
6536 * 'command execution'.
6537 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6538 */
6539 bb_signals(0
6540 + (1 << SIGTSTP)
6541 + (1 << SIGTTIN)
6542 + (1 << SIGTTOU)
6543 , SIG_IGN);
6544 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6545 close(channel[0]); /* NB: close _first_, then move fd! */
6546 xmove_fd(channel[1], 1);
6547 /* Prevent it from trying to handle ctrl-z etc */
6548 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006549# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006550 /* Awful hack for `trap` or $(trap).
6551 *
6552 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6553 * contains an example where "trap" is executed in a subshell:
6554 *
6555 * save_traps=$(trap)
6556 * ...
6557 * eval "$save_traps"
6558 *
6559 * Standard does not say that "trap" in subshell shall print
6560 * parent shell's traps. It only says that its output
6561 * must have suitable form, but then, in the above example
6562 * (which is not supposed to be normative), it implies that.
6563 *
6564 * bash (and probably other shell) does implement it
6565 * (traps are reset to defaults, but "trap" still shows them),
6566 * but as a result, "trap" logic is hopelessly messed up:
6567 *
6568 * # trap
6569 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6570 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6571 * # true | trap <--- trap is in subshell - no output (ditto)
6572 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6573 * trap -- 'echo Ho' SIGWINCH
6574 * # echo `(trap)` <--- in subshell in subshell - output
6575 * trap -- 'echo Ho' SIGWINCH
6576 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6577 * trap -- 'echo Ho' SIGWINCH
6578 *
6579 * The rules when to forget and when to not forget traps
6580 * get really complex and nonsensical.
6581 *
6582 * Our solution: ONLY bare $(trap) or `trap` is special.
6583 */
6584 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006585 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006586 && skip_whitespace(s + 4)[0] == '\0'
6587 ) {
6588 static const char *const argv[] = { NULL, NULL };
6589 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006590 fflush_all(); /* important */
6591 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006592 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006593# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006594# if BB_MMU
6595 reset_traps_to_defaults();
6596 parse_and_run_string(s);
6597 _exit(G.last_exitcode);
6598# else
6599 /* We re-execute after vfork on NOMMU. This makes this script safe:
6600 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6601 * huge=`cat BIG` # was blocking here forever
6602 * echo OK
6603 */
6604 re_execute_shell(&to_free,
6605 s,
6606 G.global_argv[0],
6607 G.global_argv + 1,
6608 NULL);
6609# endif
6610 }
6611
6612 /* parent */
6613 *pid_p = pid;
6614# if ENABLE_HUSH_FAST
6615 G.count_SIGCHLD++;
6616//bb_error_msg("[%d] fork in generate_stream_from_string:"
6617// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6618// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6619# endif
6620 enable_restore_tty_pgrp_on_exit();
6621# if !BB_MMU
6622 free(to_free);
6623# endif
6624 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006625 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006626}
6627
6628/* Return code is exit status of the process that is run. */
6629static int process_command_subs(o_string *dest, const char *s)
6630{
6631 FILE *fp;
6632 struct in_str pipe_str;
6633 pid_t pid;
6634 int status, ch, eol_cnt;
6635
6636 fp = generate_stream_from_string(s, &pid);
6637
6638 /* Now send results of command back into original context */
6639 setup_file_in_str(&pipe_str, fp);
6640 eol_cnt = 0;
6641 while ((ch = i_getch(&pipe_str)) != EOF) {
6642 if (ch == '\n') {
6643 eol_cnt++;
6644 continue;
6645 }
6646 while (eol_cnt) {
6647 o_addchr(dest, '\n');
6648 eol_cnt--;
6649 }
6650 o_addQchr(dest, ch);
6651 }
6652
6653 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006654 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006655 /* We need to extract exitcode. Test case
6656 * "true; echo `sleep 1; false` $?"
6657 * should print 1 */
6658 safe_waitpid(pid, &status, 0);
6659 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6660 return WEXITSTATUS(status);
6661}
6662#endif /* ENABLE_HUSH_TICK */
6663
6664
6665static void setup_heredoc(struct redir_struct *redir)
6666{
6667 struct fd_pair pair;
6668 pid_t pid;
6669 int len, written;
6670 /* the _body_ of heredoc (misleading field name) */
6671 const char *heredoc = redir->rd_filename;
6672 char *expanded;
6673#if !BB_MMU
6674 char **to_free;
6675#endif
6676
6677 expanded = NULL;
6678 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006679 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006680 if (expanded)
6681 heredoc = expanded;
6682 }
6683 len = strlen(heredoc);
6684
6685 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6686 xpiped_pair(pair);
6687 xmove_fd(pair.rd, redir->rd_fd);
6688
6689 /* Try writing without forking. Newer kernels have
6690 * dynamically growing pipes. Must use non-blocking write! */
6691 ndelay_on(pair.wr);
6692 while (1) {
6693 written = write(pair.wr, heredoc, len);
6694 if (written <= 0)
6695 break;
6696 len -= written;
6697 if (len == 0) {
6698 close(pair.wr);
6699 free(expanded);
6700 return;
6701 }
6702 heredoc += written;
6703 }
6704 ndelay_off(pair.wr);
6705
6706 /* Okay, pipe buffer was not big enough */
6707 /* Note: we must not create a stray child (bastard? :)
6708 * for the unsuspecting parent process. Child creates a grandchild
6709 * and exits before parent execs the process which consumes heredoc
6710 * (that exec happens after we return from this function) */
6711#if !BB_MMU
6712 to_free = NULL;
6713#endif
6714 pid = xvfork();
6715 if (pid == 0) {
6716 /* child */
6717 disable_restore_tty_pgrp_on_exit();
6718 pid = BB_MMU ? xfork() : xvfork();
6719 if (pid != 0)
6720 _exit(0);
6721 /* grandchild */
6722 close(redir->rd_fd); /* read side of the pipe */
6723#if BB_MMU
6724 full_write(pair.wr, heredoc, len); /* may loop or block */
6725 _exit(0);
6726#else
6727 /* Delegate blocking writes to another process */
6728 xmove_fd(pair.wr, STDOUT_FILENO);
6729 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6730#endif
6731 }
6732 /* parent */
6733#if ENABLE_HUSH_FAST
6734 G.count_SIGCHLD++;
6735//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6736#endif
6737 enable_restore_tty_pgrp_on_exit();
6738#if !BB_MMU
6739 free(to_free);
6740#endif
6741 close(pair.wr);
6742 free(expanded);
6743 wait(NULL); /* wait till child has died */
6744}
6745
Denys Vlasenko2db74612017-07-07 22:07:28 +02006746struct squirrel {
6747 int orig_fd;
6748 int moved_to;
6749 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6750 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6751};
6752
Denys Vlasenko621fc502017-07-24 12:42:17 +02006753static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6754{
6755 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6756 sq[i].orig_fd = orig;
6757 sq[i].moved_to = moved;
6758 sq[i+1].orig_fd = -1; /* end marker */
6759 return sq;
6760}
6761
Denys Vlasenko2db74612017-07-07 22:07:28 +02006762static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6763{
Denys Vlasenko621fc502017-07-24 12:42:17 +02006764 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006765 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02006766
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006767 i = 0;
6768 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006769 /* If we collide with an already moved fd... */
6770 if (fd == sq[i].moved_to) {
6771 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6772 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6773 if (sq[i].moved_to < 0) /* what? */
6774 xfunc_die();
6775 return sq;
6776 }
6777 if (fd == sq[i].orig_fd) {
6778 /* Example: echo Hello >/dev/null 1>&2 */
6779 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6780 return sq;
6781 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006782 }
6783
Denys Vlasenko2db74612017-07-07 22:07:28 +02006784 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko621fc502017-07-24 12:42:17 +02006785 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6786 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6787 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02006788 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02006789 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006790}
6791
Denys Vlasenko657e9002017-07-30 23:34:04 +02006792static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6793{
6794 int i;
6795
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006796 i = 0;
6797 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006798 /* If we collide with an already moved fd... */
6799 if (fd == sq[i].orig_fd) {
6800 /* Examples:
6801 * "echo 3>FILE 3>&- 3>FILE"
6802 * "echo 3>&- 3>FILE"
6803 * No need for last redirect to insert
6804 * another "need to close 3" indicator.
6805 */
6806 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6807 return sq;
6808 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006809 }
6810
6811 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6812 return append_squirrel(sq, i, fd, -1);
6813}
6814
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006815/* fd: redirect wants this fd to be used (e.g. 3>file).
6816 * Move all conflicting internally used fds,
6817 * and remember them so that we can restore them later.
6818 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006819static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006820{
Denys Vlasenko2db74612017-07-07 22:07:28 +02006821 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6822 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006823
6824#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006825 if (fd == G.interactive_fd) {
6826 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006827 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006828 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6829 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006830 }
6831#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006832 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6833 * (1) Redirect in a forked child. No need to save FILEs' fds,
6834 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02006835 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6836 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006837 * "fileno(fd) = new_fd" can't be done.
6838 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02006839 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006840 return 0;
6841
Denys Vlasenko2db74612017-07-07 22:07:28 +02006842 /* If this one of script's fds? */
6843 if (save_FILEs_on_redirect(fd, avoid_fd))
6844 return 1; /* yes. "we closed fd" */
6845
6846 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6847 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6848 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006849}
6850
Denys Vlasenko2db74612017-07-07 22:07:28 +02006851static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006852{
Denys Vlasenko2db74612017-07-07 22:07:28 +02006853 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006854 int i;
6855 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006856 if (sq[i].moved_to >= 0) {
6857 /* We simply die on error */
6858 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6859 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6860 } else {
6861 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6862 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6863 close(sq[i].orig_fd);
6864 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006865 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006866 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006867 }
6868
Denys Vlasenko2db74612017-07-07 22:07:28 +02006869 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006870
6871 restore_redirected_FILEs();
6872}
6873
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02006874#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02006875static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02006876{
6877 if (G_interactive_fd)
6878 close(G_interactive_fd);
6879 close_all_FILE_list();
6880}
6881#endif
6882
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006883static int internally_opened_fd(int fd, struct squirrel *sq)
6884{
6885 int i;
6886
6887#if ENABLE_HUSH_INTERACTIVE
6888 if (fd == G.interactive_fd)
6889 return 1;
6890#endif
6891 /* If this one of script's fds? */
6892 if (fd_in_FILEs(fd))
6893 return 1;
6894
6895 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6896 if (fd == sq[i].moved_to)
6897 return 1;
6898 }
6899 return 0;
6900}
6901
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006902/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6903 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02006904static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006905{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006906 struct redir_struct *redir;
6907
6908 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006909 int newfd;
6910 int closed;
6911
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006912 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006913 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006914 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006915 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6916 * of the heredoc */
6917 debug_printf_parse("set heredoc '%s'\n",
6918 redir->rd_filename);
6919 setup_heredoc(redir);
6920 continue;
6921 }
6922
6923 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006924 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006925 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02006926 int mode;
6927
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006928 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02006929 /*
6930 * Examples:
6931 * "cmd >" (no filename)
6932 * "cmd > <file" (2nd redirect starts too early)
6933 */
Denys Vlasenko39701202017-08-02 19:44:05 +02006934 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006935 continue;
6936 }
6937 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006938 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02006939 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006940 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02006941 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006942 /* Error message from open_or_warn can be lost
6943 * if stderr has been redirected, but bash
6944 * and ash both lose it as well
6945 * (though zsh doesn't!)
6946 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006947 return 1;
6948 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006949 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02006950 /* open() gave us precisely the fd we wanted.
6951 * This means that this fd was not busy
6952 * (not opened to anywhere).
6953 * Remember to close it on restore:
6954 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006955 *sqp = add_squirrel_closed(*sqp, newfd);
6956 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02006957 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006958 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006959 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
6960 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006961 }
6962
Denys Vlasenko657e9002017-07-30 23:34:04 +02006963 if (newfd == redir->rd_fd)
6964 continue;
6965
6966 /* if "N>FILE": move newfd to redir->rd_fd */
6967 /* if "N>&M": dup newfd to redir->rd_fd */
6968 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
6969
6970 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
6971 if (newfd == REDIRFD_CLOSE) {
6972 /* "N>&-" means "close me" */
6973 if (!closed) {
6974 /* ^^^ optimization: saving may already
6975 * have closed it. If not... */
6976 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006977 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006978 /* Sometimes we do another close on restore, getting EBADF.
6979 * Consider "echo 3>FILE 3>&-"
6980 * first redirect remembers "need to close 3",
6981 * and second redirect closes 3! Restore code then closes 3 again.
6982 */
6983 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006984 /* if newfd is a script fd or saved fd, simulate EBADF */
6985 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
6986 //errno = EBADF;
6987 //bb_perror_msg_and_die("can't duplicate file descriptor");
6988 newfd = -1; /* same effect as code above */
6989 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006990 xdup2(newfd, redir->rd_fd);
6991 if (redir->rd_dup == REDIRFD_TO_FILE)
6992 /* "rd_fd > FILE" */
6993 close(newfd);
6994 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006995 }
6996 }
6997 return 0;
6998}
6999
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007000static char *find_in_path(const char *arg)
7001{
7002 char *ret = NULL;
7003 const char *PATH = get_local_var_value("PATH");
7004
7005 if (!PATH)
7006 return NULL;
7007
7008 while (1) {
7009 const char *end = strchrnul(PATH, ':');
7010 int sz = end - PATH; /* must be int! */
7011
7012 free(ret);
7013 if (sz != 0) {
7014 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7015 } else {
7016 /* We have xxx::yyyy in $PATH,
7017 * it means "use current dir" */
7018 ret = xstrdup(arg);
7019 }
7020 if (access(ret, F_OK) == 0)
7021 break;
7022
7023 if (*end == '\0') {
7024 free(ret);
7025 return NULL;
7026 }
7027 PATH = end + 1;
7028 }
7029
7030 return ret;
7031}
7032
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007033static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007034 const struct built_in_command *x,
7035 const struct built_in_command *end)
7036{
7037 while (x != end) {
7038 if (strcmp(name, x->b_cmd) != 0) {
7039 x++;
7040 continue;
7041 }
7042 debug_printf_exec("found builtin '%s'\n", name);
7043 return x;
7044 }
7045 return NULL;
7046}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007047static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007048{
7049 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7050}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007051static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007052{
7053 const struct built_in_command *x = find_builtin1(name);
7054 if (x)
7055 return x;
7056 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7057}
7058
7059#if ENABLE_HUSH_FUNCTIONS
7060static struct function **find_function_slot(const char *name)
7061{
7062 struct function **funcpp = &G.top_func;
7063 while (*funcpp) {
7064 if (strcmp(name, (*funcpp)->name) == 0) {
7065 break;
7066 }
7067 funcpp = &(*funcpp)->next;
7068 }
7069 return funcpp;
7070}
7071
7072static const struct function *find_function(const char *name)
7073{
7074 const struct function *funcp = *find_function_slot(name);
7075 if (funcp)
7076 debug_printf_exec("found function '%s'\n", name);
7077 return funcp;
7078}
7079
7080/* Note: takes ownership on name ptr */
7081static struct function *new_function(char *name)
7082{
7083 struct function **funcpp = find_function_slot(name);
7084 struct function *funcp = *funcpp;
7085
7086 if (funcp != NULL) {
7087 struct command *cmd = funcp->parent_cmd;
7088 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7089 if (!cmd) {
7090 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7091 free(funcp->name);
7092 /* Note: if !funcp->body, do not free body_as_string!
7093 * This is a special case of "-F name body" function:
7094 * body_as_string was not malloced! */
7095 if (funcp->body) {
7096 free_pipe_list(funcp->body);
7097# if !BB_MMU
7098 free(funcp->body_as_string);
7099# endif
7100 }
7101 } else {
7102 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7103 cmd->argv[0] = funcp->name;
7104 cmd->group = funcp->body;
7105# if !BB_MMU
7106 cmd->group_as_string = funcp->body_as_string;
7107# endif
7108 }
7109 } else {
7110 debug_printf_exec("remembering new function '%s'\n", name);
7111 funcp = *funcpp = xzalloc(sizeof(*funcp));
7112 /*funcp->next = NULL;*/
7113 }
7114
7115 funcp->name = name;
7116 return funcp;
7117}
7118
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007119# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007120static void unset_func(const char *name)
7121{
7122 struct function **funcpp = find_function_slot(name);
7123 struct function *funcp = *funcpp;
7124
7125 if (funcp != NULL) {
7126 debug_printf_exec("freeing function '%s'\n", funcp->name);
7127 *funcpp = funcp->next;
7128 /* funcp is unlinked now, deleting it.
7129 * Note: if !funcp->body, the function was created by
7130 * "-F name body", do not free ->body_as_string
7131 * and ->name as they were not malloced. */
7132 if (funcp->body) {
7133 free_pipe_list(funcp->body);
7134 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007135# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007136 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007137# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007138 }
7139 free(funcp);
7140 }
7141}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007142# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007143
7144# if BB_MMU
7145#define exec_function(to_free, funcp, argv) \
7146 exec_function(funcp, argv)
7147# endif
7148static void exec_function(char ***to_free,
7149 const struct function *funcp,
7150 char **argv) NORETURN;
7151static void exec_function(char ***to_free,
7152 const struct function *funcp,
7153 char **argv)
7154{
7155# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007156 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007157
7158 argv[0] = G.global_argv[0];
7159 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007160 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007161
7162// Example when we are here: "cmd | func"
7163// func will run with saved-redirect fds open.
7164// $ f() { echo /proc/self/fd/*; }
7165// $ true | f
7166// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7167// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7168// Same in script:
7169// $ . ./SCRIPT
7170// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7171// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7172// They are CLOEXEC so external programs won't see them, but
7173// for "more correctness" we might want to close those extra fds here:
7174//? close_saved_fds_and_FILE_fds();
7175
7176 /* "we are in function, ok to use return" */
7177 G_flag_return_in_progress = -1;
7178 IF_HUSH_LOCAL(G.func_nest_level++;)
7179
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007180 /* On MMU, funcp->body is always non-NULL */
7181 n = run_list(funcp->body);
7182 fflush_all();
7183 _exit(n);
7184# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007185//? close_saved_fds_and_FILE_fds();
7186
7187//TODO: check whether "true | func_with_return" works
7188
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007189 re_execute_shell(to_free,
7190 funcp->body_as_string,
7191 G.global_argv[0],
7192 argv + 1,
7193 NULL);
7194# endif
7195}
7196
7197static int run_function(const struct function *funcp, char **argv)
7198{
7199 int rc;
7200 save_arg_t sv;
7201 smallint sv_flg;
7202
7203 save_and_replace_G_args(&sv, argv);
7204
7205 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007206 sv_flg = G_flag_return_in_progress;
7207 G_flag_return_in_progress = -1;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007208 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007209
7210 /* On MMU, funcp->body is always non-NULL */
7211# if !BB_MMU
7212 if (!funcp->body) {
7213 /* Function defined by -F */
7214 parse_and_run_string(funcp->body_as_string);
7215 rc = G.last_exitcode;
7216 } else
7217# endif
7218 {
7219 rc = run_list(funcp->body);
7220 }
7221
7222# if ENABLE_HUSH_LOCAL
7223 {
7224 struct variable *var;
7225 struct variable **var_pp;
7226
7227 var_pp = &G.top_var;
7228 while ((var = *var_pp) != NULL) {
7229 if (var->func_nest_level < G.func_nest_level) {
7230 var_pp = &var->next;
7231 continue;
7232 }
7233 /* Unexport */
7234 if (var->flg_export)
7235 bb_unsetenv(var->varstr);
7236 /* Remove from global list */
7237 *var_pp = var->next;
7238 /* Free */
7239 if (!var->max_len)
7240 free(var->varstr);
7241 free(var);
7242 }
7243 G.func_nest_level--;
7244 }
7245# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007246 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007247
7248 restore_G_args(&sv, argv);
7249
7250 return rc;
7251}
7252#endif /* ENABLE_HUSH_FUNCTIONS */
7253
7254
7255#if BB_MMU
7256#define exec_builtin(to_free, x, argv) \
7257 exec_builtin(x, argv)
7258#else
7259#define exec_builtin(to_free, x, argv) \
7260 exec_builtin(to_free, argv)
7261#endif
7262static void exec_builtin(char ***to_free,
7263 const struct built_in_command *x,
7264 char **argv) NORETURN;
7265static void exec_builtin(char ***to_free,
7266 const struct built_in_command *x,
7267 char **argv)
7268{
7269#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007270 int rcode;
7271 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007272//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007273 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007274 fflush_all();
7275 _exit(rcode);
7276#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007277 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007278 /* On NOMMU, we must never block!
7279 * Example: { sleep 99 | read line; } & echo Ok
7280 */
7281 re_execute_shell(to_free,
7282 argv[0],
7283 G.global_argv[0],
7284 G.global_argv + 1,
7285 argv);
7286#endif
7287}
7288
7289
7290static void execvp_or_die(char **argv) NORETURN;
7291static void execvp_or_die(char **argv)
7292{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007293 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007294 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007295 /* Don't propagate SIG_IGN to the child */
7296 if (SPECIAL_JOBSTOP_SIGS != 0)
7297 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007298 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007299 e = 2;
7300 if (errno == EACCES) e = 126;
7301 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007302 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007303 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007304}
7305
7306#if ENABLE_HUSH_MODE_X
7307static void dump_cmd_in_x_mode(char **argv)
7308{
7309 if (G_x_mode && argv) {
7310 /* We want to output the line in one write op */
7311 char *buf, *p;
7312 int len;
7313 int n;
7314
7315 len = 3;
7316 n = 0;
7317 while (argv[n])
7318 len += strlen(argv[n++]) + 1;
7319 buf = xmalloc(len);
7320 buf[0] = '+';
7321 p = buf + 1;
7322 n = 0;
7323 while (argv[n])
7324 p += sprintf(p, " %s", argv[n++]);
7325 *p++ = '\n';
7326 *p = '\0';
7327 fputs(buf, stderr);
7328 free(buf);
7329 }
7330}
7331#else
7332# define dump_cmd_in_x_mode(argv) ((void)0)
7333#endif
7334
Denys Vlasenko57000292018-01-12 14:41:45 +01007335#if ENABLE_HUSH_COMMAND
7336static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7337{
7338 char *to_free;
7339 if (!opt_vV)
7340 return;
7341
7342 to_free = NULL;
7343 if (!explanation) {
7344 char *path = getenv("PATH");
7345 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
7346 if (opt_vV != 'V')
7347 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7348 }
7349 if (explanation)
7350 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
7351 free(to_free);
7352 fflush_all();
7353 _exit(explanation == NULL); /* exit 1 if PROG was not found */
7354}
7355#else
7356# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7357#endif
7358
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007359#if BB_MMU
7360#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7361 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7362#define pseudo_exec(nommu_save, command, argv_expanded) \
7363 pseudo_exec(command, argv_expanded)
7364#endif
7365
7366/* Called after [v]fork() in run_pipe, or from builtin_exec.
7367 * Never returns.
7368 * Don't exit() here. If you don't exec, use _exit instead.
7369 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007370 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007371 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007372static void pseudo_exec_argv(nommu_save_t *nommu_save,
7373 char **argv, int assignment_cnt,
7374 char **argv_expanded) NORETURN;
7375static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7376 char **argv, int assignment_cnt,
7377 char **argv_expanded)
7378{
Denys Vlasenko57000292018-01-12 14:41:45 +01007379 const struct built_in_command *x;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007380 char **new_env;
Denys Vlasenko57000292018-01-12 14:41:45 +01007381#if ENABLE_HUSH_COMMAND
7382 char opt_vV = 0;
7383#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007384
7385 new_env = expand_assignments(argv, assignment_cnt);
7386 dump_cmd_in_x_mode(new_env);
7387
7388 if (!argv[assignment_cnt]) {
7389 /* Case when we are here: ... | var=val | ...
7390 * (note that we do not exit early, i.e., do not optimize out
7391 * expand_assignments(): think about ... | var=`sleep 1` | ...
7392 */
7393 free_strings(new_env);
7394 _exit(EXIT_SUCCESS);
7395 }
7396
7397#if BB_MMU
7398 set_vars_and_save_old(new_env);
7399 free(new_env); /* optional */
7400 /* we can also destroy set_vars_and_save_old's return value,
7401 * to save memory */
7402#else
7403 nommu_save->new_env = new_env;
7404 nommu_save->old_vars = set_vars_and_save_old(new_env);
7405#endif
7406
7407 if (argv_expanded) {
7408 argv = argv_expanded;
7409 } else {
7410 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7411#if !BB_MMU
7412 nommu_save->argv = argv;
7413#endif
7414 }
7415 dump_cmd_in_x_mode(argv);
7416
7417#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7418 if (strchr(argv[0], '/') != NULL)
7419 goto skip;
7420#endif
7421
Denys Vlasenko75481d32017-07-31 05:27:09 +02007422#if ENABLE_HUSH_FUNCTIONS
7423 /* Check if the command matches any functions (this goes before bltins) */
7424 {
7425 const struct function *funcp = find_function(argv[0]);
7426 if (funcp) {
7427 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7428 }
7429 }
7430#endif
7431
Denys Vlasenko57000292018-01-12 14:41:45 +01007432#if ENABLE_HUSH_COMMAND
7433 /* "command BAR": run BAR without looking it up among functions
7434 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7435 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7436 */
7437 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7438 char *p;
7439
7440 argv++;
7441 p = *argv;
7442 if (p[0] != '-' || !p[1])
7443 continue; /* bash allows "command command command [-OPT] BAR" */
7444
7445 for (;;) {
7446 p++;
7447 switch (*p) {
7448 case '\0':
7449 argv++;
7450 p = *argv;
7451 if (p[0] != '-' || !p[1])
7452 goto after_opts;
7453 continue; /* next arg is also -opts, process it too */
7454 case 'v':
7455 case 'V':
7456 opt_vV = *p;
7457 continue;
7458 default:
7459 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7460 }
7461 }
7462 }
7463 after_opts:
7464# if ENABLE_HUSH_FUNCTIONS
7465 if (opt_vV && find_function(argv[0]))
7466 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7467# endif
7468#endif
7469
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007470 /* Check if the command matches any of the builtins.
7471 * Depending on context, this might be redundant. But it's
7472 * easier to waste a few CPU cycles than it is to figure out
7473 * if this is one of those cases.
7474 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007475 /* Why "BB_MMU ? :" difference in logic? -
7476 * On NOMMU, it is more expensive to re-execute shell
7477 * just in order to run echo or test builtin.
7478 * It's better to skip it here and run corresponding
7479 * non-builtin later. */
7480 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7481 if (x) {
7482 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7483 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007484 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007485
7486#if ENABLE_FEATURE_SH_STANDALONE
7487 /* Check if the command matches any busybox applets */
7488 {
7489 int a = find_applet_by_name(argv[0]);
7490 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007491 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007492# if BB_MMU /* see above why on NOMMU it is not allowed */
7493 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007494 /* Do not leak open fds from opened script files etc.
7495 * Testcase: interactive "ls -l /proc/self/fd"
7496 * should not show tty fd open.
7497 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007498 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007499//FIXME: should also close saved redir fds
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007500 /* Without this, "rm -i FILE" can't be ^C'ed: */
7501 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007502 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007503 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007504 }
7505# endif
7506 /* Re-exec ourselves */
7507 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007508 /* Don't propagate SIG_IGN to the child */
7509 if (SPECIAL_JOBSTOP_SIGS != 0)
7510 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007511 execv(bb_busybox_exec_path, argv);
7512 /* If they called chroot or otherwise made the binary no longer
7513 * executable, fall through */
7514 }
7515 }
7516#endif
7517
7518#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7519 skip:
7520#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007521 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007522 execvp_or_die(argv);
7523}
7524
7525/* Called after [v]fork() in run_pipe
7526 */
7527static void pseudo_exec(nommu_save_t *nommu_save,
7528 struct command *command,
7529 char **argv_expanded) NORETURN;
7530static void pseudo_exec(nommu_save_t *nommu_save,
7531 struct command *command,
7532 char **argv_expanded)
7533{
7534 if (command->argv) {
7535 pseudo_exec_argv(nommu_save, command->argv,
7536 command->assignment_cnt, argv_expanded);
7537 }
7538
7539 if (command->group) {
7540 /* Cases when we are here:
7541 * ( list )
7542 * { list } &
7543 * ... | ( list ) | ...
7544 * ... | { list } | ...
7545 */
7546#if BB_MMU
7547 int rcode;
7548 debug_printf_exec("pseudo_exec: run_list\n");
7549 reset_traps_to_defaults();
7550 rcode = run_list(command->group);
7551 /* OK to leak memory by not calling free_pipe_list,
7552 * since this process is about to exit */
7553 _exit(rcode);
7554#else
7555 re_execute_shell(&nommu_save->argv_from_re_execing,
7556 command->group_as_string,
7557 G.global_argv[0],
7558 G.global_argv + 1,
7559 NULL);
7560#endif
7561 }
7562
7563 /* Case when we are here: ... | >file */
7564 debug_printf_exec("pseudo_exec'ed null command\n");
7565 _exit(EXIT_SUCCESS);
7566}
7567
7568#if ENABLE_HUSH_JOB
7569static const char *get_cmdtext(struct pipe *pi)
7570{
7571 char **argv;
7572 char *p;
7573 int len;
7574
7575 /* This is subtle. ->cmdtext is created only on first backgrounding.
7576 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7577 * On subsequent bg argv is trashed, but we won't use it */
7578 if (pi->cmdtext)
7579 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007580
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007581 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007582 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007583 pi->cmdtext = xzalloc(1);
7584 return pi->cmdtext;
7585 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007586 len = 0;
7587 do {
7588 len += strlen(*argv) + 1;
7589 } while (*++argv);
7590 p = xmalloc(len);
7591 pi->cmdtext = p;
7592 argv = pi->cmds[0].argv;
7593 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007594 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007595 *p++ = ' ';
7596 } while (*++argv);
7597 p[-1] = '\0';
7598 return pi->cmdtext;
7599}
7600
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007601static void remove_job_from_table(struct pipe *pi)
7602{
7603 struct pipe *prev_pipe;
7604
7605 if (pi == G.job_list) {
7606 G.job_list = pi->next;
7607 } else {
7608 prev_pipe = G.job_list;
7609 while (prev_pipe->next != pi)
7610 prev_pipe = prev_pipe->next;
7611 prev_pipe->next = pi->next;
7612 }
7613 G.last_jobid = 0;
7614 if (G.job_list)
7615 G.last_jobid = G.job_list->jobid;
7616}
7617
7618static void delete_finished_job(struct pipe *pi)
7619{
7620 remove_job_from_table(pi);
7621 free_pipe(pi);
7622}
7623
7624static void clean_up_last_dead_job(void)
7625{
7626 if (G.job_list && !G.job_list->alive_cmds)
7627 delete_finished_job(G.job_list);
7628}
7629
Denys Vlasenko16096292017-07-10 10:00:28 +02007630static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007631{
7632 struct pipe *job, **jobp;
7633 int i;
7634
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007635 clean_up_last_dead_job();
7636
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007637 /* Find the end of the list, and find next job ID to use */
7638 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007639 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007640 while ((job = *jobp) != NULL) {
7641 if (job->jobid > i)
7642 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007643 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007644 }
7645 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007646
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007647 /* Create a new job struct at the end */
7648 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007649 job->next = NULL;
7650 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7651 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7652 for (i = 0; i < pi->num_cmds; i++) {
7653 job->cmds[i].pid = pi->cmds[i].pid;
7654 /* all other fields are not used and stay zero */
7655 }
7656 job->cmdtext = xstrdup(get_cmdtext(pi));
7657
7658 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007659 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007660 G.last_jobid = job->jobid;
7661}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007662#endif /* JOB */
7663
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007664static int job_exited_or_stopped(struct pipe *pi)
7665{
7666 int rcode, i;
7667
7668 if (pi->alive_cmds != pi->stopped_cmds)
7669 return -1;
7670
7671 /* All processes in fg pipe have exited or stopped */
7672 rcode = 0;
7673 i = pi->num_cmds;
7674 while (--i >= 0) {
7675 rcode = pi->cmds[i].cmd_exitcode;
7676 /* usually last process gives overall exitstatus,
7677 * but with "set -o pipefail", last *failed* process does */
7678 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7679 break;
7680 }
7681 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7682 return rcode;
7683}
7684
Denys Vlasenko7e675362016-10-28 21:57:31 +02007685static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007686{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007687#if ENABLE_HUSH_JOB
7688 struct pipe *pi;
7689#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007690 int i, dead;
7691
7692 dead = WIFEXITED(status) || WIFSIGNALED(status);
7693
7694#if DEBUG_JOBS
7695 if (WIFSTOPPED(status))
7696 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7697 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7698 if (WIFSIGNALED(status))
7699 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7700 childpid, WTERMSIG(status), WEXITSTATUS(status));
7701 if (WIFEXITED(status))
7702 debug_printf_jobs("pid %d exited, exitcode %d\n",
7703 childpid, WEXITSTATUS(status));
7704#endif
7705 /* Were we asked to wait for a fg pipe? */
7706 if (fg_pipe) {
7707 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007708
Denys Vlasenko7e675362016-10-28 21:57:31 +02007709 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007710 int rcode;
7711
Denys Vlasenko7e675362016-10-28 21:57:31 +02007712 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7713 if (fg_pipe->cmds[i].pid != childpid)
7714 continue;
7715 if (dead) {
7716 int ex;
7717 fg_pipe->cmds[i].pid = 0;
7718 fg_pipe->alive_cmds--;
7719 ex = WEXITSTATUS(status);
7720 /* bash prints killer signal's name for *last*
7721 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7722 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7723 */
7724 if (WIFSIGNALED(status)) {
7725 int sig = WTERMSIG(status);
7726 if (i == fg_pipe->num_cmds-1)
7727 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7728 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7729 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7730 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7731 * Maybe we need to use sig | 128? */
7732 ex = sig + 128;
7733 }
7734 fg_pipe->cmds[i].cmd_exitcode = ex;
7735 } else {
7736 fg_pipe->stopped_cmds++;
7737 }
7738 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7739 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007740 rcode = job_exited_or_stopped(fg_pipe);
7741 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007742/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7743 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7744 * and "killall -STOP cat" */
7745 if (G_interactive_fd) {
7746#if ENABLE_HUSH_JOB
7747 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02007748 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007749#endif
7750 return rcode;
7751 }
7752 if (fg_pipe->alive_cmds == 0)
7753 return rcode;
7754 }
7755 /* There are still running processes in the fg_pipe */
7756 return -1;
7757 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02007758 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02007759 }
7760
7761#if ENABLE_HUSH_JOB
7762 /* We were asked to wait for bg or orphaned children */
7763 /* No need to remember exitcode in this case */
7764 for (pi = G.job_list; pi; pi = pi->next) {
7765 for (i = 0; i < pi->num_cmds; i++) {
7766 if (pi->cmds[i].pid == childpid)
7767 goto found_pi_and_prognum;
7768 }
7769 }
7770 /* Happens when shell is used as init process (init=/bin/sh) */
7771 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7772 return -1; /* this wasn't a process from fg_pipe */
7773
7774 found_pi_and_prognum:
7775 if (dead) {
7776 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02007777 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007778 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02007779 rcode = 128 + WTERMSIG(status);
7780 pi->cmds[i].cmd_exitcode = rcode;
7781 if (G.last_bg_pid == pi->cmds[i].pid)
7782 G.last_bg_pid_exitcode = rcode;
7783 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007784 pi->alive_cmds--;
7785 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007786 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007787 printf(JOB_STATUS_FORMAT, pi->jobid,
7788 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007789 delete_finished_job(pi);
7790 } else {
7791/*
7792 * bash deletes finished jobs from job table only in interactive mode,
7793 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7794 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7795 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7796 * We only retain one "dead" job, if it's the single job on the list.
7797 * This covers most of real-world scenarios where this is useful.
7798 */
7799 if (pi != G.job_list)
7800 delete_finished_job(pi);
7801 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007802 }
7803 } else {
7804 /* child stopped */
7805 pi->stopped_cmds++;
7806 }
7807#endif
7808 return -1; /* this wasn't a process from fg_pipe */
7809}
7810
7811/* Check to see if any processes have exited -- if they have,
7812 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007813 *
7814 * If non-NULL fg_pipe: wait for its completion or stop.
7815 * Return its exitcode or zero if stopped.
7816 *
7817 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7818 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7819 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7820 * or 0 if no children changed status.
7821 *
7822 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7823 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7824 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007825 */
7826static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7827{
7828 int attributes;
7829 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007830 int rcode = 0;
7831
7832 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7833
7834 attributes = WUNTRACED;
7835 if (fg_pipe == NULL)
7836 attributes |= WNOHANG;
7837
7838 errno = 0;
7839#if ENABLE_HUSH_FAST
7840 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7841//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7842//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7843 /* There was neither fork nor SIGCHLD since last waitpid */
7844 /* Avoid doing waitpid syscall if possible */
7845 if (!G.we_have_children) {
7846 errno = ECHILD;
7847 return -1;
7848 }
7849 if (fg_pipe == NULL) { /* is WNOHANG set? */
7850 /* We have children, but they did not exit
7851 * or stop yet (we saw no SIGCHLD) */
7852 return 0;
7853 }
7854 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7855 }
7856#endif
7857
7858/* Do we do this right?
7859 * bash-3.00# sleep 20 | false
7860 * <ctrl-Z pressed>
7861 * [3]+ Stopped sleep 20 | false
7862 * bash-3.00# echo $?
7863 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7864 * [hush 1.14.0: yes we do it right]
7865 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007866 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007867 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007868#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02007869 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007870 i = G.count_SIGCHLD;
7871#endif
7872 childpid = waitpid(-1, &status, attributes);
7873 if (childpid <= 0) {
7874 if (childpid && errno != ECHILD)
7875 bb_perror_msg("waitpid");
7876#if ENABLE_HUSH_FAST
7877 else { /* Until next SIGCHLD, waitpid's are useless */
7878 G.we_have_children = (childpid == 0);
7879 G.handled_SIGCHLD = i;
7880//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7881 }
7882#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007883 /* ECHILD (no children), or 0 (no change in children status) */
7884 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007885 break;
7886 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007887 rcode = process_wait_result(fg_pipe, childpid, status);
7888 if (rcode >= 0) {
7889 /* fg_pipe exited or stopped */
7890 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007891 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007892 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007893 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007894 rcode = WEXITSTATUS(status);
7895 if (WIFSIGNALED(status))
7896 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007897 if (WIFSTOPPED(status))
7898 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7899 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007900 rcode++;
7901 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007902 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007903 /* This wasn't one of our processes, or */
7904 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007905 } /* while (waitpid succeeds)... */
7906
7907 return rcode;
7908}
7909
7910#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007911static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007912{
7913 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007914 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007915 if (G_saved_tty_pgrp) {
7916 /* Job finished, move the shell to the foreground */
7917 p = getpgrp(); /* our process group id */
7918 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7919 tcsetpgrp(G_interactive_fd, p);
7920 }
7921 return rcode;
7922}
7923#endif
7924
7925/* Start all the jobs, but don't wait for anything to finish.
7926 * See checkjobs().
7927 *
7928 * Return code is normally -1, when the caller has to wait for children
7929 * to finish to determine the exit status of the pipe. If the pipe
7930 * is a simple builtin command, however, the action is done by the
7931 * time run_pipe returns, and the exit code is provided as the
7932 * return value.
7933 *
7934 * Returns -1 only if started some children. IOW: we have to
7935 * mask out retvals of builtins etc with 0xff!
7936 *
7937 * The only case when we do not need to [v]fork is when the pipe
7938 * is single, non-backgrounded, non-subshell command. Examples:
7939 * cmd ; ... { list } ; ...
7940 * cmd && ... { list } && ...
7941 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007942 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007943 * or (if SH_STANDALONE) an applet, and we can run the { list }
7944 * with run_list. If it isn't one of these, we fork and exec cmd.
7945 *
7946 * Cases when we must fork:
7947 * non-single: cmd | cmd
7948 * backgrounded: cmd & { list } &
7949 * subshell: ( list ) [&]
7950 */
7951#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007952#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007953 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7954#endif
7955static int redirect_and_varexp_helper(char ***new_env_p,
7956 struct variable **old_vars_p,
7957 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02007958 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007959 char **argv_expanded)
7960{
7961 /* setup_redirects acts on file descriptors, not FILEs.
7962 * This is perfect for work that comes after exec().
7963 * Is it really safe for inline use? Experimentally,
7964 * things seem to work. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007965 int rcode = setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007966 if (rcode == 0) {
7967 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7968 *new_env_p = new_env;
7969 dump_cmd_in_x_mode(new_env);
7970 dump_cmd_in_x_mode(argv_expanded);
7971 if (old_vars_p)
7972 *old_vars_p = set_vars_and_save_old(new_env);
7973 }
7974 return rcode;
7975}
7976static NOINLINE int run_pipe(struct pipe *pi)
7977{
7978 static const char *const null_ptr = NULL;
7979
7980 int cmd_no;
7981 int next_infd;
7982 struct command *command;
7983 char **argv_expanded;
7984 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007985 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007986 int rcode;
7987
7988 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7989 debug_enter();
7990
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007991 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7992 * Result should be 3 lines: q w e, qwe, q w e
7993 */
7994 G.ifs = get_local_var_value("IFS");
7995 if (!G.ifs)
7996 G.ifs = defifs;
7997
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007998 IF_HUSH_JOB(pi->pgrp = -1;)
7999 pi->stopped_cmds = 0;
8000 command = &pi->cmds[0];
8001 argv_expanded = NULL;
8002
8003 if (pi->num_cmds != 1
8004 || pi->followup == PIPE_BG
8005 || command->cmd_type == CMD_SUBSHELL
8006 ) {
8007 goto must_fork;
8008 }
8009
8010 pi->alive_cmds = 1;
8011
8012 debug_printf_exec(": group:%p argv:'%s'\n",
8013 command->group, command->argv ? command->argv[0] : "NONE");
8014
8015 if (command->group) {
8016#if ENABLE_HUSH_FUNCTIONS
8017 if (command->cmd_type == CMD_FUNCDEF) {
8018 /* "executing" func () { list } */
8019 struct function *funcp;
8020
8021 funcp = new_function(command->argv[0]);
8022 /* funcp->name is already set to argv[0] */
8023 funcp->body = command->group;
8024# if !BB_MMU
8025 funcp->body_as_string = command->group_as_string;
8026 command->group_as_string = NULL;
8027# endif
8028 command->group = NULL;
8029 command->argv[0] = NULL;
8030 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8031 funcp->parent_cmd = command;
8032 command->child_func = funcp;
8033
8034 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8035 debug_leave();
8036 return EXIT_SUCCESS;
8037 }
8038#endif
8039 /* { list } */
8040 debug_printf("non-subshell group\n");
8041 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008042 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008043 debug_printf_exec(": run_list\n");
8044 rcode = run_list(command->group) & 0xff;
8045 }
8046 restore_redirects(squirrel);
8047 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8048 debug_leave();
8049 debug_printf_exec("run_pipe: return %d\n", rcode);
8050 return rcode;
8051 }
8052
8053 argv = command->argv ? command->argv : (char **) &null_ptr;
8054 {
8055 const struct built_in_command *x;
8056#if ENABLE_HUSH_FUNCTIONS
8057 const struct function *funcp;
8058#else
8059 enum { funcp = 0 };
8060#endif
8061 char **new_env = NULL;
8062 struct variable *old_vars = NULL;
8063
8064 if (argv[command->assignment_cnt] == NULL) {
8065 /* Assignments, but no command */
8066 /* Ensure redirects take effect (that is, create files).
8067 * Try "a=t >file" */
8068#if 0 /* A few cases in testsuite fail with this code. FIXME */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008069 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008070 /* Set shell variables */
8071 if (new_env) {
8072 argv = new_env;
8073 while (*argv) {
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008074 if (set_local_var(*argv, /*flag:*/ 0)) {
8075 /* assignment to readonly var / putenv error? */
8076 rcode = 1;
8077 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008078 argv++;
8079 }
8080 }
8081 /* Redirect error sets $? to 1. Otherwise,
8082 * if evaluating assignment value set $?, retain it.
8083 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8084 if (rcode == 0)
8085 rcode = G.last_exitcode;
8086 /* Exit, _skipping_ variable restoring code: */
8087 goto clean_up_and_ret0;
8088
8089#else /* Older, bigger, but more correct code */
8090
Denys Vlasenko2db74612017-07-07 22:07:28 +02008091 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008092 restore_redirects(squirrel);
8093 /* Set shell variables */
8094 if (G_x_mode)
8095 bb_putchar_stderr('+');
8096 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02008097 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008098 if (G_x_mode)
8099 fprintf(stderr, " %s", p);
8100 debug_printf_exec("set shell var:'%s'->'%s'\n",
8101 *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008102 if (set_local_var(p, /*flag:*/ 0)) {
8103 /* assignment to readonly var / putenv error? */
8104 rcode = 1;
8105 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008106 argv++;
8107 }
8108 if (G_x_mode)
8109 bb_putchar_stderr('\n');
8110 /* Redirect error sets $? to 1. Otherwise,
8111 * if evaluating assignment value set $?, retain it.
8112 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8113 if (rcode == 0)
8114 rcode = G.last_exitcode;
8115 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8116 debug_leave();
8117 debug_printf_exec("run_pipe: return %d\n", rcode);
8118 return rcode;
8119#endif
8120 }
8121
8122 /* Expand the rest into (possibly) many strings each */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01008123#if BASH_TEST2
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008124 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008125 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008126 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008127#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008128 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008129 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8130 }
8131
8132 /* if someone gives us an empty string: `cmd with empty output` */
8133 if (!argv_expanded[0]) {
8134 free(argv_expanded);
8135 debug_leave();
8136 return G.last_exitcode;
8137 }
8138
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008139#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko75481d32017-07-31 05:27:09 +02008140 /* Check if argv[0] matches any functions (this goes before bltins) */
8141 funcp = find_function(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008142#endif
Denys Vlasenko75481d32017-07-31 05:27:09 +02008143 x = NULL;
8144 if (!funcp)
8145 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008146 if (x || funcp) {
8147 if (!funcp) {
8148 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8149 debug_printf("exec with redirects only\n");
8150 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008151 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008152 goto clean_up_and_ret1;
8153 }
8154 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02008155 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008156 if (rcode == 0) {
8157 if (!funcp) {
8158 debug_printf_exec(": builtin '%s' '%s'...\n",
8159 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008160 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008161 rcode = x->b_function(argv_expanded) & 0xff;
8162 fflush_all();
8163 }
8164#if ENABLE_HUSH_FUNCTIONS
8165 else {
8166# if ENABLE_HUSH_LOCAL
8167 struct variable **sv;
8168 sv = G.shadowed_vars_pp;
8169 G.shadowed_vars_pp = &old_vars;
8170# endif
8171 debug_printf_exec(": function '%s' '%s'...\n",
8172 funcp->name, argv_expanded[1]);
8173 rcode = run_function(funcp, argv_expanded) & 0xff;
8174# if ENABLE_HUSH_LOCAL
8175 G.shadowed_vars_pp = sv;
8176# endif
8177 }
8178#endif
8179 }
8180 clean_up_and_ret:
8181 unset_vars(new_env);
8182 add_vars(old_vars);
8183/* clean_up_and_ret0: */
8184 restore_redirects(squirrel);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008185 /*
8186 * Try "usleep 99999999" + ^C + "echo $?"
8187 * with FEATURE_SH_NOFORK=y.
8188 */
8189 if (!funcp) {
8190 /* It was builtin or nofork.
8191 * if this would be a real fork/execed program,
8192 * it should have died if a fatal sig was received.
8193 * But OTOH, there was no separate process,
8194 * the sig was sent to _shell_, not to non-existing
8195 * child.
8196 * Let's just handle ^C only, this one is obvious:
8197 * we aren't ok with exitcode 0 when ^C was pressed
8198 * during builtin/nofork.
8199 */
8200 if (sigismember(&G.pending_set, SIGINT))
8201 rcode = 128 + SIGINT;
8202 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008203 clean_up_and_ret1:
8204 free(argv_expanded);
8205 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8206 debug_leave();
8207 debug_printf_exec("run_pipe return %d\n", rcode);
8208 return rcode;
8209 }
8210
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008211 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008212 int n = find_applet_by_name(argv_expanded[0]);
8213 if (n >= 0 && APPLET_IS_NOFORK(n)) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02008214 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008215 if (rcode == 0) {
8216 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8217 argv_expanded[0], argv_expanded[1]);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008218 /*
8219 * Note: signals (^C) can't interrupt here.
8220 * We remember them and they will be acted upon
8221 * after applet returns.
8222 * This makes applets which can run for a long time
8223 * and/or wait for user input ineligible for NOFORK:
8224 * for example, "yes" or "rm" (rm -i waits for input).
8225 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008226 rcode = run_nofork_applet(n, argv_expanded);
8227 }
8228 goto clean_up_and_ret;
8229 }
8230 }
8231 /* It is neither builtin nor applet. We must fork. */
8232 }
8233
8234 must_fork:
8235 /* NB: argv_expanded may already be created, and that
8236 * might include `cmd` runs! Do not rerun it! We *must*
8237 * use argv_expanded if it's non-NULL */
8238
8239 /* Going to fork a child per each pipe member */
8240 pi->alive_cmds = 0;
8241 next_infd = 0;
8242
8243 cmd_no = 0;
8244 while (cmd_no < pi->num_cmds) {
8245 struct fd_pair pipefds;
8246#if !BB_MMU
8247 volatile nommu_save_t nommu_save;
8248 nommu_save.new_env = NULL;
8249 nommu_save.old_vars = NULL;
8250 nommu_save.argv = NULL;
8251 nommu_save.argv_from_re_execing = NULL;
8252#endif
8253 command = &pi->cmds[cmd_no];
8254 cmd_no++;
8255 if (command->argv) {
8256 debug_printf_exec(": pipe member '%s' '%s'...\n",
8257 command->argv[0], command->argv[1]);
8258 } else {
8259 debug_printf_exec(": pipe member with no argv\n");
8260 }
8261
8262 /* pipes are inserted between pairs of commands */
8263 pipefds.rd = 0;
8264 pipefds.wr = 1;
8265 if (cmd_no < pi->num_cmds)
8266 xpiped_pair(pipefds);
8267
8268 command->pid = BB_MMU ? fork() : vfork();
8269 if (!command->pid) { /* child */
8270#if ENABLE_HUSH_JOB
8271 disable_restore_tty_pgrp_on_exit();
8272 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8273
8274 /* Every child adds itself to new process group
8275 * with pgid == pid_of_first_child_in_pipe */
8276 if (G.run_list_level == 1 && G_interactive_fd) {
8277 pid_t pgrp;
8278 pgrp = pi->pgrp;
8279 if (pgrp < 0) /* true for 1st process only */
8280 pgrp = getpid();
8281 if (setpgid(0, pgrp) == 0
8282 && pi->followup != PIPE_BG
8283 && G_saved_tty_pgrp /* we have ctty */
8284 ) {
8285 /* We do it in *every* child, not just first,
8286 * to avoid races */
8287 tcsetpgrp(G_interactive_fd, pgrp);
8288 }
8289 }
8290#endif
8291 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8292 /* 1st cmd in backgrounded pipe
8293 * should have its stdin /dev/null'ed */
8294 close(0);
8295 if (open(bb_dev_null, O_RDONLY))
8296 xopen("/", O_RDONLY);
8297 } else {
8298 xmove_fd(next_infd, 0);
8299 }
8300 xmove_fd(pipefds.wr, 1);
8301 if (pipefds.rd > 1)
8302 close(pipefds.rd);
8303 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008304 * and the pipe fd (fd#1) is available for dup'ing:
8305 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8306 * of cmd1 goes into pipe.
8307 */
8308 if (setup_redirects(command, NULL)) {
8309 /* Happens when redir file can't be opened:
8310 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8311 * FOO
8312 * hush: can't open '/qwe/rty': No such file or directory
8313 * BAZ
8314 * (echo BAR is not executed, it hits _exit(1) below)
8315 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008316 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008317 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008318
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008319 /* Stores to nommu_save list of env vars putenv'ed
8320 * (NOMMU, on MMU we don't need that) */
8321 /* cast away volatility... */
8322 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8323 /* pseudo_exec() does not return */
8324 }
8325
8326 /* parent or error */
8327#if ENABLE_HUSH_FAST
8328 G.count_SIGCHLD++;
8329//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8330#endif
8331 enable_restore_tty_pgrp_on_exit();
8332#if !BB_MMU
8333 /* Clean up after vforked child */
8334 free(nommu_save.argv);
8335 free(nommu_save.argv_from_re_execing);
8336 unset_vars(nommu_save.new_env);
8337 add_vars(nommu_save.old_vars);
8338#endif
8339 free(argv_expanded);
8340 argv_expanded = NULL;
8341 if (command->pid < 0) { /* [v]fork failed */
8342 /* Clearly indicate, was it fork or vfork */
8343 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8344 } else {
8345 pi->alive_cmds++;
8346#if ENABLE_HUSH_JOB
8347 /* Second and next children need to know pid of first one */
8348 if (pi->pgrp < 0)
8349 pi->pgrp = command->pid;
8350#endif
8351 }
8352
8353 if (cmd_no > 1)
8354 close(next_infd);
8355 if (cmd_no < pi->num_cmds)
8356 close(pipefds.wr);
8357 /* Pass read (output) pipe end to next iteration */
8358 next_infd = pipefds.rd;
8359 }
8360
8361 if (!pi->alive_cmds) {
8362 debug_leave();
8363 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8364 return 1;
8365 }
8366
8367 debug_leave();
8368 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8369 return -1;
8370}
8371
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008372/* NB: called by pseudo_exec, and therefore must not modify any
8373 * global data until exec/_exit (we can be a child after vfork!) */
8374static int run_list(struct pipe *pi)
8375{
8376#if ENABLE_HUSH_CASE
8377 char *case_word = NULL;
8378#endif
8379#if ENABLE_HUSH_LOOPS
8380 struct pipe *loop_top = NULL;
8381 char **for_lcur = NULL;
8382 char **for_list = NULL;
8383#endif
8384 smallint last_followup;
8385 smalluint rcode;
8386#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8387 smalluint cond_code = 0;
8388#else
8389 enum { cond_code = 0 };
8390#endif
8391#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008392 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008393 smallint last_rword; /* ditto */
8394#endif
8395
8396 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8397 debug_enter();
8398
8399#if ENABLE_HUSH_LOOPS
8400 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008401 {
8402 struct pipe *cpipe;
8403 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8404 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8405 continue;
8406 /* current word is FOR or IN (BOLD in comments below) */
8407 if (cpipe->next == NULL) {
8408 syntax_error("malformed for");
8409 debug_leave();
8410 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8411 return 1;
8412 }
8413 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8414 if (cpipe->next->res_word == RES_DO)
8415 continue;
8416 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8417 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8418 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8419 ) {
8420 syntax_error("malformed for");
8421 debug_leave();
8422 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8423 return 1;
8424 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008425 }
8426 }
8427#endif
8428
8429 /* Past this point, all code paths should jump to ret: label
8430 * in order to return, no direct "return" statements please.
8431 * This helps to ensure that no memory is leaked. */
8432
8433#if ENABLE_HUSH_JOB
8434 G.run_list_level++;
8435#endif
8436
8437#if HAS_KEYWORDS
8438 rword = RES_NONE;
8439 last_rword = RES_XXXX;
8440#endif
8441 last_followup = PIPE_SEQ;
8442 rcode = G.last_exitcode;
8443
8444 /* Go through list of pipes, (maybe) executing them. */
8445 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008446 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008447 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008448
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008449 if (G.flag_SIGINT)
8450 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008451 if (G_flag_return_in_progress == 1)
8452 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008453
8454 IF_HAS_KEYWORDS(rword = pi->res_word;)
8455 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8456 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008457
8458 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008459 if (
8460#if ENABLE_HUSH_IF
8461 rword == RES_IF || rword == RES_ELIF ||
8462#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008463 pi->followup != PIPE_SEQ
8464 ) {
8465 G.errexit_depth++;
8466 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008467#if ENABLE_HUSH_LOOPS
8468 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8469 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8470 ) {
8471 /* start of a loop: remember where loop starts */
8472 loop_top = pi;
8473 G.depth_of_loop++;
8474 }
8475#endif
8476 /* Still in the same "if...", "then..." or "do..." branch? */
8477 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8478 if ((rcode == 0 && last_followup == PIPE_OR)
8479 || (rcode != 0 && last_followup == PIPE_AND)
8480 ) {
8481 /* It is "<true> || CMD" or "<false> && CMD"
8482 * and we should not execute CMD */
8483 debug_printf_exec("skipped cmd because of || or &&\n");
8484 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008485 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008486 }
8487 }
8488 last_followup = pi->followup;
8489 IF_HAS_KEYWORDS(last_rword = rword;)
8490#if ENABLE_HUSH_IF
8491 if (cond_code) {
8492 if (rword == RES_THEN) {
8493 /* if false; then ... fi has exitcode 0! */
8494 G.last_exitcode = rcode = EXIT_SUCCESS;
8495 /* "if <false> THEN cmd": skip cmd */
8496 continue;
8497 }
8498 } else {
8499 if (rword == RES_ELSE || rword == RES_ELIF) {
8500 /* "if <true> then ... ELSE/ELIF cmd":
8501 * skip cmd and all following ones */
8502 break;
8503 }
8504 }
8505#endif
8506#if ENABLE_HUSH_LOOPS
8507 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8508 if (!for_lcur) {
8509 /* first loop through for */
8510
8511 static const char encoded_dollar_at[] ALIGN1 = {
8512 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8513 }; /* encoded representation of "$@" */
8514 static const char *const encoded_dollar_at_argv[] = {
8515 encoded_dollar_at, NULL
8516 }; /* argv list with one element: "$@" */
8517 char **vals;
8518
8519 vals = (char**)encoded_dollar_at_argv;
8520 if (pi->next->res_word == RES_IN) {
8521 /* if no variable values after "in" we skip "for" */
8522 if (!pi->next->cmds[0].argv) {
8523 G.last_exitcode = rcode = EXIT_SUCCESS;
8524 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8525 break;
8526 }
8527 vals = pi->next->cmds[0].argv;
8528 } /* else: "for var; do..." -> assume "$@" list */
8529 /* create list of variable values */
8530 debug_print_strings("for_list made from", vals);
8531 for_list = expand_strvec_to_strvec(vals);
8532 for_lcur = for_list;
8533 debug_print_strings("for_list", for_list);
8534 }
8535 if (!*for_lcur) {
8536 /* "for" loop is over, clean up */
8537 free(for_list);
8538 for_list = NULL;
8539 for_lcur = NULL;
8540 break;
8541 }
8542 /* Insert next value from for_lcur */
8543 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008544 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008545 continue;
8546 }
8547 if (rword == RES_IN) {
8548 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8549 }
8550 if (rword == RES_DONE) {
8551 continue; /* "done" has no cmds too */
8552 }
8553#endif
8554#if ENABLE_HUSH_CASE
8555 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008556 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008557 case_word = expand_strvec_to_string(pi->cmds->argv);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008558 unbackslash(case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008559 continue;
8560 }
8561 if (rword == RES_MATCH) {
8562 char **argv;
8563
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008564 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008565 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8566 break;
8567 /* all prev words didn't match, does this one match? */
8568 argv = pi->cmds->argv;
8569 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008570 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008571 /* TODO: which FNM_xxx flags to use? */
8572 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008573 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008574 free(pattern);
8575 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008576 free(case_word);
8577 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008578 break;
8579 }
8580 argv++;
8581 }
8582 continue;
8583 }
8584 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008585 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008586 if (cond_code != 0)
8587 continue; /* not matched yet, skip this pipe */
8588 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008589 if (rword == RES_ESAC) {
8590 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8591 if (case_word) {
8592 /* "case" did not match anything: still set $? (to 0) */
8593 G.last_exitcode = rcode = EXIT_SUCCESS;
8594 }
8595 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008596#endif
8597 /* Just pressing <enter> in shell should check for jobs.
8598 * OTOH, in non-interactive shell this is useless
8599 * and only leads to extra job checks */
8600 if (pi->num_cmds == 0) {
8601 if (G_interactive_fd)
8602 goto check_jobs_and_continue;
8603 continue;
8604 }
8605
8606 /* After analyzing all keywords and conditions, we decided
8607 * to execute this pipe. NB: have to do checkjobs(NULL)
8608 * after run_pipe to collect any background children,
8609 * even if list execution is to be stopped. */
8610 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008611#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008612 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008613#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008614 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8615 if (r != -1) {
8616 /* We ran a builtin, function, or group.
8617 * rcode is already known
8618 * and we don't need to wait for anything. */
8619 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8620 G.last_exitcode = rcode;
8621 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008622#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008623 /* Was it "break" or "continue"? */
8624 if (G.flag_break_continue) {
8625 smallint fbc = G.flag_break_continue;
8626 /* We might fall into outer *loop*,
8627 * don't want to break it too */
8628 if (loop_top) {
8629 G.depth_break_continue--;
8630 if (G.depth_break_continue == 0)
8631 G.flag_break_continue = 0;
8632 /* else: e.g. "continue 2" should *break* once, *then* continue */
8633 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8634 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008635 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008636 break;
8637 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008638 /* "continue": simulate end of loop */
8639 rword = RES_DONE;
8640 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008641 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008642#endif
8643 if (G_flag_return_in_progress == 1) {
8644 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8645 break;
8646 }
8647 } else if (pi->followup == PIPE_BG) {
8648 /* What does bash do with attempts to background builtins? */
8649 /* even bash 3.2 doesn't do that well with nested bg:
8650 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8651 * I'm NOT treating inner &'s as jobs */
8652#if ENABLE_HUSH_JOB
8653 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008654 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008655#endif
8656 /* Last command's pid goes to $! */
8657 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008658 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008659 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008660/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008661 rcode = EXIT_SUCCESS;
8662 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008663 } else {
8664#if ENABLE_HUSH_JOB
8665 if (G.run_list_level == 1 && G_interactive_fd) {
8666 /* Waits for completion, then fg's main shell */
8667 rcode = checkjobs_and_fg_shell(pi);
8668 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008669 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008670 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008671#endif
8672 /* This one just waits for completion */
8673 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8674 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8675 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008676 G.last_exitcode = rcode;
8677 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008678 }
8679
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008680 /* Handle "set -e" */
8681 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8682 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8683 if (G.errexit_depth == 0)
8684 hush_exit(rcode);
8685 }
8686 G.errexit_depth = sv_errexit_depth;
8687
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008688 /* Analyze how result affects subsequent commands */
8689#if ENABLE_HUSH_IF
8690 if (rword == RES_IF || rword == RES_ELIF)
8691 cond_code = rcode;
8692#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008693 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008694 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008695 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008696#if ENABLE_HUSH_LOOPS
8697 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008698 if (pi->next
8699 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008700 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008701 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008702 if (rword == RES_WHILE) {
8703 if (rcode) {
8704 /* "while false; do...done" - exitcode 0 */
8705 G.last_exitcode = rcode = EXIT_SUCCESS;
8706 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008707 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008708 }
8709 }
8710 if (rword == RES_UNTIL) {
8711 if (!rcode) {
8712 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008713 break;
8714 }
8715 }
8716 }
8717#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008718 } /* for (pi) */
8719
8720#if ENABLE_HUSH_JOB
8721 G.run_list_level--;
8722#endif
8723#if ENABLE_HUSH_LOOPS
8724 if (loop_top)
8725 G.depth_of_loop--;
8726 free(for_list);
8727#endif
8728#if ENABLE_HUSH_CASE
8729 free(case_word);
8730#endif
8731 debug_leave();
8732 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8733 return rcode;
8734}
8735
8736/* Select which version we will use */
8737static int run_and_free_list(struct pipe *pi)
8738{
8739 int rcode = 0;
8740 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008741 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008742 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8743 rcode = run_list(pi);
8744 }
8745 /* free_pipe_list has the side effect of clearing memory.
8746 * In the long run that function can be merged with run_list,
8747 * but doing that now would hobble the debugging effort. */
8748 free_pipe_list(pi);
8749 debug_printf_exec("run_and_free_list return %d\n", rcode);
8750 return rcode;
8751}
8752
8753
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008754static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008755{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008756 sighandler_t old_handler;
8757 unsigned sig = 0;
8758 while ((mask >>= 1) != 0) {
8759 sig++;
8760 if (!(mask & 1))
8761 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008762 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008763 /* POSIX allows shell to re-enable SIGCHLD
8764 * even if it was SIG_IGN on entry.
8765 * Therefore we skip IGN check for it:
8766 */
8767 if (sig == SIGCHLD)
8768 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02008769 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8770 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8771 */
8772 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008773 if (old_handler == SIG_IGN) {
8774 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008775 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008776#if ENABLE_HUSH_TRAP
8777 if (!G_traps)
8778 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8779 free(G_traps[sig]);
8780 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8781#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008782 }
8783 }
8784}
8785
8786/* Called a few times only (or even once if "sh -c") */
8787static void install_special_sighandlers(void)
8788{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008789 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008790
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008791 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008792 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008793 if (G_interactive_fd) {
8794 mask |= SPECIAL_INTERACTIVE_SIGS;
8795 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008796 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008797 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008798 /* Careful, do not re-install handlers we already installed */
8799 if (G.special_sig_mask != mask) {
8800 unsigned diff = mask & ~G.special_sig_mask;
8801 G.special_sig_mask = mask;
8802 install_sighandlers(diff);
8803 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008804}
8805
8806#if ENABLE_HUSH_JOB
8807/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008808/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008809static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008810{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008811 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008812
8813 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008814 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008815 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8816 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008817 + (1 << SIGBUS ) * HUSH_DEBUG
8818 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008819 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008820 + (1 << SIGABRT)
8821 /* bash 3.2 seems to handle these just like 'fatal' ones */
8822 + (1 << SIGPIPE)
8823 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008824 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008825 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008826 * we never want to restore pgrp on exit, and this fn is not called
8827 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008828 /*+ (1 << SIGHUP )*/
8829 /*+ (1 << SIGTERM)*/
8830 /*+ (1 << SIGINT )*/
8831 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008832 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008833
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008834 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008835}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00008836#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00008837
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008838static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00008839{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008840 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008841 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008842 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008843 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008844 break;
8845 case 'x':
8846 IF_HUSH_MODE_X(G_x_mode = state;)
8847 break;
8848 case 'o':
8849 if (!o_opt) {
8850 /* "set -+o" without parameter.
8851 * in bash, set -o produces this output:
8852 * pipefail off
8853 * and set +o:
8854 * set +o pipefail
8855 * We always use the second form.
8856 */
8857 const char *p = o_opt_strings;
8858 idx = 0;
8859 while (*p) {
8860 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8861 idx++;
8862 p += strlen(p) + 1;
8863 }
8864 break;
8865 }
8866 idx = index_in_strings(o_opt_strings, o_opt);
8867 if (idx >= 0) {
8868 G.o_opt[idx] = state;
8869 break;
8870 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008871 case 'e':
8872 G.o_opt[OPT_O_ERREXIT] = state;
8873 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008874 default:
8875 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008876 }
8877 return EXIT_SUCCESS;
8878}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008879
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00008880int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00008881int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00008882{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008883 enum {
8884 OPT_login = (1 << 0),
8885 };
8886 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00008887 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008888 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008889 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008890 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008891 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00008892
Denis Vlasenko574f2f42008-02-27 18:41:59 +00008893 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02008894 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008895 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008896
Denys Vlasenko10c01312011-05-11 11:49:21 +02008897#if ENABLE_HUSH_FAST
8898 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8899#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008900#if !BB_MMU
8901 G.argv0_for_re_execing = argv[0];
8902#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008903 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008904 shell_ver = xzalloc(sizeof(*shell_ver));
8905 shell_ver->flg_export = 1;
8906 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02008907 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02008908 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008909 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02008910 /* Create shell local variables from the values
8911 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00008912 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008913 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008914 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008915 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008916 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008917 if (e) while (*e) {
8918 char *value = strchr(*e, '=');
8919 if (value) { /* paranoia */
8920 cur_var->next = xzalloc(sizeof(*cur_var));
8921 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008922 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008923 cur_var->max_len = strlen(*e);
8924 cur_var->flg_export = 1;
8925 }
8926 e++;
8927 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008928 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008929 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8930 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008931
8932 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008933 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008934
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01008935#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008936 /* Set (but not export) HOSTNAME unless already set */
8937 if (!get_local_var_value("HOSTNAME")) {
8938 struct utsname uts;
8939 uname(&uts);
8940 set_local_var_from_halves("HOSTNAME", uts.nodename);
8941 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008942 /* bash also exports SHLVL and _,
8943 * and sets (but doesn't export) the following variables:
8944 * BASH=/bin/bash
8945 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8946 * BASH_VERSION='3.2.0(1)-release'
8947 * HOSTTYPE=i386
8948 * MACHTYPE=i386-pc-linux-gnu
8949 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008950 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008951 * EUID=<NNNNN>
8952 * UID=<NNNNN>
8953 * GROUPS=()
8954 * LINES=<NNN>
8955 * COLUMNS=<NNN>
8956 * BASH_ARGC=()
8957 * BASH_ARGV=()
8958 * BASH_LINENO=()
8959 * BASH_SOURCE=()
8960 * DIRSTACK=()
8961 * PIPESTATUS=([0]="0")
8962 * HISTFILE=/<xxx>/.bash_history
8963 * HISTFILESIZE=500
8964 * HISTSIZE=500
8965 * MAILCHECK=60
8966 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8967 * SHELL=/bin/bash
8968 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8969 * TERM=dumb
8970 * OPTERR=1
8971 * OPTIND=1
8972 * IFS=$' \t\n'
8973 * PS1='\s-\v\$ '
8974 * PS2='> '
8975 * PS4='+ '
8976 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008977#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008978
Denis Vlasenko38f63192007-01-22 09:03:07 +00008979#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008980 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008981#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008982
Eric Andersen94ac2442001-05-22 19:05:18 +00008983 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008984 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008985
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008986 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008987
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008988 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008989 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008990 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008991 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008992 * in order to intercept (more) signals.
8993 */
8994
8995 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008996 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008997 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008998 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008999 while (1) {
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009000 opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009001#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009002 "<:$:R:V:"
9003# if ENABLE_HUSH_FUNCTIONS
9004 "F:"
9005# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009006#endif
9007 );
9008 if (opt <= 0)
9009 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009010 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009011 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009012 /* Possibilities:
9013 * sh ... -c 'script'
9014 * sh ... -c 'script' ARG0 [ARG1...]
9015 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009016 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009017 * "" needs to be replaced with NULL
9018 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009019 * Note: the form without ARG0 never happens:
9020 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009021 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009022 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009023 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009024 G.root_ppid = getppid();
9025 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009026 G.global_argv = argv + optind;
9027 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009028 if (builtin_argc) {
9029 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9030 const struct built_in_command *x;
9031
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009032 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009033 x = find_builtin(optarg);
9034 if (x) { /* paranoia */
9035 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9036 G.global_argv += builtin_argc;
9037 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009038 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009039 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009040 }
9041 goto final_return;
9042 }
9043 if (!G.global_argv[0]) {
9044 /* -c 'script' (no params): prevent empty $0 */
9045 G.global_argv--; /* points to argv[i] of 'script' */
9046 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009047 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009048 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009049 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009050 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009051 goto final_return;
9052 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009053 /* Well, we cannot just declare interactiveness,
9054 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009055 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009056 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009057 case 's':
9058 /* "-s" means "read from stdin", but this is how we always
9059 * operate, so simply do nothing here. */
9060 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009061 case 'l':
9062 flags |= OPT_login;
9063 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009064#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009065 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009066 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009067 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009068 case '$': {
9069 unsigned long long empty_trap_mask;
9070
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009071 G.root_pid = bb_strtou(optarg, &optarg, 16);
9072 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009073 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9074 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009075 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9076 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009077 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009078 optarg++;
9079 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009080 optarg++;
9081 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9082 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009083 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009084 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009085# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009086 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009087 for (sig = 1; sig < NSIG; sig++) {
9088 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009089 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009090 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009091 }
9092 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009093# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009094 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009095# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009096 optarg++;
9097 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009098# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009099 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009100 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009101 case 'R':
9102 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009103 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009104 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009105# if ENABLE_HUSH_FUNCTIONS
9106 case 'F': {
9107 struct function *funcp = new_function(optarg);
9108 /* funcp->name is already set to optarg */
9109 /* funcp->body is set to NULL. It's a special case. */
9110 funcp->body_as_string = argv[optind];
9111 optind++;
9112 break;
9113 }
9114# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009115#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009116 case 'n':
9117 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009118 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009119 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009120 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009121 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009122#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009123 fprintf(stderr, "Usage: sh [FILE]...\n"
9124 " or: sh -c command [args]...\n\n");
9125 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009126#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009127 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009128#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009129 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009130 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009131
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009132 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9133 G.global_argc = argc - (optind - 1);
9134 G.global_argv = argv + (optind - 1);
9135 G.global_argv[0] = argv[0];
9136
Denys Vlasenkodea47882009-10-09 15:40:49 +02009137 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009138 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009139 G.root_ppid = getppid();
9140 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009141
9142 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009143 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009144 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009145 debug_printf("sourcing /etc/profile\n");
9146 input = fopen_for_read("/etc/profile");
9147 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009148 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009149 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009150 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009151 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009152 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009153 /* bash: after sourcing /etc/profile,
9154 * tries to source (in the given order):
9155 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009156 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009157 * bash also sources ~/.bash_logout on exit.
9158 * If called as sh, skips .bash_XXX files.
9159 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009160 }
9161
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009162 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009163 FILE *input;
9164 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009165 * "bash <script>" (which is never interactive (unless -i?))
9166 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009167 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009168 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009169 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009170 G.global_argc--;
9171 G.global_argv++;
9172 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009173 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009174 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009175 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009176 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009177 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009178 parse_and_run_file(input);
9179#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009180 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009181#endif
9182 goto final_return;
9183 }
9184
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009185 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009186 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009187 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009188
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009189 /* A shell is interactive if the '-i' flag was given,
9190 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009191 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009192 * no arguments remaining or the -s flag given
9193 * standard input is a terminal
9194 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009195 * Refer to Posix.2, the description of the 'sh' utility.
9196 */
9197#if ENABLE_HUSH_JOB
9198 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009199 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9200 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9201 if (G_saved_tty_pgrp < 0)
9202 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009203
9204 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009205 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009206 if (G_interactive_fd < 0) {
9207 /* try to dup to any fd */
9208 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009209 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009210 /* give up */
9211 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009212 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009213 }
9214 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009215// TODO: track & disallow any attempts of user
9216// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009217 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009218 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009219 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009220 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009221
Mike Frysinger38478a62009-05-20 04:48:06 -04009222 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009223 /* If we were run as 'hush &', sleep until we are
9224 * in the foreground (tty pgrp == our pgrp).
9225 * If we get started under a job aware app (like bash),
9226 * make sure we are now in charge so we don't fight over
9227 * who gets the foreground */
9228 while (1) {
9229 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009230 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9231 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009232 break;
9233 /* send TTIN to ourself (should stop us) */
9234 kill(- shell_pgrp, SIGTTIN);
9235 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009236 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009237
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009238 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009239 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009240
Mike Frysinger38478a62009-05-20 04:48:06 -04009241 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009242 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009243 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009244 /* Put ourselves in our own process group
9245 * (bash, too, does this only if ctty is available) */
9246 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9247 /* Grab control of the terminal */
9248 tcsetpgrp(G_interactive_fd, getpid());
9249 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009250 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009251
9252# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9253 {
9254 const char *hp = get_local_var_value("HISTFILE");
9255 if (!hp) {
9256 hp = get_local_var_value("HOME");
9257 if (hp)
9258 hp = concat_path_file(hp, ".hush_history");
9259 } else {
9260 hp = xstrdup(hp);
9261 }
9262 if (hp) {
9263 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009264 //set_local_var(xasprintf("HISTFILE=%s", ...));
9265 }
9266# if ENABLE_FEATURE_SH_HISTFILESIZE
9267 hp = get_local_var_value("HISTFILESIZE");
9268 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9269# endif
9270 }
9271# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009272 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009273 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009274 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009275#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009276 /* No job control compiled in, only prompt/line editing */
9277 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02009278 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009279 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009280 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009281 G_interactive_fd = dup(STDIN_FILENO);
9282 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009283 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009284 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009285 }
9286 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009287 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009288 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009289 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009290 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009291#else
9292 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009293 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009294#endif
9295 /* bash:
9296 * if interactive but not a login shell, sources ~/.bashrc
9297 * (--norc turns this off, --rcfile <file> overrides)
9298 */
9299
9300 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009301 /* note: ash and hush share this string */
9302 printf("\n\n%s %s\n"
9303 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9304 "\n",
9305 bb_banner,
9306 "hush - the humble shell"
9307 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009308 }
9309
Denis Vlasenkof9375282009-04-05 19:13:39 +00009310 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009311
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009312 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009313 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009314}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009315
9316
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009317/*
9318 * Built-ins
9319 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009320static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009321{
9322 return 0;
9323}
9324
Denys Vlasenko265062d2017-01-10 15:13:30 +01009325#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009326static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009327{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009328 int argc = string_array_len(argv);
9329 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009330}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009331#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009332#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009333static int FAST_FUNC builtin_test(char **argv)
9334{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009335 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009336}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009337#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009338#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009339static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009340{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009341 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009342}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009343#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009344#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009345static int FAST_FUNC builtin_printf(char **argv)
9346{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009347 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009348}
9349#endif
9350
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009351#if ENABLE_HUSH_HELP
9352static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9353{
9354 const struct built_in_command *x;
9355
9356 printf(
9357 "Built-in commands:\n"
9358 "------------------\n");
9359 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9360 if (x->b_descr)
9361 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9362 }
9363 return EXIT_SUCCESS;
9364}
9365#endif
9366
9367#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9368static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9369{
9370 show_history(G.line_input_state);
9371 return EXIT_SUCCESS;
9372}
9373#endif
9374
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009375static char **skip_dash_dash(char **argv)
9376{
9377 argv++;
9378 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9379 argv++;
9380 return argv;
9381}
9382
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009383static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009384{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009385 const char *newdir;
9386
9387 argv = skip_dash_dash(argv);
9388 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009389 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009390 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009391 * bash says "bash: cd: HOME not set" and does nothing
9392 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009393 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009394 const char *home = get_local_var_value("HOME");
9395 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009396 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009397 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009398 /* Mimic bash message exactly */
9399 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009400 return EXIT_FAILURE;
9401 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009402 /* Read current dir (get_cwd(1) is inside) and set PWD.
9403 * Note: do not enforce exporting. If PWD was unset or unexported,
9404 * set it again, but do not export. bash does the same.
9405 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009406 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009407 return EXIT_SUCCESS;
9408}
9409
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009410static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9411{
9412 puts(get_cwd(0));
9413 return EXIT_SUCCESS;
9414}
9415
9416static int FAST_FUNC builtin_eval(char **argv)
9417{
9418 int rcode = EXIT_SUCCESS;
9419
9420 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009421 if (argv[0]) {
9422 char *str = NULL;
9423
9424 if (argv[1]) {
9425 /* "The eval utility shall construct a command by
9426 * concatenating arguments together, separating
9427 * each with a <space> character."
9428 */
9429 char *p;
9430 unsigned len = 0;
9431 char **pp = argv;
9432 do
9433 len += strlen(*pp) + 1;
9434 while (*++pp);
9435 str = p = xmalloc(len);
9436 pp = argv;
9437 do {
9438 p = stpcpy(p, *pp);
9439 *p++ = ' ';
9440 } while (*++pp);
9441 p[-1] = '\0';
9442 }
9443
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009444 /* bash:
9445 * eval "echo Hi; done" ("done" is syntax error):
9446 * "echo Hi" will not execute too.
9447 */
Denys Vlasenko1f191122018-01-11 13:17:30 +01009448 parse_and_run_string(str ? str : argv[0]);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009449 free(str);
9450 rcode = G.last_exitcode;
9451 }
9452 return rcode;
9453}
9454
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009455static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009456{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009457 argv = skip_dash_dash(argv);
9458 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009459 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009460
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009461 /* Careful: we can end up here after [v]fork. Do not restore
9462 * tty pgrp then, only top-level shell process does that */
9463 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9464 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9465
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009466 /* Saved-redirect fds, script fds and G_interactive_fd are still
9467 * open here. However, they are all CLOEXEC, and execv below
9468 * closes them. Try interactive "exec ls -l /proc/self/fd",
9469 * it should show no extra open fds in the "ls" process.
9470 * If we'd try to run builtins/NOEXECs, this would need improving.
9471 */
9472 //close_saved_fds_and_FILE_fds();
9473
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009474 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009475 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009476 * and tcsetpgrp, and this is inherently racy.
9477 */
9478 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009479}
9480
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009481static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009482{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009483 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009484
9485 /* interactive bash:
9486 * # trap "echo EEE" EXIT
9487 * # exit
9488 * exit
9489 * There are stopped jobs.
9490 * (if there are _stopped_ jobs, running ones don't count)
9491 * # exit
9492 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009493 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009494 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009495 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009496 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009497
9498 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009499 argv = skip_dash_dash(argv);
9500 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009501 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009502 /* mimic bash: exit 123abc == exit 255 + error msg */
9503 xfunc_error_retval = 255;
9504 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009505 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009506}
9507
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009508#if ENABLE_HUSH_TYPE
9509/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9510static int FAST_FUNC builtin_type(char **argv)
9511{
9512 int ret = EXIT_SUCCESS;
9513
9514 while (*++argv) {
9515 const char *type;
9516 char *path = NULL;
9517
9518 if (0) {} /* make conditional compile easier below */
9519 /*else if (find_alias(*argv))
9520 type = "an alias";*/
9521#if ENABLE_HUSH_FUNCTIONS
9522 else if (find_function(*argv))
9523 type = "a function";
9524#endif
9525 else if (find_builtin(*argv))
9526 type = "a shell builtin";
9527 else if ((path = find_in_path(*argv)) != NULL)
9528 type = path;
9529 else {
9530 bb_error_msg("type: %s: not found", *argv);
9531 ret = EXIT_FAILURE;
9532 continue;
9533 }
9534
9535 printf("%s is %s\n", *argv, type);
9536 free(path);
9537 }
9538
9539 return ret;
9540}
9541#endif
9542
9543#if ENABLE_HUSH_READ
9544/* Interruptibility of read builtin in bash
9545 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9546 *
9547 * Empty trap makes read ignore corresponding signal, for any signal.
9548 *
9549 * SIGINT:
9550 * - terminates non-interactive shell;
9551 * - interrupts read in interactive shell;
9552 * if it has non-empty trap:
9553 * - executes trap and returns to command prompt in interactive shell;
9554 * - executes trap and returns to read in non-interactive shell;
9555 * SIGTERM:
9556 * - is ignored (does not interrupt) read in interactive shell;
9557 * - terminates non-interactive shell;
9558 * if it has non-empty trap:
9559 * - executes trap and returns to read;
9560 * SIGHUP:
9561 * - terminates shell (regardless of interactivity);
9562 * if it has non-empty trap:
9563 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009564 * SIGCHLD from children:
9565 * - does not interrupt read regardless of interactivity:
9566 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009567 */
9568static int FAST_FUNC builtin_read(char **argv)
9569{
9570 const char *r;
9571 char *opt_n = NULL;
9572 char *opt_p = NULL;
9573 char *opt_t = NULL;
9574 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009575 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009576 const char *ifs;
9577 int read_flags;
9578
9579 /* "!": do not abort on errors.
9580 * Option string must start with "sr" to match BUILTIN_READ_xxx
9581 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009582 read_flags = getopt32(argv,
9583#if BASH_READ_D
9584 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9585#else
9586 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9587#endif
9588 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009589 if (read_flags == (uint32_t)-1)
9590 return EXIT_FAILURE;
9591 argv += optind;
9592 ifs = get_local_var_value("IFS"); /* can be NULL */
9593
9594 again:
9595 r = shell_builtin_read(set_local_var_from_halves,
9596 argv,
9597 ifs,
9598 read_flags,
9599 opt_n,
9600 opt_p,
9601 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009602 opt_u,
9603 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009604 );
9605
9606 if ((uintptr_t)r == 1 && errno == EINTR) {
9607 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009608 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009609 goto again;
9610 }
9611
9612 if ((uintptr_t)r > 1) {
9613 bb_error_msg("%s", r);
9614 r = (char*)(uintptr_t)1;
9615 }
9616
9617 return (uintptr_t)r;
9618}
9619#endif
9620
9621#if ENABLE_HUSH_UMASK
9622static int FAST_FUNC builtin_umask(char **argv)
9623{
9624 int rc;
9625 mode_t mask;
9626
9627 rc = 1;
9628 mask = umask(0);
9629 argv = skip_dash_dash(argv);
9630 if (argv[0]) {
9631 mode_t old_mask = mask;
9632
9633 /* numeric umasks are taken as-is */
9634 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9635 if (!isdigit(argv[0][0]))
9636 mask ^= 0777;
9637 mask = bb_parse_mode(argv[0], mask);
9638 if (!isdigit(argv[0][0]))
9639 mask ^= 0777;
9640 if ((unsigned)mask > 0777) {
9641 mask = old_mask;
9642 /* bash messages:
9643 * bash: umask: 'q': invalid symbolic mode operator
9644 * bash: umask: 999: octal number out of range
9645 */
9646 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9647 rc = 0;
9648 }
9649 } else {
9650 /* Mimic bash */
9651 printf("%04o\n", (unsigned) mask);
9652 /* fall through and restore mask which we set to 0 */
9653 }
9654 umask(mask);
9655
9656 return !rc; /* rc != 0 - success */
9657}
9658#endif
9659
Denys Vlasenko41ade052017-01-08 18:56:24 +01009660#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009661static void print_escaped(const char *s)
9662{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009663 if (*s == '\'')
9664 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009665 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009666 const char *p = strchrnul(s, '\'');
9667 /* print 'xxxx', possibly just '' */
9668 printf("'%.*s'", (int)(p - s), s);
9669 if (*p == '\0')
9670 break;
9671 s = p;
9672 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009673 /* s points to '; print "'''...'''" */
9674 putchar('"');
9675 do putchar('\''); while (*++s == '\'');
9676 putchar('"');
9677 } while (*s);
9678}
Denys Vlasenko41ade052017-01-08 18:56:24 +01009679#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009680
Denys Vlasenko1e660422017-07-17 21:10:50 +02009681#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009682static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009683{
9684 do {
9685 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009686 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02009687
9688 /* So far we do not check that name is valid (TODO?) */
9689
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009690 if (*name_end == '\0') {
9691 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009692
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009693 vpp = get_ptr_to_local_var(name, name_end - name);
9694 var = vpp ? *vpp : NULL;
9695
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009696 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009697 /* export -n NAME (without =VALUE) */
9698 if (var) {
9699 var->flg_export = 0;
9700 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9701 unsetenv(name);
9702 } /* else: export -n NOT_EXISTING_VAR: no-op */
9703 continue;
9704 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009705 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009706 /* export NAME (without =VALUE) */
9707 if (var) {
9708 var->flg_export = 1;
9709 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9710 putenv(var->varstr);
9711 continue;
9712 }
9713 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009714 if (flags & SETFLAG_MAKE_RO) {
9715 /* readonly NAME (without =VALUE) */
9716 if (var) {
9717 var->flg_read_only = 1;
9718 continue;
9719 }
9720 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009721# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009722 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009723 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9724 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009725 if (var && var->func_nest_level == lvl) {
9726 /* "local x=abc; ...; local x" - ignore second local decl */
9727 continue;
9728 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02009729 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009730# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009731 /* Exporting non-existing variable.
9732 * bash does not put it in environment,
9733 * but remembers that it is exported,
9734 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +02009735 * We just set it to "" and export.
9736 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009737 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +02009738 * bash sets the value to "".
9739 */
9740 /* Or, it's "readonly NAME" (without =VALUE).
9741 * bash remembers NAME and disallows its creation
9742 * in the future.
9743 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009744 name = xasprintf("%s=", name);
9745 } else {
9746 /* (Un)exporting/making local NAME=VALUE */
9747 name = xstrdup(name);
9748 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009749 if (set_local_var(name, flags))
9750 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009751 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +02009752 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009753}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009754#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009755
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009756#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009757static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009758{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00009759 unsigned opt_unexport;
9760
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02009761#if ENABLE_HUSH_EXPORT_N
9762 /* "!": do not abort on errors */
9763 opt_unexport = getopt32(argv, "!n");
9764 if (opt_unexport == (uint32_t)-1)
9765 return EXIT_FAILURE;
9766 argv += optind;
9767#else
9768 opt_unexport = 0;
9769 argv++;
9770#endif
9771
9772 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009773 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009774 if (e) {
9775 while (*e) {
9776#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009777 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009778#else
9779 /* ash emits: export VAR='VAL'
9780 * bash: declare -x VAR="VAL"
9781 * we follow ash example */
9782 const char *s = *e++;
9783 const char *p = strchr(s, '=');
9784
9785 if (!p) /* wtf? take next variable */
9786 continue;
9787 /* export var= */
9788 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009789 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009790 putchar('\n');
9791#endif
9792 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009793 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009794 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009795 return EXIT_SUCCESS;
9796 }
9797
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009798 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009799}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009800#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009801
Denys Vlasenko295fef82009-06-03 12:47:26 +02009802#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009803static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009804{
9805 if (G.func_nest_level == 0) {
9806 bb_error_msg("%s: not in a function", argv[0]);
9807 return EXIT_FAILURE; /* bash compat */
9808 }
Denys Vlasenko1e660422017-07-17 21:10:50 +02009809 argv++;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009810 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +02009811}
9812#endif
9813
Denys Vlasenko1e660422017-07-17 21:10:50 +02009814#if ENABLE_HUSH_READONLY
9815static int FAST_FUNC builtin_readonly(char **argv)
9816{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009817 argv++;
9818 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +02009819 /* bash: readonly [-p]: list all readonly VARs
9820 * (-p has no effect in bash)
9821 */
9822 struct variable *e;
9823 for (e = G.top_var; e; e = e->next) {
9824 if (e->flg_read_only) {
9825//TODO: quote value: readonly VAR='VAL'
9826 printf("readonly %s\n", e->varstr);
9827 }
9828 }
9829 return EXIT_SUCCESS;
9830 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009831 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +02009832}
9833#endif
9834
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009835#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009836/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9837static int FAST_FUNC builtin_unset(char **argv)
9838{
9839 int ret;
9840 unsigned opts;
9841
9842 /* "!": do not abort on errors */
9843 /* "+": stop at 1st non-option */
9844 opts = getopt32(argv, "!+vf");
9845 if (opts == (unsigned)-1)
9846 return EXIT_FAILURE;
9847 if (opts == 3) {
9848 bb_error_msg("unset: -v and -f are exclusive");
9849 return EXIT_FAILURE;
9850 }
9851 argv += optind;
9852
9853 ret = EXIT_SUCCESS;
9854 while (*argv) {
9855 if (!(opts & 2)) { /* not -f */
9856 if (unset_local_var(*argv)) {
9857 /* unset <nonexistent_var> doesn't fail.
9858 * Error is when one tries to unset RO var.
9859 * Message was printed by unset_local_var. */
9860 ret = EXIT_FAILURE;
9861 }
9862 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009863# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +02009864 else {
9865 unset_func(*argv);
9866 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009867# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009868 argv++;
9869 }
9870 return ret;
9871}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009872#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009873
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009874#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009875/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9876 * built-in 'set' handler
9877 * SUSv3 says:
9878 * set [-abCefhmnuvx] [-o option] [argument...]
9879 * set [+abCefhmnuvx] [+o option] [argument...]
9880 * set -- [argument...]
9881 * set -o
9882 * set +o
9883 * Implementations shall support the options in both their hyphen and
9884 * plus-sign forms. These options can also be specified as options to sh.
9885 * Examples:
9886 * Write out all variables and their values: set
9887 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9888 * Turn on the -x and -v options: set -xv
9889 * Unset all positional parameters: set --
9890 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9891 * Set the positional parameters to the expansion of x, even if x expands
9892 * with a leading '-' or '+': set -- $x
9893 *
9894 * So far, we only support "set -- [argument...]" and some of the short names.
9895 */
9896static int FAST_FUNC builtin_set(char **argv)
9897{
9898 int n;
9899 char **pp, **g_argv;
9900 char *arg = *++argv;
9901
9902 if (arg == NULL) {
9903 struct variable *e;
9904 for (e = G.top_var; e; e = e->next)
9905 puts(e->varstr);
9906 return EXIT_SUCCESS;
9907 }
9908
9909 do {
9910 if (strcmp(arg, "--") == 0) {
9911 ++argv;
9912 goto set_argv;
9913 }
9914 if (arg[0] != '+' && arg[0] != '-')
9915 break;
9916 for (n = 1; arg[n]; ++n) {
9917 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9918 goto error;
9919 if (arg[n] == 'o' && argv[1])
9920 argv++;
9921 }
9922 } while ((arg = *++argv) != NULL);
9923 /* Now argv[0] is 1st argument */
9924
9925 if (arg == NULL)
9926 return EXIT_SUCCESS;
9927 set_argv:
9928
9929 /* NB: G.global_argv[0] ($0) is never freed/changed */
9930 g_argv = G.global_argv;
9931 if (G.global_args_malloced) {
9932 pp = g_argv;
9933 while (*++pp)
9934 free(*pp);
9935 g_argv[1] = NULL;
9936 } else {
9937 G.global_args_malloced = 1;
9938 pp = xzalloc(sizeof(pp[0]) * 2);
9939 pp[0] = g_argv[0]; /* retain $0 */
9940 g_argv = pp;
9941 }
9942 /* This realloc's G.global_argv */
9943 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9944
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009945 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +02009946
9947 return EXIT_SUCCESS;
9948
9949 /* Nothing known, so abort */
9950 error:
Denys Vlasenko57000292018-01-12 14:41:45 +01009951 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +02009952 return EXIT_FAILURE;
9953}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009954#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009955
9956static int FAST_FUNC builtin_shift(char **argv)
9957{
9958 int n = 1;
9959 argv = skip_dash_dash(argv);
9960 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +02009961 n = bb_strtou(argv[0], NULL, 10);
9962 if (errno || n < 0) {
9963 /* shared string with ash.c */
9964 bb_error_msg("Illegal number: %s", argv[0]);
9965 /*
9966 * ash aborts in this case.
9967 * bash prints error message and set $? to 1.
9968 * Interestingly, for "shift 99999" bash does not
9969 * print error message, but does set $? to 1
9970 * (and does no shifting at all).
9971 */
9972 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02009973 }
9974 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01009975 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +02009976 int m = 1;
9977 while (m <= n)
9978 free(G.global_argv[m++]);
9979 }
9980 G.global_argc -= n;
9981 memmove(&G.global_argv[1], &G.global_argv[n+1],
9982 G.global_argc * sizeof(G.global_argv[0]));
9983 return EXIT_SUCCESS;
9984 }
9985 return EXIT_FAILURE;
9986}
9987
Denys Vlasenko74d40582017-08-11 01:32:46 +02009988#if ENABLE_HUSH_GETOPTS
9989static int FAST_FUNC builtin_getopts(char **argv)
9990{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +02009991/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
9992
Denys Vlasenko74d40582017-08-11 01:32:46 +02009993TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +02009994If a required argument is not found, and getopts is not silent,
9995a question mark (?) is placed in VAR, OPTARG is unset, and a
9996diagnostic message is printed. If getopts is silent, then a
9997colon (:) is placed in VAR and OPTARG is set to the option
9998character found.
9999
10000Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010001
10002"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010003*/
10004 char cbuf[2];
10005 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010006 int c, n, exitcode, my_opterr;
10007 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010008
10009 optstring = *++argv;
10010 if (!optstring || !(var = *++argv)) {
10011 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10012 return EXIT_FAILURE;
10013 }
10014
Denys Vlasenko238ff982017-08-29 13:38:30 +020010015 if (argv[1])
10016 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10017 else
10018 argv = G.global_argv;
10019 cbuf[1] = '\0';
10020
10021 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010022 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010023 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010024 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010025 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010026 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010027
10028 /* getopts stops on first non-option. Add "+" to force that */
10029 /*if (optstring[0] != '+')*/ {
10030 char *s = alloca(strlen(optstring) + 2);
10031 sprintf(s, "+%s", optstring);
10032 optstring = s;
10033 }
10034
Denys Vlasenko238ff982017-08-29 13:38:30 +020010035 /* Naively, now we should just
10036 * cp = get_local_var_value("OPTIND");
10037 * optind = cp ? atoi(cp) : 0;
10038 * optarg = NULL;
10039 * opterr = my_opterr;
10040 * c = getopt(string_array_len(argv), argv, optstring);
10041 * and be done? Not so fast...
10042 * Unlike normal getopt() usage in C programs, here
10043 * each successive call will (usually) have the same argv[] CONTENTS,
10044 * but not the ADDRESSES. Worse yet, it's possible that between
10045 * invocations of "getopts", there will be calls to shell builtins
10046 * which use getopt() internally. Example:
10047 * while getopts "abc" RES -a -bc -abc de; do
10048 * unset -ff func
10049 * done
10050 * This would not work correctly: getopt() call inside "unset"
10051 * modifies internal libc state which is tracking position in
10052 * multi-option strings ("-abc"). At best, it can skip options
10053 * or return the same option infinitely. With glibc implementation
10054 * of getopt(), it would use outright invalid pointers and return
10055 * garbage even _without_ "unset" mangling internal state.
10056 *
10057 * We resort to resetting getopt() state and calling it N times,
10058 * until we get Nth result (or failure).
10059 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10060 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010061 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010062 count = 0;
10063 n = string_array_len(argv);
10064 do {
10065 optarg = NULL;
10066 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10067 c = getopt(n, argv, optstring);
10068 if (c < 0)
10069 break;
10070 count++;
10071 } while (count <= G.getopt_count);
10072
10073 /* Set OPTIND. Prevent resetting of the magic counter! */
10074 set_local_var_from_halves("OPTIND", utoa(optind));
10075 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010076 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010077
10078 /* Set OPTARG */
10079 /* Always set or unset, never left as-is, even on exit/error:
10080 * "If no option was found, or if the option that was found
10081 * does not have an option-argument, OPTARG shall be unset."
10082 */
10083 cp = optarg;
10084 if (c == '?') {
10085 /* If ":optstring" and unknown option is seen,
10086 * it is stored to OPTARG.
10087 */
10088 if (optstring[1] == ':') {
10089 cbuf[0] = optopt;
10090 cp = cbuf;
10091 }
10092 }
10093 if (cp)
10094 set_local_var_from_halves("OPTARG", cp);
10095 else
10096 unset_local_var("OPTARG");
10097
10098 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010099 exitcode = EXIT_SUCCESS;
10100 if (c < 0) { /* -1: end of options */
10101 exitcode = EXIT_FAILURE;
10102 c = '?';
10103 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010104
Denys Vlasenko238ff982017-08-29 13:38:30 +020010105 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010106 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010107 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010108
Denys Vlasenko74d40582017-08-11 01:32:46 +020010109 return exitcode;
10110}
10111#endif
10112
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010113static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010114{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010115 char *arg_path, *filename;
10116 FILE *input;
10117 save_arg_t sv;
10118 char *args_need_save;
10119#if ENABLE_HUSH_FUNCTIONS
10120 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010121#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010122
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010123 argv = skip_dash_dash(argv);
10124 filename = argv[0];
10125 if (!filename) {
10126 /* bash says: "bash: .: filename argument required" */
10127 return 2; /* bash compat */
10128 }
10129 arg_path = NULL;
10130 if (!strchr(filename, '/')) {
10131 arg_path = find_in_path(filename);
10132 if (arg_path)
10133 filename = arg_path;
10134 }
10135 input = remember_FILE(fopen_or_warn(filename, "r"));
10136 free(arg_path);
10137 if (!input) {
10138 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10139 /* POSIX: non-interactive shell should abort here,
10140 * not merely fail. So far no one complained :)
10141 */
10142 return EXIT_FAILURE;
10143 }
10144
10145#if ENABLE_HUSH_FUNCTIONS
10146 sv_flg = G_flag_return_in_progress;
10147 /* "we are inside sourced file, ok to use return" */
10148 G_flag_return_in_progress = -1;
10149#endif
10150 args_need_save = argv[1]; /* used as a boolean variable */
10151 if (args_need_save)
10152 save_and_replace_G_args(&sv, argv);
10153
10154 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10155 G.last_exitcode = 0;
10156 parse_and_run_file(input);
10157 fclose_and_forget(input);
10158
10159 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10160 restore_G_args(&sv, argv);
10161#if ENABLE_HUSH_FUNCTIONS
10162 G_flag_return_in_progress = sv_flg;
10163#endif
10164
10165 return G.last_exitcode;
10166}
10167
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010168#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010169static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010170{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010171 int sig;
10172 char *new_cmd;
10173
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010174 if (!G_traps)
10175 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010176
10177 argv++;
10178 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010179 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010180 /* No args: print all trapped */
10181 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010182 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010183 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010184 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010185 /* note: bash adds "SIG", but only if invoked
10186 * as "bash". If called as "sh", or if set -o posix,
10187 * then it prints short signal names.
10188 * We are printing short names: */
10189 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010190 }
10191 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010192 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010193 return EXIT_SUCCESS;
10194 }
10195
10196 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010197 /* If first arg is a number: reset all specified signals */
10198 sig = bb_strtou(*argv, NULL, 10);
10199 if (errno == 0) {
10200 int ret;
10201 process_sig_list:
10202 ret = EXIT_SUCCESS;
10203 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010204 sighandler_t handler;
10205
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010206 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010207 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010208 ret = EXIT_FAILURE;
10209 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010210 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010211 continue;
10212 }
10213
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010214 free(G_traps[sig]);
10215 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010216
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010217 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010218 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010219
10220 /* There is no signal for 0 (EXIT) */
10221 if (sig == 0)
10222 continue;
10223
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010224 if (new_cmd)
10225 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10226 else
10227 /* We are removing trap handler */
10228 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010229 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010230 }
10231 return ret;
10232 }
10233
10234 if (!argv[1]) { /* no second arg */
10235 bb_error_msg("trap: invalid arguments");
10236 return EXIT_FAILURE;
10237 }
10238
10239 /* First arg is "-": reset all specified to default */
10240 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10241 /* Everything else: set arg as signal handler
10242 * (includes "" case, which ignores signal) */
10243 if (argv[0][0] == '-') {
10244 if (argv[0][1] == '\0') { /* "-" */
10245 /* new_cmd remains NULL: "reset these sigs" */
10246 goto reset_traps;
10247 }
10248 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10249 argv++;
10250 }
10251 /* else: "-something", no special meaning */
10252 }
10253 new_cmd = *argv;
10254 reset_traps:
10255 argv++;
10256 goto process_sig_list;
10257}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010258#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010259
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010260#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010261static struct pipe *parse_jobspec(const char *str)
10262{
10263 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010264 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010265
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010266 if (sscanf(str, "%%%u", &jobnum) != 1) {
10267 if (str[0] != '%'
10268 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10269 ) {
10270 bb_error_msg("bad argument '%s'", str);
10271 return NULL;
10272 }
10273 /* It is "%%", "%+" or "%" - current job */
10274 jobnum = G.last_jobid;
10275 if (jobnum == 0) {
10276 bb_error_msg("no current job");
10277 return NULL;
10278 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010279 }
10280 for (pi = G.job_list; pi; pi = pi->next) {
10281 if (pi->jobid == jobnum) {
10282 return pi;
10283 }
10284 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010285 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010286 return NULL;
10287}
10288
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010289static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10290{
10291 struct pipe *job;
10292 const char *status_string;
10293
10294 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10295 for (job = G.job_list; job; job = job->next) {
10296 if (job->alive_cmds == job->stopped_cmds)
10297 status_string = "Stopped";
10298 else
10299 status_string = "Running";
10300
10301 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10302 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010303
10304 clean_up_last_dead_job();
10305
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010306 return EXIT_SUCCESS;
10307}
10308
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010309/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010310static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010311{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010312 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010313 struct pipe *pi;
10314
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010315 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010316 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010317
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010318 /* If they gave us no args, assume they want the last backgrounded task */
10319 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010320 for (pi = G.job_list; pi; pi = pi->next) {
10321 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010322 goto found;
10323 }
10324 }
10325 bb_error_msg("%s: no current job", argv[0]);
10326 return EXIT_FAILURE;
10327 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010328
10329 pi = parse_jobspec(argv[1]);
10330 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010331 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010332 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010333 /* TODO: bash prints a string representation
10334 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010335 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010336 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010337 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010338 }
10339
10340 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010341 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10342 for (i = 0; i < pi->num_cmds; i++) {
10343 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010344 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010345 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010346
10347 i = kill(- pi->pgrp, SIGCONT);
10348 if (i < 0) {
10349 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010350 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010351 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010352 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010353 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010354 }
10355
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010356 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010357 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010358 return checkjobs_and_fg_shell(pi);
10359 }
10360 return EXIT_SUCCESS;
10361}
10362#endif
10363
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010364#if ENABLE_HUSH_KILL
10365static int FAST_FUNC builtin_kill(char **argv)
10366{
10367 int ret = 0;
10368
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010369# if ENABLE_HUSH_JOB
10370 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10371 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010372
10373 do {
10374 struct pipe *pi;
10375 char *dst;
10376 int j, n;
10377
10378 if (argv[i][0] != '%')
10379 continue;
10380 /*
10381 * "kill %N" - job kill
10382 * Converting to pgrp / pid kill
10383 */
10384 pi = parse_jobspec(argv[i]);
10385 if (!pi) {
10386 /* Eat bad jobspec */
10387 j = i;
10388 do {
10389 j++;
10390 argv[j - 1] = argv[j];
10391 } while (argv[j]);
10392 ret = 1;
10393 i--;
10394 continue;
10395 }
10396 /*
10397 * In jobs started under job control, we signal
10398 * entire process group by kill -PGRP_ID.
10399 * This happens, f.e., in interactive shell.
10400 *
10401 * Otherwise, we signal each child via
10402 * kill PID1 PID2 PID3.
10403 * Testcases:
10404 * sh -c 'sleep 1|sleep 1 & kill %1'
10405 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10406 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10407 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010408 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010409 dst = alloca(n * sizeof(int)*4);
10410 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010411 if (G_interactive_fd)
10412 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010413 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010414 struct command *cmd = &pi->cmds[j];
10415 /* Skip exited members of the job */
10416 if (cmd->pid == 0)
10417 continue;
10418 /*
10419 * kill_main has matching code to expect
10420 * leading space. Needed to not confuse
10421 * negative pids with "kill -SIGNAL_NO" syntax
10422 */
10423 dst += sprintf(dst, " %u", (int)cmd->pid);
10424 }
10425 *dst = '\0';
10426 } while (argv[++i]);
10427 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010428# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010429
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010430 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010431 ret = run_applet_main(argv, kill_main);
10432 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010433 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010434 return ret;
10435}
10436#endif
10437
10438#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010439/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010440#if !ENABLE_HUSH_JOB
10441# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10442#endif
10443static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010444{
10445 int ret = 0;
10446 for (;;) {
10447 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010448 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010449
Denys Vlasenko830ea352016-11-08 04:59:11 +010010450 if (!sigisemptyset(&G.pending_set))
10451 goto check_sig;
10452
Denys Vlasenko7e675362016-10-28 21:57:31 +020010453 /* waitpid is not interruptible by SA_RESTARTed
10454 * signals which we use. Thus, this ugly dance:
10455 */
10456
10457 /* Make sure possible SIGCHLD is stored in kernel's
10458 * pending signal mask before we call waitpid.
10459 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010460 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010461 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010462 sigfillset(&oldset); /* block all signals, remember old set */
10463 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010464
10465 if (!sigisemptyset(&G.pending_set)) {
10466 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010467 goto restore;
10468 }
10469
10470 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010471/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010472 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010473 debug_printf_exec("checkjobs:%d\n", ret);
10474#if ENABLE_HUSH_JOB
10475 if (waitfor_pipe) {
10476 int rcode = job_exited_or_stopped(waitfor_pipe);
10477 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10478 if (rcode >= 0) {
10479 ret = rcode;
10480 sigprocmask(SIG_SETMASK, &oldset, NULL);
10481 break;
10482 }
10483 }
10484#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010485 /* if ECHILD, there are no children (ret is -1 or 0) */
10486 /* if ret == 0, no children changed state */
10487 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010488 if (errno == ECHILD || ret) {
10489 ret--;
10490 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010491 ret = 0;
10492 sigprocmask(SIG_SETMASK, &oldset, NULL);
10493 break;
10494 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010495 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010496 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10497 /* Note: sigsuspend invokes signal handler */
10498 sigsuspend(&oldset);
10499 restore:
10500 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010501 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010502 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010503 sig = check_and_run_traps();
10504 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010505 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010506 ret = 128 + sig;
10507 break;
10508 }
10509 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10510 }
10511 return ret;
10512}
10513
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010514static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010515{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010516 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010517 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010518
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010519 argv = skip_dash_dash(argv);
10520 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010521 /* Don't care about wait results */
10522 /* Note 1: must wait until there are no more children */
10523 /* Note 2: must be interruptible */
10524 /* Examples:
10525 * $ sleep 3 & sleep 6 & wait
10526 * [1] 30934 sleep 3
10527 * [2] 30935 sleep 6
10528 * [1] Done sleep 3
10529 * [2] Done sleep 6
10530 * $ sleep 3 & sleep 6 & wait
10531 * [1] 30936 sleep 3
10532 * [2] 30937 sleep 6
10533 * [1] Done sleep 3
10534 * ^C <-- after ~4 sec from keyboard
10535 * $
10536 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010537 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010538 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010539
Denys Vlasenko7e675362016-10-28 21:57:31 +020010540 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010541 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010542 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010543#if ENABLE_HUSH_JOB
10544 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010545 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010546 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010547 wait_pipe = parse_jobspec(*argv);
10548 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010549 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010550 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010551 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010552 } else {
10553 /* waiting on "last dead job" removes it */
10554 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010555 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010556 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010557 /* else: parse_jobspec() already emitted error msg */
10558 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010559 }
10560#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010561 /* mimic bash message */
10562 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010563 ret = EXIT_FAILURE;
10564 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010565 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010566
Denys Vlasenko7e675362016-10-28 21:57:31 +020010567 /* Do we have such child? */
10568 ret = waitpid(pid, &status, WNOHANG);
10569 if (ret < 0) {
10570 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010571 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010572 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010573 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010574 /* "wait $!" but last bg task has already exited. Try:
10575 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10576 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010577 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010578 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010579 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010580 } else {
10581 /* Example: "wait 1". mimic bash message */
10582 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010583 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010584 } else {
10585 /* ??? */
10586 bb_perror_msg("wait %s", *argv);
10587 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010588 continue; /* bash checks all argv[] */
10589 }
10590 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010591 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010592 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010593 } else {
10594 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010595 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010596 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010597 if (WIFSIGNALED(status))
10598 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010599 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010600 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010601
10602 return ret;
10603}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010604#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010605
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010606#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10607static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10608{
10609 if (argv[1]) {
10610 def = bb_strtou(argv[1], NULL, 10);
10611 if (errno || def < def_min || argv[2]) {
10612 bb_error_msg("%s: bad arguments", argv[0]);
10613 def = UINT_MAX;
10614 }
10615 }
10616 return def;
10617}
10618#endif
10619
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010620#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010621static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010622{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010623 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010624 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010625 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010626 /* if we came from builtin_continue(), need to undo "= 1" */
10627 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010628 return EXIT_SUCCESS; /* bash compat */
10629 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010630 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010631
10632 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10633 if (depth == UINT_MAX)
10634 G.flag_break_continue = BC_BREAK;
10635 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010636 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010637
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010638 return EXIT_SUCCESS;
10639}
10640
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010641static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010642{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010643 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10644 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010645}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010646#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010647
10648#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010649static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010650{
10651 int rc;
10652
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010653 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010654 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10655 return EXIT_FAILURE; /* bash compat */
10656 }
10657
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010658 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010659
10660 /* bash:
10661 * out of range: wraps around at 256, does not error out
10662 * non-numeric param:
10663 * f() { false; return qwe; }; f; echo $?
10664 * bash: return: qwe: numeric argument required <== we do this
10665 * 255 <== we also do this
10666 */
10667 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10668 return rc;
10669}
10670#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010671
Denys Vlasenko11f2e992017-08-10 16:34:03 +020010672#if ENABLE_HUSH_TIMES
10673static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10674{
10675 static const uint8_t times_tbl[] ALIGN1 = {
10676 ' ', offsetof(struct tms, tms_utime),
10677 '\n', offsetof(struct tms, tms_stime),
10678 ' ', offsetof(struct tms, tms_cutime),
10679 '\n', offsetof(struct tms, tms_cstime),
10680 0
10681 };
10682 const uint8_t *p;
10683 unsigned clk_tck;
10684 struct tms buf;
10685
10686 clk_tck = bb_clk_tck();
10687
10688 times(&buf);
10689 p = times_tbl;
10690 do {
10691 unsigned sec, frac;
10692 unsigned long t;
10693 t = *(clock_t *)(((char *) &buf) + p[1]);
10694 sec = t / clk_tck;
10695 frac = t % clk_tck;
10696 printf("%um%u.%03us%c",
10697 sec / 60, sec % 60,
10698 (frac * 1000) / clk_tck,
10699 p[0]);
10700 p += 2;
10701 } while (*p);
10702
10703 return EXIT_SUCCESS;
10704}
10705#endif
10706
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010707#if ENABLE_HUSH_MEMLEAK
10708static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10709{
10710 void *p;
10711 unsigned long l;
10712
10713# ifdef M_TRIM_THRESHOLD
10714 /* Optional. Reduces probability of false positives */
10715 malloc_trim(0);
10716# endif
10717 /* Crude attempt to find where "free memory" starts,
10718 * sans fragmentation. */
10719 p = malloc(240);
10720 l = (unsigned long)p;
10721 free(p);
10722 p = malloc(3400);
10723 if (l < (unsigned long)p) l = (unsigned long)p;
10724 free(p);
10725
10726
10727# if 0 /* debug */
10728 {
10729 struct mallinfo mi = mallinfo();
10730 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10731 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10732 }
10733# endif
10734
10735 if (!G.memleak_value)
10736 G.memleak_value = l;
10737
10738 l -= G.memleak_value;
10739 if ((long)l < 0)
10740 l = 0;
10741 l /= 1024;
10742 if (l > 127)
10743 l = 127;
10744
10745 /* Exitcode is "how many kilobytes we leaked since 1st call" */
10746 return l;
10747}
10748#endif