blob: c2b987f49e51f6f705f67f2709ebf209e0eef03c [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
50 * builtins mandated by standards we don't support:
Denys Vlasenko74d40582017-08-11 01:32:46 +020051 * [un]alias, command, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020052 * command -v CMD: print "/path/to/CMD"
53 * prints "CMD" for builtins
54 * prints "alias ALIAS='EXPANSION'" for aliases
55 * prints nothing and sets $? to 1 if not found
56 * command -V CMD: print "CMD is /path/CMD|a shell builtin|etc"
57 * command [-p] CMD: run CMD, even if a function CMD also exists
58 * (can use this to override standalone shell as well)
59 * -p: use default $PATH
Denys Vlasenko1e660422017-07-17 21:10:50 +020060 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020061 * fc -l[nr] [BEG] [END]: list range of commands in history
62 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
63 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000064 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * Bash compat TODO:
66 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020067 * reserved words: function select
68 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020069 * process substitution: <(list) and >(list)
70 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
73 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
74 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020075 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020076 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
77 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020078 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * indirect expansion: ${!VAR}
80 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020081 *
82 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020083 * Some builtins mandated by standards:
84 * newgrp [GRP]: not a builtin in bash but a suid binary
85 * which spawns a new shell with new group ID
Denys Vlasenkobbecd742010-10-03 17:22:52 +020086 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020087 * and therefore expansion of them should be "one-word" expansion:
88 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
89 * compare with:
90 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
91 * ls: cannot access i=a: No such file or directory
92 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020093 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020094 * Note2: bash 3.2.33(1) does this only if export word itself
95 * is not quoted:
96 * $ export i=`echo 'aaa bbb'`; echo "$i"
97 * aaa bbb
98 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
99 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +0000100 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200101//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +0200102//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config: default y
104//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200105//config: hush is a small shell. It handles the normal flow control
106//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
107//config: case/esac. Redirections, here documents, $((arithmetic))
108//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200109//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200110//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200111//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200112//config: It does not handle select, aliases, tilde expansion,
113//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200114//config:
115//config:config HUSH_BASH_COMPAT
116//config: bool "bash-compatible extensions"
117//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100118//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200119//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200120//config:config HUSH_BRACE_EXPANSION
121//config: bool "Brace expansion"
122//config: default y
123//config: depends on HUSH_BASH_COMPAT
124//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200125//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200126//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200127//config:config HUSH_INTERACTIVE
128//config: bool "Interactive mode"
129//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100130//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200131//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200132//config: Enable interactive mode (prompt and command editing).
133//config: Without this, hush simply reads and executes commands
134//config: from stdin just like a shell script from a file.
135//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200136//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200137//config:config HUSH_SAVEHISTORY
138//config: bool "Save command history to .hush_history"
139//config: default y
140//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200141//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:config HUSH_JOB
143//config: bool "Job control"
144//config: default y
145//config: depends on HUSH_INTERACTIVE
146//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200147//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
148//config: command (not entire shell), fg/bg builtins work. Without this option,
149//config: "cmd &" still works by simply spawning a process and immediately
150//config: prompting for next command (or executing next command in a script),
151//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200152//config:
153//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100154//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200155//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100156//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200157//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200158//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200159//config:
160//config:config HUSH_IF
161//config: bool "Support if/then/elif/else/fi"
162//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100163//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200164//config:
165//config:config HUSH_LOOPS
166//config: bool "Support for, while and until loops"
167//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100168//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200169//config:
170//config:config HUSH_CASE
171//config: bool "Support case ... esac statement"
172//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100173//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200174//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200175//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200176//config:
177//config:config HUSH_FUNCTIONS
178//config: bool "Support funcname() { commands; } syntax"
179//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100180//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200181//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200182//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200183//config:
184//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100185//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200186//config: default y
187//config: depends on HUSH_FUNCTIONS
188//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200189//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200190//config:
191//config:config HUSH_RANDOM_SUPPORT
192//config: bool "Pseudorandom generator and $RANDOM variable"
193//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100194//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200195//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200196//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
197//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200198//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200199//config:config HUSH_MODE_X
200//config: bool "Support 'hush -x' option and 'set -x' command"
201//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100202//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200203//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200204//config: This instructs hush to print commands before execution.
205//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200206//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100207//config:config HUSH_ECHO
208//config: bool "echo builtin"
209//config: default y
210//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100211//config:
212//config:config HUSH_PRINTF
213//config: bool "printf builtin"
214//config: default y
215//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100216//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100217//config:config HUSH_TEST
218//config: bool "test builtin"
219//config: default y
220//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
221//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100222//config:config HUSH_HELP
223//config: bool "help builtin"
224//config: default y
225//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100226//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100227//config:config HUSH_EXPORT
228//config: bool "export builtin"
229//config: default y
230//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100231//config:
232//config:config HUSH_EXPORT_N
233//config: bool "Support 'export -n' option"
234//config: default y
235//config: depends on HUSH_EXPORT
236//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200237//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100238//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200239//config:config HUSH_READONLY
240//config: bool "readonly builtin"
241//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200242//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200243//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200244//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200245//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100246//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100247//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100248//config: default y
249//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100250//config:
251//config:config HUSH_WAIT
252//config: bool "wait builtin"
253//config: default y
254//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100255//config:
256//config:config HUSH_TRAP
257//config: bool "trap builtin"
258//config: default y
259//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100260//config:
261//config:config HUSH_TYPE
262//config: bool "type builtin"
263//config: default y
264//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100265//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200266//config:config HUSH_TIMES
267//config: bool "times builtin"
268//config: default y
269//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
270//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100271//config:config HUSH_READ
272//config: bool "read builtin"
273//config: default y
274//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100275//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100276//config:config HUSH_SET
277//config: bool "set builtin"
278//config: default y
279//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100280//config:
281//config:config HUSH_UNSET
282//config: bool "unset builtin"
283//config: default y
284//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100285//config:
286//config:config HUSH_ULIMIT
287//config: bool "ulimit builtin"
288//config: default y
289//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100290//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100291//config:config HUSH_UMASK
292//config: bool "umask builtin"
293//config: default y
294//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100295//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200296//config:config HUSH_GETOPTS
297//config: bool "getopts builtin"
298//config: default y
299//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
300//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100301//config:config HUSH_MEMLEAK
302//config: bool "memleak builtin (debugging)"
303//config: default n
304//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200305
Denys Vlasenko20704f02011-03-23 17:59:27 +0100306//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100307// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100308//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100309//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100310
311//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100312//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
313//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100314//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
315
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100316/* -i (interactive) and -s (read stdin) are also accepted,
317 * but currently do nothing, therefore aren't shown in help.
318 * NOMMU-specific options are not meant to be used by users,
319 * therefore we don't show them either.
320 */
321//usage:#define hush_trivial_usage
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200322//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100323//usage:#define hush_full_usage "\n\n"
324//usage: "Unix shell interpreter"
325
Denys Vlasenko67047462016-12-22 15:21:58 +0100326#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
327 || defined(__APPLE__) \
328 )
329# include <malloc.h> /* for malloc_trim */
330#endif
331#include <glob.h>
332/* #include <dmalloc.h> */
333#if ENABLE_HUSH_CASE
334# include <fnmatch.h>
335#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200336#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100337#include <sys/utsname.h> /* for setting $HOSTNAME */
338
339#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
340#include "unicode.h"
341#include "shell_common.h"
342#include "math.h"
343#include "match.h"
344#if ENABLE_HUSH_RANDOM_SUPPORT
345# include "random.h"
346#else
347# define CLEAR_RANDOM_T(rnd) ((void)0)
348#endif
349#ifndef F_DUPFD_CLOEXEC
350# define F_DUPFD_CLOEXEC F_DUPFD
351#endif
352#ifndef PIPE_BUF
353# define PIPE_BUF 4096 /* amount of buffering in a pipe */
354#endif
355
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000356
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100357/* So far, all bash compat is controlled by one config option */
358/* Separate defines document which part of code implements what */
359#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
360#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100361#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
362#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200363#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200364#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100365
366
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200367/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000368#define LEAK_HUNTING 0
369#define BUILD_AS_NOMMU 0
370/* Enable/disable sanity checks. Ok to enable in production,
371 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
372 * Keeping 1 for now even in released versions.
373 */
374#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200375/* Slightly bigger (+200 bytes), but faster hush.
376 * So far it only enables a trick with counting SIGCHLDs and forks,
377 * which allows us to do fewer waitpid's.
378 * (we can detect a case where neither forks were done nor SIGCHLDs happened
379 * and therefore waitpid will return the same result as last time)
380 */
381#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200382/* TODO: implement simplified code for users which do not need ${var%...} ops
383 * So far ${var%...} ops are always enabled:
384 */
385#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000386
387
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000388#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000389# undef BB_MMU
390# undef USE_FOR_NOMMU
391# undef USE_FOR_MMU
392# define BB_MMU 0
393# define USE_FOR_NOMMU(...) __VA_ARGS__
394# define USE_FOR_MMU(...)
395#endif
396
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200397#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100398#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000399/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000400# undef CONFIG_FEATURE_SH_STANDALONE
401# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000402# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100403# undef IF_NOT_FEATURE_SH_STANDALONE
404# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000405# define IF_FEATURE_SH_STANDALONE(...)
406# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000407#endif
408
Denis Vlasenko05743d72008-02-10 12:10:08 +0000409#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000410# undef ENABLE_FEATURE_EDITING
411# define ENABLE_FEATURE_EDITING 0
412# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
413# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200414# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
415# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000416#endif
417
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000418/* Do we support ANY keywords? */
419#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000420# define HAS_KEYWORDS 1
421# define IF_HAS_KEYWORDS(...) __VA_ARGS__
422# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000423#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000424# define HAS_KEYWORDS 0
425# define IF_HAS_KEYWORDS(...)
426# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000427#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000428
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000429/* If you comment out one of these below, it will be #defined later
430 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000431#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000432/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000433#define debug_printf_parse(...) do {} while (0)
434#define debug_print_tree(a, b) do {} while (0)
435#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000436#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000437#define debug_printf_jobs(...) do {} while (0)
438#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200439#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000440#define debug_printf_glob(...) do {} while (0)
Denys Vlasenko2db74612017-07-07 22:07:28 +0200441#define debug_printf_redir(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000442#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000443#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000444#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000445
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000446#define ERR_PTR ((void*)(long)1)
447
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100448#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000449
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200450#define _SPECIAL_VARS_STR "_*@$!?#"
451#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
452#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100453#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200454/* Support / and // replace ops */
455/* Note that // is stored as \ in "encoded" string representation */
456# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
457# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
458# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
459#else
460# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
461# define VAR_SUBST_OPS "%#:-=+?"
462# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
463#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200464
Denys Vlasenko932b9972018-01-11 12:39:48 +0100465#define SPECIAL_VAR_SYMBOL_STR "\3"
466#define SPECIAL_VAR_SYMBOL 3
467/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
468#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000469
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200470struct variable;
471
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000472static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
473
474/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000475 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000476 */
477#if !BB_MMU
478typedef struct nommu_save_t {
479 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200480 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000481 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000482 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000483} nommu_save_t;
484#endif
485
Denys Vlasenko9b782552010-09-08 13:33:26 +0200486enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000487 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000488#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000489 RES_IF ,
490 RES_THEN ,
491 RES_ELIF ,
492 RES_ELSE ,
493 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000494#endif
495#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000496 RES_FOR ,
497 RES_WHILE ,
498 RES_UNTIL ,
499 RES_DO ,
500 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000501#endif
502#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000503 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000504#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000505#if ENABLE_HUSH_CASE
506 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200507 /* three pseudo-keywords support contrived "case" syntax: */
508 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
509 RES_MATCH , /* "word)" */
510 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000511 RES_ESAC ,
512#endif
513 RES_XXXX ,
514 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200515};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000516
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000517typedef struct o_string {
518 char *data;
519 int length; /* position where data is appended */
520 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200521 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000522 /* At least some part of the string was inside '' or "",
523 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200524 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000525 smallint has_empty_slot;
526 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
527} o_string;
528enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200529 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
530 EXP_FLAG_GLOB = 0x2,
531 /* Protect newly added chars against globbing
532 * by prepending \ to *, ?, [, \ */
533 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
534};
535enum {
536 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000537 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200538 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200539 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200540 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000541};
542/* Used for initialization: o_string foo = NULL_O_STRING; */
543#define NULL_O_STRING { NULL }
544
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200545#ifndef debug_printf_parse
546static const char *const assignment_flag[] = {
547 "MAYBE_ASSIGNMENT",
548 "DEFINITELY_ASSIGNMENT",
549 "NOT_ASSIGNMENT",
550 "WORD_IS_KEYWORD",
551};
552#endif
553
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000554typedef struct in_str {
555 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000556#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000557 smallint promptmode; /* 0: PS1, 1: PS2 */
558#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200559 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200560 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000561 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000562} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000563
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200564/* The descrip member of this structure is only used to make
565 * debugging output pretty */
566static const struct {
567 int mode;
568 signed char default_fd;
569 char descrip[3];
570} redir_table[] = {
571 { O_RDONLY, 0, "<" },
572 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
573 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
574 { O_CREAT|O_RDWR, 1, "<>" },
575 { O_RDONLY, 0, "<<" },
576/* Should not be needed. Bogus default_fd helps in debugging */
577/* { O_RDONLY, 77, "<<" }, */
578};
579
Eric Andersen25f27032001-04-26 23:22:31 +0000580struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000581 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000582 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000583 int rd_fd; /* fd to redirect */
584 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
585 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000586 smallint rd_type; /* (enum redir_type) */
587 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000588 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200589 * bit 0: do we need to trim leading tabs?
590 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000591 */
Eric Andersen25f27032001-04-26 23:22:31 +0000592};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000593typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200594 REDIRECT_INPUT = 0,
595 REDIRECT_OVERWRITE = 1,
596 REDIRECT_APPEND = 2,
597 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000598 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200599 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000600
601 REDIRFD_CLOSE = -3,
602 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000603 REDIRFD_TO_FILE = -1,
604 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000605
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000606 HEREDOC_SKIPTABS = 1,
607 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000608} redir_type;
609
Eric Andersen25f27032001-04-26 23:22:31 +0000610
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000611struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000612 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000613 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200614 smallint cmd_type; /* CMD_xxx */
615#define CMD_NORMAL 0
616#define CMD_SUBSHELL 1
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100617#if BASH_TEST2
Denys Vlasenkod383b492010-09-06 10:22:13 +0200618/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200619# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000620#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200621#if ENABLE_HUSH_FUNCTIONS
622# define CMD_FUNCDEF 3
623#endif
624
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100625 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200626 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
627 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000628#if !BB_MMU
629 char *group_as_string;
630#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000631#if ENABLE_HUSH_FUNCTIONS
632 struct function *child_func;
633/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200634 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000635 * When we execute "f1() {a;}" cmd, we create new function and clear
636 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200637 * When we execute "f1() {b;}", we notice that f1 exists,
638 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000639 * we put those fields back into cmd->xxx
640 * (struct function has ->parent_cmd ptr to facilitate that).
641 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
642 * Without this trick, loop would execute a;b;b;b;...
643 * instead of correct sequence a;b;a;b;...
644 * When command is freed, it severs the link
645 * (sets ->child_func->parent_cmd to NULL).
646 */
647#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000648 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000649/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
650 * and on execution these are substituted with their values.
651 * Substitution can make _several_ words out of one argv[n]!
652 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000653 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000654 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000655 struct redir_struct *redirects; /* I/O redirections */
656};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000657/* Is there anything in this command at all? */
658#define IS_NULL_CMD(cmd) \
659 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
660
Eric Andersen25f27032001-04-26 23:22:31 +0000661struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000662 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000663 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000664 int alive_cmds; /* number of commands running (not exited) */
665 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000666#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100667 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000668 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000669 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000670#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000671 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000672 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000673 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
674 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000675};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000676typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100677 PIPE_SEQ = 0,
678 PIPE_AND = 1,
679 PIPE_OR = 2,
680 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000681} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000682/* Is there anything in this pipe at all? */
683#define IS_NULL_PIPE(pi) \
684 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000685
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000686/* This holds pointers to the various results of parsing */
687struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000688 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000689 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000690 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000691 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000692 /* last command in pipe (being constructed right now) */
693 struct command *command;
694 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000695 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000696#if !BB_MMU
697 o_string as_string;
698#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000699#if HAS_KEYWORDS
700 smallint ctx_res_w;
701 smallint ctx_inverted; /* "! cmd | cmd" */
702#if ENABLE_HUSH_CASE
703 smallint ctx_dsemicolon; /* ";;" seen */
704#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000705 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
706 int old_flag;
707 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000708 * example: "if pipe1; pipe2; then pipe3; fi"
709 * when we see "if" or "then", we malloc and copy current context,
710 * and make ->stack point to it. then we parse pipeN.
711 * when closing "then" / fi" / whatever is found,
712 * we move list_head into ->stack->command->group,
713 * copy ->stack into current context, and delete ->stack.
714 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000715 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000716 struct parse_context *stack;
717#endif
718};
719
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000720/* On program start, environ points to initial environment.
721 * putenv adds new pointers into it, unsetenv removes them.
722 * Neither of these (de)allocates the strings.
723 * setenv allocates new strings in malloc space and does putenv,
724 * and thus setenv is unusable (leaky) for shell's purposes */
725#define setenv(...) setenv_is_leaky_dont_use()
726struct variable {
727 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000728 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200729#if ENABLE_HUSH_LOCAL
730 unsigned func_nest_level;
731#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000732 int max_len; /* if > 0, name is part of initial env; else name is malloced */
733 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000734 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000735};
736
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000737enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000738 BC_BREAK = 1,
739 BC_CONTINUE = 2,
740};
741
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000742#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000743struct function {
744 struct function *next;
745 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000746 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000747 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200748# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000749 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200750# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000751};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000752#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000753
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000754
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100755/* set -/+o OPT support. (TODO: make it optional)
756 * bash supports the following opts:
757 * allexport off
758 * braceexpand on
759 * emacs on
760 * errexit off
761 * errtrace off
762 * functrace off
763 * hashall on
764 * histexpand off
765 * history on
766 * ignoreeof off
767 * interactive-comments on
768 * keyword off
769 * monitor on
770 * noclobber off
771 * noexec off
772 * noglob off
773 * nolog off
774 * notify off
775 * nounset off
776 * onecmd off
777 * physical off
778 * pipefail off
779 * posix off
780 * privileged off
781 * verbose off
782 * vi off
783 * xtrace off
784 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800785static const char o_opt_strings[] ALIGN1 =
786 "pipefail\0"
787 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200788 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800789#if ENABLE_HUSH_MODE_X
790 "xtrace\0"
791#endif
792 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100793enum {
794 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800795 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200796 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800797#if ENABLE_HUSH_MODE_X
798 OPT_O_XTRACE,
799#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100800 NUM_OPT_O
801};
802
803
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200804struct FILE_list {
805 struct FILE_list *next;
806 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200807 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200808};
809
810
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000811/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000812/* Sorted roughly by size (smaller offsets == smaller code) */
813struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000814 /* interactive_fd != 0 means we are an interactive shell.
815 * If we are, then saved_tty_pgrp can also be != 0, meaning
816 * that controlling tty is available. With saved_tty_pgrp == 0,
817 * job control still works, but terminal signals
818 * (^C, ^Z, ^Y, ^\) won't work at all, and background
819 * process groups can only be created with "cmd &".
820 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
821 * to give tty to the foreground process group,
822 * and will take it back when the group is stopped (^Z)
823 * or killed (^C).
824 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000825#if ENABLE_HUSH_INTERACTIVE
826 /* 'interactive_fd' is a fd# open to ctty, if we have one
827 * _AND_ if we decided to act interactively */
828 int interactive_fd;
829 const char *PS1;
830 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000831# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000832#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000833# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000834#endif
835#if ENABLE_FEATURE_EDITING
836 line_input_t *line_input_state;
837#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000838 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200839 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000840 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200841#if ENABLE_HUSH_RANDOM_SUPPORT
842 random_t random_gen;
843#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000844#if ENABLE_HUSH_JOB
845 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100846 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000847 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000848 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400849# define G_saved_tty_pgrp (G.saved_tty_pgrp)
850#else
851# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000852#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200853 /* How deeply are we in context where "set -e" is ignored */
854 int errexit_depth;
855 /* "set -e" rules (do we follow them correctly?):
856 * Exit if pipe, list, or compound command exits with a non-zero status.
857 * Shell does not exit if failed command is part of condition in
858 * if/while, part of && or || list except the last command, any command
859 * in a pipe but the last, or if the command's return value is being
860 * inverted with !. If a compound command other than a subshell returns a
861 * non-zero status because a command failed while -e was being ignored, the
862 * shell does not exit. A trap on ERR, if set, is executed before the shell
863 * exits [ERR is a bashism].
864 *
865 * If a compound command or function executes in a context where -e is
866 * ignored, none of the commands executed within are affected by the -e
867 * setting. If a compound command or function sets -e while executing in a
868 * context where -e is ignored, that setting does not have any effect until
869 * the compound command or the command containing the function call completes.
870 */
871
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100872 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100873#if ENABLE_HUSH_MODE_X
874# define G_x_mode (G.o_opt[OPT_O_XTRACE])
875#else
876# define G_x_mode 0
877#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000878 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000879#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000880 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000881#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000882#if ENABLE_HUSH_FUNCTIONS
883 /* 0: outside of a function (or sourced file)
884 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000885 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000886 */
887 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200888# define G_flag_return_in_progress (G.flag_return_in_progress)
889#else
890# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000891#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000892 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000893 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000894 smalluint last_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200895 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100896#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000897 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000898 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100899# define G_global_args_malloced (G.global_args_malloced)
900#else
901# define G_global_args_malloced 0
902#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000903 /* how many non-NULL argv's we have. NB: $# + 1 */
904 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000905 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000906#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000907 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000908#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000909#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000910 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000911 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000912#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200913#if ENABLE_HUSH_GETOPTS
914 unsigned getopt_count;
915#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000916 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000917 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200918 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200919 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000920#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000921 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200922# if ENABLE_HUSH_LOCAL
923 struct variable **shadowed_vars_pp;
924 unsigned func_nest_level;
925# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000926#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000927 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200928#if ENABLE_HUSH_FAST
929 unsigned count_SIGCHLD;
930 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200931 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200932#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200933 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200934 /* Which signals have non-DFL handler (even with no traps set)?
935 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200936 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200937 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200938 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200939 * Other than these two times, never modified.
940 */
941 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200942#if ENABLE_HUSH_JOB
943 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100944# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200945#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200946# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200947#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100948#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000949 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100950# define G_traps G.traps
951#else
952# define G_traps ((char**)NULL)
953#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200954 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100955#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000956 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100957#endif
958#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000959 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000960#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200961 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200962#if ENABLE_FEATURE_EDITING
963 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
964#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000965};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000966#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000967/* Not #defining name to G.name - this quickly gets unwieldy
968 * (too many defines). Also, I actually prefer to see when a variable
969 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000970#define INIT_G() do { \
971 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200972 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
973 sigfillset(&G.sa.sa_mask); \
974 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000975} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000976
977
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000978/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200979static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100980#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200981static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100982#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200983static int builtin_eval(char **argv) FAST_FUNC;
984static int builtin_exec(char **argv) FAST_FUNC;
985static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100986#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200987static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100988#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +0200989#if ENABLE_HUSH_READONLY
990static int builtin_readonly(char **argv) FAST_FUNC;
991#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000992#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200993static int builtin_fg_bg(char **argv) FAST_FUNC;
994static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000995#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +0200996#if ENABLE_HUSH_GETOPTS
997static int builtin_getopts(char **argv) FAST_FUNC;
998#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000999#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001000static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001001#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001002#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001003static int builtin_history(char **argv) FAST_FUNC;
1004#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001005#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001006static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001007#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001008#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001009static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001010#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001011#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001012static int builtin_printf(char **argv) FAST_FUNC;
1013#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001014static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001015#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001016static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001017#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001018#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001019static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001020#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001021static int builtin_shift(char **argv) FAST_FUNC;
1022static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001023#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001024static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001025#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001026#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001027static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001028#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001029#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001030static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001031#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001032#if ENABLE_HUSH_TIMES
1033static int builtin_times(char **argv) FAST_FUNC;
1034#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001035static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001036#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001038#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001039#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001040static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001041#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001042#if ENABLE_HUSH_KILL
1043static int builtin_kill(char **argv) FAST_FUNC;
1044#endif
1045#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001046static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001047#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001048#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001049static int builtin_break(char **argv) FAST_FUNC;
1050static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001051#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001052#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001053static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001054#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001055
1056/* Table of built-in functions. They can be forked or not, depending on
1057 * context: within pipes, they fork. As simple commands, they do not.
1058 * When used in non-forking context, they can change global variables
1059 * in the parent shell process. If forked, of course they cannot.
1060 * For example, 'unset foo | whatever' will parse and run, but foo will
1061 * still be set at the end. */
1062struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001063 const char *b_cmd;
1064 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001065#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001066 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001067# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001068#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001069# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001070#endif
1071};
1072
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001073static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001074 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001075 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001076#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001077 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001078#endif
1079#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001080 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001081#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001082 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001083#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001084 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001085#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001086 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1087 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001088 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001089#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001090 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001091#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001092#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001093 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001094#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001095#if ENABLE_HUSH_GETOPTS
1096 BLTIN("getopts" , builtin_getopts , NULL),
1097#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001098#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001099 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001100#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001101#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001102 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001103#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001104#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001105 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001106#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001107#if ENABLE_HUSH_KILL
1108 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1109#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001110#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001111 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001112#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001113#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001114 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001115#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001116#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001117 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001118#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001119#if ENABLE_HUSH_READONLY
1120 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1121#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001122#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001123 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001124#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001125#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001126 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001127#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001128 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001129#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001130 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001131#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001132#if ENABLE_HUSH_TIMES
1133 BLTIN("times" , builtin_times , NULL),
1134#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001135#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001136 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001137#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001138 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001139#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001140 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001141#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001142#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001143 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001144#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001145#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001146 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001147#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001148#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001149 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001150#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001151#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001152 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001153#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001154};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001155/* These builtins won't be used if we are on NOMMU and need to re-exec
1156 * (it's cheaper to run an external program in this case):
1157 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001158static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001159#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001160 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001161#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001162#if BASH_TEST2
1163 BLTIN("[[" , builtin_test , NULL),
1164#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001165#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001166 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001167#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001168#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001169 BLTIN("printf" , builtin_printf , NULL),
1170#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001171 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001172#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001173 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001174#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001175};
1176
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001177
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001178/* Debug printouts.
1179 */
1180#if HUSH_DEBUG
1181/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001182# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001183# define debug_enter() (G.debug_indent++)
1184# define debug_leave() (G.debug_indent--)
1185#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001186# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001187# define debug_enter() ((void)0)
1188# define debug_leave() ((void)0)
1189#endif
1190
1191#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001192# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001193#endif
1194
1195#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001196# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001197#endif
1198
1199#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001200#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001201#endif
1202
1203#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001204# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001205#endif
1206
1207#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001208# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001209# define DEBUG_JOBS 1
1210#else
1211# define DEBUG_JOBS 0
1212#endif
1213
1214#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001215# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001216# define DEBUG_EXPAND 1
1217#else
1218# define DEBUG_EXPAND 0
1219#endif
1220
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001221#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001222# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001223#endif
1224
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001225#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001226# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001227# define DEBUG_GLOB 1
1228#else
1229# define DEBUG_GLOB 0
1230#endif
1231
Denys Vlasenko2db74612017-07-07 22:07:28 +02001232#ifndef debug_printf_redir
1233# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1234#endif
1235
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001236#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001237# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001238#endif
1239
1240#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001241# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001242#endif
1243
1244#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001245# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001246# define DEBUG_CLEAN 1
1247#else
1248# define DEBUG_CLEAN 0
1249#endif
1250
1251#if DEBUG_EXPAND
1252static void debug_print_strings(const char *prefix, char **vv)
1253{
1254 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001255 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001256 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001257 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258}
1259#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001260# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001261#endif
1262
1263
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001264/* Leak hunting. Use hush_leaktool.sh for post-processing.
1265 */
1266#if LEAK_HUNTING
1267static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001268{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001269 void *ptr = xmalloc((size + 0xff) & ~0xff);
1270 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1271 return ptr;
1272}
1273static void *xxrealloc(int lineno, void *ptr, size_t size)
1274{
1275 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1276 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1277 return ptr;
1278}
1279static char *xxstrdup(int lineno, const char *str)
1280{
1281 char *ptr = xstrdup(str);
1282 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1283 return ptr;
1284}
1285static void xxfree(void *ptr)
1286{
1287 fdprintf(2, "free %p\n", ptr);
1288 free(ptr);
1289}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001290# define xmalloc(s) xxmalloc(__LINE__, s)
1291# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1292# define xstrdup(s) xxstrdup(__LINE__, s)
1293# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001294#endif
1295
1296
1297/* Syntax and runtime errors. They always abort scripts.
1298 * In interactive use they usually discard unparsed and/or unexecuted commands
1299 * and return to the prompt.
1300 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1301 */
1302#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001303# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001304# define syntax_error(lineno, msg) syntax_error(msg)
1305# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1306# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1307# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1308# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001309#endif
1310
Denys Vlasenko39701202017-08-02 19:44:05 +02001311static void die_if_script(void)
1312{
1313 if (!G_interactive_fd) {
1314 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1315 xfunc_error_retval = G.last_exitcode;
1316 xfunc_die();
1317 }
1318}
1319
1320static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001321{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001322 va_list p;
1323
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001324#if HUSH_DEBUG >= 2
1325 bb_error_msg("hush.c:%u", lineno);
1326#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001327 va_start(p, fmt);
1328 bb_verror_msg(fmt, p, NULL);
1329 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001330 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001331}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001332
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001333static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001334{
1335 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001336 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001337 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001338 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001339 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001340}
1341
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001342static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001343{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001344 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001345 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001346}
1347
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001348static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001349{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001350 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001351//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1352// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001353}
1354
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001355static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001356{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001357 char msg[2] = { ch, '\0' };
1358 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001359}
1360
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001361static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001362{
1363 char msg[2];
1364 msg[0] = ch;
1365 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001366#if HUSH_DEBUG >= 2
1367 bb_error_msg("hush.c:%u", lineno);
1368#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001369 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001370 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001371}
1372
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001373#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001374# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001375# undef syntax_error
1376# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001377# undef syntax_error_unterm_ch
1378# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001379# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001380#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001381# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001382# define syntax_error(msg) syntax_error(__LINE__, msg)
1383# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1384# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1385# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1386# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001387#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001388
Denis Vlasenko552433b2009-04-04 19:29:21 +00001389
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001390#if ENABLE_HUSH_INTERACTIVE
1391static void cmdedit_update_prompt(void);
1392#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001393# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001394#endif
1395
1396
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001397/* Utility functions
1398 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001399/* Replace each \x with x in place, return ptr past NUL. */
1400static char *unbackslash(char *src)
1401{
Denys Vlasenko71885402009-09-24 01:44:13 +02001402 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001403 while (1) {
1404 if (*src == '\\')
1405 src++;
1406 if ((*dst++ = *src++) == '\0')
1407 break;
1408 }
1409 return dst;
1410}
1411
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001412static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001413{
1414 int i;
1415 unsigned count1;
1416 unsigned count2;
1417 char **v;
1418
1419 v = strings;
1420 count1 = 0;
1421 if (v) {
1422 while (*v) {
1423 count1++;
1424 v++;
1425 }
1426 }
1427 count2 = 0;
1428 v = add;
1429 while (*v) {
1430 count2++;
1431 v++;
1432 }
1433 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1434 v[count1 + count2] = NULL;
1435 i = count2;
1436 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001437 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001438 return v;
1439}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001440#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001441static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1442{
1443 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1444 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1445 return ptr;
1446}
1447#define add_strings_to_strings(strings, add, need_to_dup) \
1448 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1449#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001450
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001451/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001452static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001453{
1454 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001455 v[0] = add;
1456 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001457 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001458}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001459#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001460static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1461{
1462 char **ptr = add_string_to_strings(strings, add);
1463 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1464 return ptr;
1465}
1466#define add_string_to_strings(strings, add) \
1467 xx_add_string_to_strings(__LINE__, strings, add)
1468#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001469
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001470static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001471{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001472 char **v;
1473
1474 if (!strings)
1475 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001476 v = strings;
1477 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001478 free(*v);
1479 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001480 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001481 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001482}
1483
Denys Vlasenko2db74612017-07-07 22:07:28 +02001484static int fcntl_F_DUPFD(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001485{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001486 int newfd;
1487 repeat:
1488 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001489 if (newfd < 0) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001490 if (errno == EBUSY)
1491 goto repeat;
1492 if (errno == EINTR)
1493 goto repeat;
1494 }
1495 return newfd;
1496}
1497
Denys Vlasenko657e9002017-07-30 23:34:04 +02001498static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001499{
1500 int newfd;
1501 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001502 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001503 if (newfd < 0) {
1504 if (errno == EBUSY)
1505 goto repeat;
1506 if (errno == EINTR)
1507 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001508 /* fd was not open? */
1509 if (errno == EBADF)
1510 return fd;
1511 xfunc_die();
1512 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001513 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1514 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001515 close(fd);
1516 return newfd;
1517}
1518
1519
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001520/* Manipulating the list of open FILEs */
1521static FILE *remember_FILE(FILE *fp)
1522{
1523 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001524 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001525 n->next = G.FILE_list;
1526 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001527 n->fp = fp;
1528 n->fd = fileno(fp);
1529 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001530 }
1531 return fp;
1532}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001533static void fclose_and_forget(FILE *fp)
1534{
1535 struct FILE_list **pp = &G.FILE_list;
1536 while (*pp) {
1537 struct FILE_list *cur = *pp;
1538 if (cur->fp == fp) {
1539 *pp = cur->next;
1540 free(cur);
1541 break;
1542 }
1543 pp = &cur->next;
1544 }
1545 fclose(fp);
1546}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001547static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001548{
1549 struct FILE_list *fl = G.FILE_list;
1550 while (fl) {
1551 if (fd == fl->fd) {
1552 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001553 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001554 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 +02001555 return 1;
1556 }
1557 fl = fl->next;
1558 }
1559 return 0;
1560}
1561static void restore_redirected_FILEs(void)
1562{
1563 struct FILE_list *fl = G.FILE_list;
1564 while (fl) {
1565 int should_be = fileno(fl->fp);
1566 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001567 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001568 xmove_fd(fl->fd, should_be);
1569 fl->fd = should_be;
1570 }
1571 fl = fl->next;
1572 }
1573}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001574#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001575static void close_all_FILE_list(void)
1576{
1577 struct FILE_list *fl = G.FILE_list;
1578 while (fl) {
1579 /* fclose would also free FILE object.
1580 * It is disastrous if we share memory with a vforked parent.
1581 * I'm not sure we never come here after vfork.
1582 * Therefore just close fd, nothing more.
1583 */
1584 /*fclose(fl->fp); - unsafe */
1585 close(fl->fd);
1586 fl = fl->next;
1587 }
1588}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001589#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001590static int fd_in_FILEs(int fd)
1591{
1592 struct FILE_list *fl = G.FILE_list;
1593 while (fl) {
1594 if (fl->fd == fd)
1595 return 1;
1596 fl = fl->next;
1597 }
1598 return 0;
1599}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001600
1601
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001602/* Helpers for setting new $n and restoring them back
1603 */
1604typedef struct save_arg_t {
1605 char *sv_argv0;
1606 char **sv_g_argv;
1607 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001608 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001609} save_arg_t;
1610
1611static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1612{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001613 sv->sv_argv0 = argv[0];
1614 sv->sv_g_argv = G.global_argv;
1615 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001616 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001617
1618 argv[0] = G.global_argv[0]; /* retain $0 */
1619 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001620 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001621
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001622 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001623}
1624
1625static void restore_G_args(save_arg_t *sv, char **argv)
1626{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001627#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001628 if (G.global_args_malloced) {
1629 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001630 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001631 while (*++pp) /* note: does not free $0 */
1632 free(*pp);
1633 free(G.global_argv);
1634 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001635#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001636 argv[0] = sv->sv_argv0;
1637 G.global_argv = sv->sv_g_argv;
1638 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001639 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001640}
1641
1642
Denis Vlasenkod5762932009-03-31 11:22:57 +00001643/* Basic theory of signal handling in shell
1644 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001645 * This does not describe what hush does, rather, it is current understanding
1646 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001647 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1648 *
1649 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1650 * is finished or backgrounded. It is the same in interactive and
1651 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001652 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001653 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001654 * backgrounds (i.e. stops) or kills all members of currently running
1655 * pipe.
1656 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001657 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001658 * or by SIGINT in interactive shell.
1659 *
1660 * Trap handlers will execute even within trap handlers. (right?)
1661 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001662 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1663 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001664 *
1665 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001666 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001667 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001668 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001669 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001670 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001671 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001672 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001673 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001674 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001675 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001676 *
1677 * SIGQUIT: ignore
1678 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001679 * SIGHUP (interactive):
1680 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001681 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001682 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1683 * that all pipe members are stopped. Try this in bash:
1684 * while :; do :; done - ^Z does not background it
1685 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001686 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001687 * of the command line, show prompt. NB: ^C does not send SIGINT
1688 * to interactive shell while shell is waiting for a pipe,
1689 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001690 * Example 1: this waits 5 sec, but does not execute ls:
1691 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1692 * Example 2: this does not wait and does not execute ls:
1693 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1694 * Example 3: this does not wait 5 sec, but executes ls:
1695 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001696 * Example 4: this does not wait and does not execute ls:
1697 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001698 *
1699 * (What happens to signals which are IGN on shell start?)
1700 * (What happens with signal mask on shell start?)
1701 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001702 * Old implementation
1703 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001704 * We use in-kernel pending signal mask to determine which signals were sent.
1705 * We block all signals which we don't want to take action immediately,
1706 * i.e. we block all signals which need to have special handling as described
1707 * above, and all signals which have traps set.
1708 * After each pipe execution, we extract any pending signals via sigtimedwait()
1709 * and act on them.
1710 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001711 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001712 * sigset_t blocked_set: current blocked signal set
1713 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001714 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001715 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001716 * "trap 'cmd' SIGxxx":
1717 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001718 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001719 * unblock signals with special interactive handling
1720 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001721 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001722 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001723 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001724 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001725 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001726 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001727 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001728 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001729 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001730 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001731 * Standard says "When a subshell is entered, traps that are not being ignored
1732 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001733 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001734 *
1735 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001736 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001737 * masked signals are not visible!
1738 *
1739 * New implementation
1740 * ==================
1741 * We record each signal we are interested in by installing signal handler
1742 * for them - a bit like emulating kernel pending signal mask in userspace.
1743 * We are interested in: signals which need to have special handling
1744 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001745 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001746 * After each pipe execution, we extract any pending signals
1747 * and act on them.
1748 *
1749 * unsigned special_sig_mask: a mask of shell-special signals.
1750 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1751 * char *traps[sig] if trap for sig is set (even if it's '').
1752 * sigset_t pending_set: set of sigs we received.
1753 *
1754 * "trap - SIGxxx":
1755 * if sig is in special_sig_mask, set handler back to:
1756 * record_pending_signo, or to IGN if it's a tty stop signal
1757 * if sig is in fatal_sig_mask, set handler back to sigexit.
1758 * else: set handler back to SIG_DFL
1759 * "trap 'cmd' SIGxxx":
1760 * set handler to record_pending_signo.
1761 * "trap '' SIGxxx":
1762 * set handler to SIG_IGN.
1763 * after [v]fork, if we plan to be a shell:
1764 * set signals with special interactive handling to SIG_DFL
1765 * (because child shell is not interactive),
1766 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1767 * after [v]fork, if we plan to exec:
1768 * POSIX says fork clears pending signal mask in child - no need to clear it.
1769 *
1770 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1771 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1772 *
1773 * Note (compat):
1774 * Standard says "When a subshell is entered, traps that are not being ignored
1775 * are set to the default actions". bash interprets it so that traps which
1776 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001777 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001778enum {
1779 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001780 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001781 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001782 | (1 << SIGHUP)
1783 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001784 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001785#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001786 | (1 << SIGTTIN)
1787 | (1 << SIGTTOU)
1788 | (1 << SIGTSTP)
1789#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001790 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001791};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001792
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001793static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001794{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001795 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001796#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001797 if (sig == SIGCHLD) {
1798 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001799//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 +02001800 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001801#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001802}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001803
Denys Vlasenko0806e402011-05-12 23:06:20 +02001804static sighandler_t install_sighandler(int sig, sighandler_t handler)
1805{
1806 struct sigaction old_sa;
1807
1808 /* We could use signal() to install handlers... almost:
1809 * except that we need to mask ALL signals while handlers run.
1810 * I saw signal nesting in strace, race window isn't small.
1811 * SA_RESTART is also needed, but in Linux, signal()
1812 * sets SA_RESTART too.
1813 */
1814 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1815 /* sigfillset(&G.sa.sa_mask); - already done */
1816 /* G.sa.sa_flags = SA_RESTART; - already done */
1817 G.sa.sa_handler = handler;
1818 sigaction(sig, &G.sa, &old_sa);
1819 return old_sa.sa_handler;
1820}
1821
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001822static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001823
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001824static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001825static void restore_ttypgrp_and__exit(void)
1826{
1827 /* xfunc has failed! die die die */
1828 /* no EXIT traps, this is an escape hatch! */
1829 G.exiting = 1;
1830 hush_exit(xfunc_error_retval);
1831}
1832
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001833#if ENABLE_HUSH_JOB
1834
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001835/* Needed only on some libc:
1836 * It was observed that on exit(), fgetc'ed buffered data
1837 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1838 * With the net effect that even after fork(), not vfork(),
1839 * exit() in NOEXECed applet in "sh SCRIPT":
1840 * noexec_applet_here
1841 * echo END_OF_SCRIPT
1842 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1843 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001844 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001845 * and in `cmd` handling.
1846 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1847 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001848static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001849static void fflush_and__exit(void)
1850{
1851 fflush_all();
1852 _exit(xfunc_error_retval);
1853}
1854
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001855/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001856# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001857/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001858# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001859
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001860/* Restores tty foreground process group, and exits.
1861 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001862 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001863 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001864 * We also call it if xfunc is exiting.
1865 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001866static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001867static void sigexit(int sig)
1868{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001869 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001870 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001871 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1872 /* Disable all signals: job control, SIGPIPE, etc.
1873 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1874 */
1875 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001876 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001877 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001878
1879 /* Not a signal, just exit */
1880 if (sig <= 0)
1881 _exit(- sig);
1882
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001883 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001884}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001885#else
1886
Denys Vlasenko8391c482010-05-22 17:50:43 +02001887# define disable_restore_tty_pgrp_on_exit() ((void)0)
1888# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001889
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001890#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001891
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001892static sighandler_t pick_sighandler(unsigned sig)
1893{
1894 sighandler_t handler = SIG_DFL;
1895 if (sig < sizeof(unsigned)*8) {
1896 unsigned sigmask = (1 << sig);
1897
1898#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001899 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001900 if (G_fatal_sig_mask & sigmask)
1901 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001902 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001903#endif
1904 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001905 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001906 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001907 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001908 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001909 * in an endless loop when we try to do some
1910 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001911 */
1912 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1913 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001914 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001915 }
1916 return handler;
1917}
1918
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001919/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001920static void hush_exit(int exitcode)
1921{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001922#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1923 save_history(G.line_input_state);
1924#endif
1925
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001926 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001927 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001928 char *argv[3];
1929 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001930 argv[1] = G_traps[0];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001931 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001932 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001933 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001934 * "trap" will still show it, if executed
1935 * in the handler */
1936 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001937 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001938
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001939#if ENABLE_FEATURE_CLEAN_UP
1940 {
1941 struct variable *cur_var;
1942 if (G.cwd != bb_msg_unknown)
1943 free((char*)G.cwd);
1944 cur_var = G.top_var;
1945 while (cur_var) {
1946 struct variable *tmp = cur_var;
1947 if (!cur_var->max_len)
1948 free(cur_var->varstr);
1949 cur_var = cur_var->next;
1950 free(tmp);
1951 }
1952 }
1953#endif
1954
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001955 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001956#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001957 sigexit(- (exitcode & 0xff));
1958#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001959 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001960#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001961}
1962
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001963
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001964//TODO: return a mask of ALL handled sigs?
1965static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001966{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001967 int last_sig = 0;
1968
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001969 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001970 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001971
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001972 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001973 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001974 sig = 0;
1975 do {
1976 sig++;
1977 if (sigismember(&G.pending_set, sig)) {
1978 sigdelset(&G.pending_set, sig);
1979 goto got_sig;
1980 }
1981 } while (sig < NSIG);
1982 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001983 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001984 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001985 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001986 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001987 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001988 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001989 char *argv[3];
1990 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001991 argv[1] = G_traps[sig];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001992 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001993 save_rcode = G.last_exitcode;
1994 builtin_eval(argv);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01001995//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001996 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001997 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001998 } /* else: "" trap, ignoring signal */
1999 continue;
2000 }
2001 /* not a trap: special action */
2002 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002003 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002004 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002005 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002006 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002007 break;
2008#if ENABLE_HUSH_JOB
2009 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002010//TODO: why are we doing this? ash and dash don't do this,
2011//they have no handler for SIGHUP at all,
2012//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002013 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002014 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002015 /* bash is observed to signal whole process groups,
2016 * not individual processes */
2017 for (job = G.job_list; job; job = job->next) {
2018 if (job->pgrp <= 0)
2019 continue;
2020 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2021 if (kill(- job->pgrp, SIGHUP) == 0)
2022 kill(- job->pgrp, SIGCONT);
2023 }
2024 sigexit(SIGHUP);
2025 }
2026#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002027#if ENABLE_HUSH_FAST
2028 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002029 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002030 G.count_SIGCHLD++;
2031//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2032 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002033 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002034 * This simplifies wait builtin a bit.
2035 */
2036 break;
2037#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002038 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002039 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002040 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002041 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002042 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002043 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002044 * in interactive shell, because TERM is ignored.
2045 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002046 break;
2047 }
2048 }
2049 return last_sig;
2050}
2051
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002052
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002053static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002054{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002055 if (force || G.cwd == NULL) {
2056 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2057 * we must not try to free(bb_msg_unknown) */
2058 if (G.cwd == bb_msg_unknown)
2059 G.cwd = NULL;
2060 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2061 if (!G.cwd)
2062 G.cwd = bb_msg_unknown;
2063 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002064 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002065}
2066
Denis Vlasenko83506862007-11-23 13:11:42 +00002067
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002068/*
2069 * Shell and environment variable support
2070 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002071static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002072{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002073 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002074 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002075
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002076 pp = &G.top_var;
2077 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002078 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002079 return pp;
2080 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002081 }
2082 return NULL;
2083}
2084
Denys Vlasenko03dad222010-01-12 23:29:57 +01002085static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002086{
Denys Vlasenko29082232010-07-16 13:52:32 +02002087 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002088 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002089
2090 if (G.expanded_assignments) {
2091 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002092 while (*cpp) {
2093 char *cp = *cpp;
2094 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2095 return cp + len + 1;
2096 cpp++;
2097 }
2098 }
2099
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002100 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002101 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002102 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002103
Denys Vlasenkodea47882009-10-09 15:40:49 +02002104 if (strcmp(name, "PPID") == 0)
2105 return utoa(G.root_ppid);
2106 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002107#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002108 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002109 return utoa(next_random(&G.random_gen));
2110#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002111 return NULL;
2112}
2113
2114/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002115 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002116 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002117#define SETFLAG_EXPORT (1 << 0)
2118#define SETFLAG_UNEXPORT (1 << 1)
2119#define SETFLAG_MAKE_RO (1 << 2)
2120#define SETFLAG_LOCAL_SHIFT 3
2121static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002122{
Denys Vlasenko295fef82009-06-03 12:47:26 +02002123 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002124 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002125 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002126 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002127 int name_len;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002128 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129
Denis Vlasenko950bd722009-04-21 11:23:56 +00002130 eq_sign = strchr(str, '=');
2131 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002132 free(str);
2133 return -1;
2134 }
2135
Denis Vlasenko950bd722009-04-21 11:23:56 +00002136 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002137 var_pp = &G.top_var;
2138 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002139 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002140 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141 continue;
2142 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002143
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002144 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002145 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002146 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002147 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002148//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2149//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002150 return -1;
2151 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002152 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002153 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2154 *eq_sign = '\0';
2155 unsetenv(str);
2156 *eq_sign = '=';
2157 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002158#if ENABLE_HUSH_LOCAL
2159 if (cur->func_nest_level < local_lvl) {
2160 /* New variable is declared as local,
2161 * and existing one is global, or local
2162 * from enclosing function.
2163 * Remove and save old one: */
2164 *var_pp = cur->next;
2165 cur->next = *G.shadowed_vars_pp;
2166 *G.shadowed_vars_pp = cur;
2167 /* bash 3.2.33(1) and exported vars:
2168 * # export z=z
2169 * # f() { local z=a; env | grep ^z; }
2170 * # f
2171 * z=a
2172 * # env | grep ^z
2173 * z=z
2174 */
2175 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002176 flags |= SETFLAG_EXPORT;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002177 break;
2178 }
2179#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00002180 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002181 free_and_exp:
2182 free(str);
2183 goto exp;
2184 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002185 if (cur->max_len != 0) {
2186 if (cur->max_len >= strlen(str)) {
2187 /* This one is from startup env, reuse space */
2188 strcpy(cur->varstr, str);
2189 goto free_and_exp;
2190 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002191 /* Can't reuse */
2192 cur->max_len = 0;
2193 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002194 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002195 /* max_len == 0 signifies "malloced" var, which we can
2196 * (and have to) free. But we can't free(cur->varstr) here:
2197 * if cur->flg_export is 1, it is in the environment.
2198 * We should either unsetenv+free, or wait until putenv,
2199 * then putenv(new)+free(old).
2200 */
2201 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002202 goto set_str_and_exp;
2203 }
2204
Denys Vlasenko295fef82009-06-03 12:47:26 +02002205 /* Not found - create new variable struct */
2206 cur = xzalloc(sizeof(*cur));
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002207 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
Denys Vlasenko295fef82009-06-03 12:47:26 +02002208 cur->next = *var_pp;
2209 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002210
2211 set_str_and_exp:
2212 cur->varstr = str;
2213 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002214#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002215 if (flags & SETFLAG_MAKE_RO) {
2216 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002217 }
2218#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002219 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002220 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002221 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2222 cmdedit_update_prompt();
Denys Vlasenko238ff982017-08-29 13:38:30 +02002223#if ENABLE_HUSH_GETOPTS
Denys Vlasenko55af51c2017-08-29 13:48:49 +02002224 /* defoptindvar is a "OPTIND=..." constant string */
2225 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
Denys Vlasenko238ff982017-08-29 13:38:30 +02002226 G.getopt_count = 0;
2227#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002228 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002229 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002230 cur->flg_export = 0;
2231 /* unsetenv was already done */
2232 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002233 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002234 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002235 i = putenv(cur->varstr);
2236 /* only now we can free old exported malloced string */
2237 free(free_me);
2238 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002239 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002240 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002241 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002242 return 0;
2243}
2244
Denys Vlasenko6db47842009-09-05 20:15:17 +02002245/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002246static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002247{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002248 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002249}
2250
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002251static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002252{
2253 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002254 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002255
2256 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002257 return EXIT_SUCCESS;
Denys Vlasenko238ff982017-08-29 13:38:30 +02002258#if ENABLE_HUSH_GETOPTS
2259 if (name_len == 6 && strncmp(name, "OPTIND", 6) == 0)
2260 G.getopt_count = 0;
2261#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002262 var_pp = &G.top_var;
2263 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002264 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2265 if (cur->flg_read_only) {
2266 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002267 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002268 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002269 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002270 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2271 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002272 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2273 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002274 if (!cur->max_len)
2275 free(cur->varstr);
2276 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002277 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002278 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002279 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002280 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002281 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002282}
2283
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002284#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002285static int unset_local_var(const char *name)
2286{
2287 return unset_local_var_len(name, strlen(name));
2288}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002289#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002290
2291static void unset_vars(char **strings)
2292{
2293 char **v;
2294
2295 if (!strings)
2296 return;
2297 v = strings;
2298 while (*v) {
2299 const char *eq = strchrnul(*v, '=');
2300 unset_local_var_len(*v, (int)(eq - *v));
2301 v++;
2302 }
2303 free(strings);
2304}
2305
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002306#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002307static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002308{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002309 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002310 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002311}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002312#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002313
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002314
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002316 * Helpers for "var1=val1 var2=val2 cmd" feature
2317 */
2318static void add_vars(struct variable *var)
2319{
2320 struct variable *next;
2321
2322 while (var) {
2323 next = var->next;
2324 var->next = G.top_var;
2325 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002326 if (var->flg_export) {
2327 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002328 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002329 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002330 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002331 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002332 var = next;
2333 }
2334}
2335
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002336static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002337{
2338 char **s;
2339 struct variable *old = NULL;
2340
2341 if (!strings)
2342 return old;
2343 s = strings;
2344 while (*s) {
2345 struct variable *var_p;
2346 struct variable **var_pp;
2347 char *eq;
2348
2349 eq = strchr(*s, '=');
2350 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002351 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002352 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002353 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002354 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002355 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002356 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002357 /*
2358 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2359 * If VAR is readonly, leaving it in the list
2360 * after asssignment error (msg above)
2361 * causes doubled error message later, on unset.
2362 */
2363 debug_printf_env("removing/freeing '%s' element\n", *s);
2364 free(*s);
2365 p = s;
2366 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002367 goto next;
2368 }
2369 /* Remove variable from global linked list */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002370 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002371 *var_pp = var_p->next;
2372 /* Add it to returned list */
2373 var_p->next = old;
2374 old = var_p;
2375 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002376 set_local_var(*s, SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002377 }
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002378 next:
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002379 s++;
2380 }
2381 return old;
2382}
2383
2384
2385/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002386 * Unicode helper
2387 */
2388static void reinit_unicode_for_hush(void)
2389{
2390 /* Unicode support should be activated even if LANG is set
2391 * _during_ shell execution, not only if it was set when
2392 * shell was started. Therefore, re-check LANG every time:
2393 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002394 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2395 || ENABLE_UNICODE_USING_LOCALE
2396 ) {
2397 const char *s = get_local_var_value("LC_ALL");
2398 if (!s) s = get_local_var_value("LC_CTYPE");
2399 if (!s) s = get_local_var_value("LANG");
2400 reinit_unicode(s);
2401 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002402}
2403
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002404/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002405 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002406 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002407
2408#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002409/* To test correct lineedit/interactive behavior, type from command line:
2410 * echo $P\
2411 * \
2412 * AT\
2413 * H\
2414 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002415 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002416 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002417static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002418{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002419 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002420 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002421 if (G.PS1 == NULL)
2422 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002423 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002424 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002425 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002426 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002427 if (G.PS2 == NULL)
2428 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002429}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002430static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002431{
2432 const char *prompt_str;
2433 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002434 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2435 /* Set up the prompt */
2436 if (promptmode == 0) { /* PS1 */
2437 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002438 /* bash uses $PWD value, even if it is set by user.
2439 * It uses current dir only if PWD is unset.
2440 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002441 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002442 prompt_str = G.PS1;
2443 } else
2444 prompt_str = G.PS2;
2445 } else
2446 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002447 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002448 return prompt_str;
2449}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002450static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002451{
2452 int r;
2453 const char *prompt_str;
2454
2455 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002456# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002457 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002458 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002459 if (G.flag_SIGINT) {
2460 /* There was ^C'ed, make it look prettier: */
2461 bb_putchar('\n');
2462 G.flag_SIGINT = 0;
2463 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002464 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002465 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002466 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002467 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002468 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002469 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002470 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002471 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002472 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002473 if (r != 0 && !G.flag_SIGINT)
2474 break;
2475 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002476 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2477 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002478 G.last_exitcode = 128 + SIGINT;
2479 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002480 if (r < 0) {
2481 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002482 i->p = NULL;
2483 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002484 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002485 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002486 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002487 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002488# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002489 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002490 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002491 if (i->last_char == '\0' || i->last_char == '\n') {
2492 /* Why check_and_run_traps here? Try this interactively:
2493 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2494 * $ <[enter], repeatedly...>
2495 * Without check_and_run_traps, handler never runs.
2496 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002497 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002498 fputs(prompt_str, stdout);
2499 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002500 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002501//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002502 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002503 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2504 * no ^C masking happens during fgetc, no special code for ^C:
2505 * it generates SIGINT as usual.
2506 */
2507 check_and_run_traps();
2508 if (G.flag_SIGINT)
2509 G.last_exitcode = 128 + SIGINT;
2510 if (r != '\0')
2511 break;
2512 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002513 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002514# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002515}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002516/* This is the magic location that prints prompts
2517 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002518static int fgetc_interactive(struct in_str *i)
2519{
2520 int ch;
2521 /* If it's interactive stdin, get new line. */
2522 if (G_interactive_fd && i->file == stdin) {
2523 /* Returns first char (or EOF), the rest is in i->p[] */
2524 ch = get_user_input(i);
2525 i->promptmode = 1; /* PS2 */
2526 } else {
2527 /* Not stdin: script file, sourced file, etc */
2528 do ch = fgetc(i->file); while (ch == '\0');
2529 }
2530 return ch;
2531}
2532#else
2533static inline int fgetc_interactive(struct in_str *i)
2534{
2535 int ch;
2536 do ch = fgetc(i->file); while (ch == '\0');
2537 return ch;
2538}
2539#endif /* INTERACTIVE */
2540
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002541static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002542{
2543 int ch;
2544
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002545 if (!i->file) {
2546 /* string-based in_str */
2547 ch = (unsigned char)*i->p;
2548 if (ch != '\0') {
2549 i->p++;
2550 i->last_char = ch;
2551 return ch;
2552 }
2553 return EOF;
2554 }
2555
2556 /* FILE-based in_str */
2557
Denys Vlasenko4074d492016-09-30 01:49:53 +02002558#if ENABLE_FEATURE_EDITING
2559 /* This can be stdin, check line editing char[] buffer */
2560 if (i->p && *i->p != '\0') {
2561 ch = (unsigned char)*i->p++;
2562 goto out;
2563 }
2564#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002565 /* peek_buf[] is an int array, not char. Can contain EOF. */
2566 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002567 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002568 int ch2 = i->peek_buf[1];
2569 i->peek_buf[0] = ch2;
2570 if (ch2 == 0) /* very likely, avoid redundant write */
2571 goto out;
2572 i->peek_buf[1] = 0;
2573 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002574 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002575
Denys Vlasenko4074d492016-09-30 01:49:53 +02002576 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002577 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002578 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002579 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002580 return ch;
2581}
2582
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002583static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002584{
2585 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002586
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002587 if (!i->file) {
2588 /* string-based in_str */
2589 /* Doesn't report EOF on NUL. None of the callers care. */
2590 return (unsigned char)*i->p;
2591 }
2592
2593 /* FILE-based in_str */
2594
Denys Vlasenko4074d492016-09-30 01:49:53 +02002595#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002596 /* This can be stdin, check line editing char[] buffer */
2597 if (i->p && *i->p != '\0')
2598 return (unsigned char)*i->p;
2599#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002600 /* peek_buf[] is an int array, not char. Can contain EOF. */
2601 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002602 if (ch != 0)
2603 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002604
Denys Vlasenko4074d492016-09-30 01:49:53 +02002605 /* Need to get a new char */
2606 ch = fgetc_interactive(i);
2607 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2608
2609 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2610#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2611 if (i->p) {
2612 i->p -= 1;
2613 return ch;
2614 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002615#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002616 i->peek_buf[0] = ch;
2617 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002618 return ch;
2619}
2620
Denys Vlasenko4074d492016-09-30 01:49:53 +02002621/* Only ever called if i_peek() was called, and did not return EOF.
2622 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2623 * not end-of-line. Therefore we never need to read a new editing line here.
2624 */
2625static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002626{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002627 int ch;
2628
2629 /* There are two cases when i->p[] buffer exists.
2630 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002631 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002632 * In both cases, we know that i->p[0] exists and not NUL, and
2633 * the peek2 result is in i->p[1].
2634 */
2635 if (i->p)
2636 return (unsigned char)i->p[1];
2637
2638 /* Now we know it is a file-based in_str. */
2639
2640 /* peek_buf[] is an int array, not char. Can contain EOF. */
2641 /* Is there 2nd char? */
2642 ch = i->peek_buf[1];
2643 if (ch == 0) {
2644 /* We did not read it yet, get it now */
2645 do ch = fgetc(i->file); while (ch == '\0');
2646 i->peek_buf[1] = ch;
2647 }
2648
2649 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2650 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002651}
2652
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002653static void setup_file_in_str(struct in_str *i, FILE *f)
2654{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002655 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002656 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002657 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002658 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002659}
2660
2661static void setup_string_in_str(struct in_str *i, const char *s)
2662{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002663 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002664 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002665 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002666 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002667}
2668
2669
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002670/*
2671 * o_string support
2672 */
2673#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002674
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002675static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002676{
2677 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002678 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002679 if (o->data)
2680 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002681}
2682
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002683static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002684{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002685 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002686 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002687}
2688
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002689static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2690{
2691 free(o->data);
2692}
2693
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002694static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002695{
2696 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002697 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002698 o->data = xrealloc(o->data, 1 + o->maxlen);
2699 }
2700}
2701
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002702static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002703{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002704 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002705 if (o->length < o->maxlen) {
2706 /* likely. avoid o_grow_by() call */
2707 add:
2708 o->data[o->length] = ch;
2709 o->length++;
2710 o->data[o->length] = '\0';
2711 return;
2712 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002713 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002714 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002715}
2716
Denys Vlasenko657086a2016-09-29 18:07:42 +02002717#if 0
2718/* Valid only if we know o_string is not empty */
2719static void o_delchr(o_string *o)
2720{
2721 o->length--;
2722 o->data[o->length] = '\0';
2723}
2724#endif
2725
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002726static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002727{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002728 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002729 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002730 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002731}
2732
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002733static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002734{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002735 o_addblock(o, str, strlen(str));
2736}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002737
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002738#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002739static void nommu_addchr(o_string *o, int ch)
2740{
2741 if (o)
2742 o_addchr(o, ch);
2743}
2744#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002745# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002746#endif
2747
2748static void o_addstr_with_NUL(o_string *o, const char *str)
2749{
2750 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002751}
2752
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002753/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002754 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002755 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2756 * Apparently, on unquoted $v bash still does globbing
2757 * ("v='*.txt'; echo $v" prints all .txt files),
2758 * but NOT brace expansion! Thus, there should be TWO independent
2759 * quoting mechanisms on $v expansion side: one protects
2760 * $v from brace expansion, and other additionally protects "$v" against globbing.
2761 * We have only second one.
2762 */
2763
Denys Vlasenko9e800222010-10-03 14:28:04 +02002764#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002765# define MAYBE_BRACES "{}"
2766#else
2767# define MAYBE_BRACES ""
2768#endif
2769
Eric Andersen25f27032001-04-26 23:22:31 +00002770/* My analysis of quoting semantics tells me that state information
2771 * is associated with a destination, not a source.
2772 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002773static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002774{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002775 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002776 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002777 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002778 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002779 o_grow_by(o, sz);
2780 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002781 o->data[o->length] = '\\';
2782 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002783 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002784 o->data[o->length] = ch;
2785 o->length++;
2786 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002787}
2788
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002789static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002790{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002791 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002792 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2793 && strchr("*?[\\" MAYBE_BRACES, ch)
2794 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002795 sz++;
2796 o->data[o->length] = '\\';
2797 o->length++;
2798 }
2799 o_grow_by(o, sz);
2800 o->data[o->length] = ch;
2801 o->length++;
2802 o->data[o->length] = '\0';
2803}
2804
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002805static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002806{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002807 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002808 char ch;
2809 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002810 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002811 if (ordinary_cnt > len) /* paranoia */
2812 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002813 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002814 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002815 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002816 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002817 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002818
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002819 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002820 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002821 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002822 sz++;
2823 o->data[o->length] = '\\';
2824 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002825 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002826 o_grow_by(o, sz);
2827 o->data[o->length] = ch;
2828 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002829 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002830 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002831}
2832
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002833static void o_addQblock(o_string *o, const char *str, int len)
2834{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002835 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002836 o_addblock(o, str, len);
2837 return;
2838 }
2839 o_addqblock(o, str, len);
2840}
2841
Denys Vlasenko38292b62010-09-05 14:49:40 +02002842static void o_addQstr(o_string *o, const char *str)
2843{
2844 o_addQblock(o, str, strlen(str));
2845}
2846
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002847/* A special kind of o_string for $VAR and `cmd` expansion.
2848 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002849 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002850 * list[i] contains an INDEX (int!) into this string data.
2851 * It means that if list[] needs to grow, data needs to be moved higher up
2852 * but list[i]'s need not be modified.
2853 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002854 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002855 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2856 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002857#if DEBUG_EXPAND || DEBUG_GLOB
2858static void debug_print_list(const char *prefix, o_string *o, int n)
2859{
2860 char **list = (char**)o->data;
2861 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2862 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002863
2864 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002865 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 +02002866 prefix, list, n, string_start, o->length, o->maxlen,
2867 !!(o->o_expflags & EXP_FLAG_GLOB),
2868 o->has_quoted_part,
2869 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002870 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002871 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002872 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2873 o->data + (int)(uintptr_t)list[i] + string_start,
2874 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002875 i++;
2876 }
2877 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002878 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002879 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002880 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002881 }
2882}
2883#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002884# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002885#endif
2886
2887/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2888 * in list[n] so that it points past last stored byte so far.
2889 * It returns n+1. */
2890static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002891{
2892 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002893 int string_start;
2894 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002895
2896 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002897 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2898 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002899 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002900 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002901 /* list[n] points to string_start, make space for 16 more pointers */
2902 o->maxlen += 0x10 * sizeof(list[0]);
2903 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002904 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002905 memmove(list + n + 0x10, list + n, string_len);
2906 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002907 } else {
2908 debug_printf_list("list[%d]=%d string_start=%d\n",
2909 n, string_len, string_start);
2910 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002911 } else {
2912 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002913 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2914 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002915 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2916 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002917 o->has_empty_slot = 0;
2918 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002919 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002920 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002921 return n + 1;
2922}
2923
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002924/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002925static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002926{
2927 char **list = (char**)o->data;
2928 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2929
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002930 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002931}
2932
Denys Vlasenko9e800222010-10-03 14:28:04 +02002933#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002934/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2935 * first, it processes even {a} (no commas), second,
2936 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002937 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002938 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002939
2940/* Helper */
2941static int glob_needed(const char *s)
2942{
2943 while (*s) {
2944 if (*s == '\\') {
2945 if (!s[1])
2946 return 0;
2947 s += 2;
2948 continue;
2949 }
2950 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2951 return 1;
2952 s++;
2953 }
2954 return 0;
2955}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002956/* Return pointer to next closing brace or to comma */
2957static const char *next_brace_sub(const char *cp)
2958{
2959 unsigned depth = 0;
2960 cp++;
2961 while (*cp != '\0') {
2962 if (*cp == '\\') {
2963 if (*++cp == '\0')
2964 break;
2965 cp++;
2966 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002967 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002968 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002969 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002970 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002971 depth++;
2972 }
2973
2974 return *cp != '\0' ? cp : NULL;
2975}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002976/* Recursive brace globber. Note: may garble pattern[]. */
2977static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002978{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002979 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002980 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002981 const char *next;
2982 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002983 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002984 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002985
2986 debug_printf_glob("glob_brace('%s')\n", pattern);
2987
2988 begin = pattern;
2989 while (1) {
2990 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002991 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002992 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002993 /* Find the first sub-pattern and at the same time
2994 * find the rest after the closing brace */
2995 next = next_brace_sub(begin);
2996 if (next == NULL) {
2997 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002998 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002999 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003000 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003001 /* "{abc}" with no commas - illegal
3002 * brace expr, disregard and skip it */
3003 begin = next + 1;
3004 continue;
3005 }
3006 break;
3007 }
3008 if (*begin == '\\' && begin[1] != '\0')
3009 begin++;
3010 begin++;
3011 }
3012 debug_printf_glob("begin:%s\n", begin);
3013 debug_printf_glob("next:%s\n", next);
3014
3015 /* Now find the end of the whole brace expression */
3016 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003017 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003018 rest = next_brace_sub(rest);
3019 if (rest == NULL) {
3020 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003021 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003022 }
3023 debug_printf_glob("rest:%s\n", rest);
3024 }
3025 rest_len = strlen(++rest) + 1;
3026
3027 /* We are sure the brace expression is well-formed */
3028
3029 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003030 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003031
3032 /* We have a brace expression. BEGIN points to the opening {,
3033 * NEXT points past the terminator of the first element, and REST
3034 * points past the final }. We will accumulate result names from
3035 * recursive runs for each brace alternative in the buffer using
3036 * GLOB_APPEND. */
3037
3038 p = begin + 1;
3039 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003040 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003041 memcpy(
3042 mempcpy(
3043 mempcpy(new_pattern_buf,
3044 /* We know the prefix for all sub-patterns */
3045 pattern, begin - pattern),
3046 p, next - p),
3047 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003048
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003049 /* Note: glob_brace() may garble new_pattern_buf[].
3050 * That's why we re-copy prefix every time (1st memcpy above).
3051 */
3052 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003053 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003054 /* We saw the last entry */
3055 break;
3056 }
3057 p = next + 1;
3058 next = next_brace_sub(next);
3059 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003060 free(new_pattern_buf);
3061 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003062
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003063 simple_glob:
3064 {
3065 int gr;
3066 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003067
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003068 memset(&globdata, 0, sizeof(globdata));
3069 gr = glob(pattern, 0, NULL, &globdata);
3070 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3071 if (gr != 0) {
3072 if (gr == GLOB_NOMATCH) {
3073 globfree(&globdata);
3074 /* NB: garbles parameter */
3075 unbackslash(pattern);
3076 o_addstr_with_NUL(o, pattern);
3077 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3078 return o_save_ptr_helper(o, n);
3079 }
3080 if (gr == GLOB_NOSPACE)
3081 bb_error_msg_and_die(bb_msg_memory_exhausted);
3082 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3083 * but we didn't specify it. Paranoia again. */
3084 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3085 }
3086 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3087 char **argv = globdata.gl_pathv;
3088 while (1) {
3089 o_addstr_with_NUL(o, *argv);
3090 n = o_save_ptr_helper(o, n);
3091 argv++;
3092 if (!*argv)
3093 break;
3094 }
3095 }
3096 globfree(&globdata);
3097 }
3098 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003099}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003100/* Performs globbing on last list[],
3101 * saving each result as a new list[].
3102 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003103static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003104{
3105 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003106
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003107 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003108 if (!o->data)
3109 return o_save_ptr_helper(o, n);
3110 pattern = o->data + o_get_last_ptr(o, n);
3111 debug_printf_glob("glob pattern '%s'\n", pattern);
3112 if (!glob_needed(pattern)) {
3113 /* unbackslash last string in o in place, fix length */
3114 o->length = unbackslash(pattern) - o->data;
3115 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3116 return o_save_ptr_helper(o, n);
3117 }
3118
3119 copy = xstrdup(pattern);
3120 /* "forget" pattern in o */
3121 o->length = pattern - o->data;
3122 n = glob_brace(copy, o, n);
3123 free(copy);
3124 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003125 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003126 return n;
3127}
3128
Denys Vlasenko238081f2010-10-03 14:26:26 +02003129#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003130
3131/* Helper */
3132static int glob_needed(const char *s)
3133{
3134 while (*s) {
3135 if (*s == '\\') {
3136 if (!s[1])
3137 return 0;
3138 s += 2;
3139 continue;
3140 }
3141 if (*s == '*' || *s == '[' || *s == '?')
3142 return 1;
3143 s++;
3144 }
3145 return 0;
3146}
3147/* Performs globbing on last list[],
3148 * saving each result as a new list[].
3149 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003150static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003151{
3152 glob_t globdata;
3153 int gr;
3154 char *pattern;
3155
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003156 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003157 if (!o->data)
3158 return o_save_ptr_helper(o, n);
3159 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003160 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003161 if (!glob_needed(pattern)) {
3162 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003163 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003164 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003165 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003166 return o_save_ptr_helper(o, n);
3167 }
3168
3169 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003170 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3171 * If we glob "*.\*" and don't find anything, we need
3172 * to fall back to using literal "*.*", but GLOB_NOCHECK
3173 * will return "*.\*"!
3174 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003175 gr = glob(pattern, 0, NULL, &globdata);
3176 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003177 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003178 if (gr == GLOB_NOMATCH) {
3179 globfree(&globdata);
3180 goto literal;
3181 }
3182 if (gr == GLOB_NOSPACE)
3183 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003184 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3185 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003186 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003187 }
3188 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3189 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003190 /* "forget" pattern in o */
3191 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003192 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003193 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003194 n = o_save_ptr_helper(o, n);
3195 argv++;
3196 if (!*argv)
3197 break;
3198 }
3199 }
3200 globfree(&globdata);
3201 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003202 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003203 return n;
3204}
3205
Denys Vlasenko238081f2010-10-03 14:26:26 +02003206#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003207
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003208/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003209 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003210static int o_save_ptr(o_string *o, int n)
3211{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003212 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003213 /* If o->has_empty_slot, list[n] was already globbed
3214 * (if it was requested back then when it was filled)
3215 * so don't do that again! */
3216 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003217 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003218 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003219 return o_save_ptr_helper(o, n);
3220}
3221
3222/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003223static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003224{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003225 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003226 int string_start;
3227
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003228 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3229 if (DEBUG_EXPAND)
3230 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003231 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003232 list = (char**)o->data;
3233 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3234 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003235 while (n) {
3236 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003237 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003238 }
3239 return list;
3240}
3241
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003242static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003243
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003244/* Returns pi->next - next pipe in the list */
3245static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003246{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003247 struct pipe *next;
3248 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003249
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003250 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003251 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003252 struct command *command;
3253 struct redir_struct *r, *rnext;
3254
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003255 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003256 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003257 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003258 if (DEBUG_CLEAN) {
3259 int a;
3260 char **p;
3261 for (a = 0, p = command->argv; *p; a++, p++) {
3262 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3263 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003264 }
3265 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003266 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003267 }
3268 /* not "else if": on syntax error, we may have both! */
3269 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003270 debug_printf_clean(" begin group (cmd_type:%d)\n",
3271 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003272 free_pipe_list(command->group);
3273 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003274 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003275 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003276 /* else is crucial here.
3277 * If group != NULL, child_func is meaningless */
3278#if ENABLE_HUSH_FUNCTIONS
3279 else if (command->child_func) {
3280 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3281 command->child_func->parent_cmd = NULL;
3282 }
3283#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003284#if !BB_MMU
3285 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003286 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003287#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003288 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003289 debug_printf_clean(" redirect %d%s",
3290 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003291 /* guard against the case >$FOO, where foo is unset or blank */
3292 if (r->rd_filename) {
3293 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3294 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003295 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003296 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003297 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003298 rnext = r->next;
3299 free(r);
3300 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003301 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003302 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003303 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003304 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003305#if ENABLE_HUSH_JOB
3306 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003307 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003308#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003309
3310 next = pi->next;
3311 free(pi);
3312 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003313}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003314
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003315static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003316{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003317 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003318#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003319 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003320#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003321 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003322 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003323 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003324}
3325
3326
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003327/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003328
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003329#ifndef debug_print_tree
3330static void debug_print_tree(struct pipe *pi, int lvl)
3331{
3332 static const char *const PIPE[] = {
3333 [PIPE_SEQ] = "SEQ",
3334 [PIPE_AND] = "AND",
3335 [PIPE_OR ] = "OR" ,
3336 [PIPE_BG ] = "BG" ,
3337 };
3338 static const char *RES[] = {
3339 [RES_NONE ] = "NONE" ,
3340# if ENABLE_HUSH_IF
3341 [RES_IF ] = "IF" ,
3342 [RES_THEN ] = "THEN" ,
3343 [RES_ELIF ] = "ELIF" ,
3344 [RES_ELSE ] = "ELSE" ,
3345 [RES_FI ] = "FI" ,
3346# endif
3347# if ENABLE_HUSH_LOOPS
3348 [RES_FOR ] = "FOR" ,
3349 [RES_WHILE] = "WHILE",
3350 [RES_UNTIL] = "UNTIL",
3351 [RES_DO ] = "DO" ,
3352 [RES_DONE ] = "DONE" ,
3353# endif
3354# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3355 [RES_IN ] = "IN" ,
3356# endif
3357# if ENABLE_HUSH_CASE
3358 [RES_CASE ] = "CASE" ,
3359 [RES_CASE_IN ] = "CASE_IN" ,
3360 [RES_MATCH] = "MATCH",
3361 [RES_CASE_BODY] = "CASE_BODY",
3362 [RES_ESAC ] = "ESAC" ,
3363# endif
3364 [RES_XXXX ] = "XXXX" ,
3365 [RES_SNTX ] = "SNTX" ,
3366 };
3367 static const char *const CMDTYPE[] = {
3368 "{}",
3369 "()",
3370 "[noglob]",
3371# if ENABLE_HUSH_FUNCTIONS
3372 "func()",
3373# endif
3374 };
3375
3376 int pin, prn;
3377
3378 pin = 0;
3379 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003380 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003381 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3382 prn = 0;
3383 while (prn < pi->num_cmds) {
3384 struct command *command = &pi->cmds[prn];
3385 char **argv = command->argv;
3386
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003387 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003388 lvl*2, "", prn,
3389 command->assignment_cnt);
3390 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003391 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003392 CMDTYPE[command->cmd_type],
3393 argv
3394# if !BB_MMU
3395 , " group_as_string:", command->group_as_string
3396# else
3397 , "", ""
3398# endif
3399 );
3400 debug_print_tree(command->group, lvl+1);
3401 prn++;
3402 continue;
3403 }
3404 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003405 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003406 argv++;
3407 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003408 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003409 prn++;
3410 }
3411 pi = pi->next;
3412 pin++;
3413 }
3414}
3415#endif /* debug_print_tree */
3416
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003417static struct pipe *new_pipe(void)
3418{
Eric Andersen25f27032001-04-26 23:22:31 +00003419 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003420 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003421 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003422 return pi;
3423}
3424
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003425/* Command (member of a pipe) is complete, or we start a new pipe
3426 * if ctx->command is NULL.
3427 * No errors possible here.
3428 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003429static int done_command(struct parse_context *ctx)
3430{
3431 /* The command is really already in the pipe structure, so
3432 * advance the pipe counter and make a new, null command. */
3433 struct pipe *pi = ctx->pipe;
3434 struct command *command = ctx->command;
3435
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003436#if 0 /* Instead we emit error message at run time */
3437 if (ctx->pending_redirect) {
3438 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003439 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003440 ctx->pending_redirect = NULL;
3441 }
3442#endif
3443
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003444 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003445 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003446 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003447 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003448 }
3449 pi->num_cmds++;
3450 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003451 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003452 } else {
3453 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3454 }
3455
3456 /* Only real trickiness here is that the uncommitted
3457 * command structure is not counted in pi->num_cmds. */
3458 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003459 ctx->command = command = &pi->cmds[pi->num_cmds];
3460 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003461 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003462 return pi->num_cmds; /* used only for 0/nonzero check */
3463}
3464
3465static void done_pipe(struct parse_context *ctx, pipe_style type)
3466{
3467 int not_null;
3468
3469 debug_printf_parse("done_pipe entered, followup %d\n", type);
3470 /* Close previous command */
3471 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003472#if HAS_KEYWORDS
3473 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3474 ctx->ctx_inverted = 0;
3475 ctx->pipe->res_word = ctx->ctx_res_w;
3476#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003477 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3478 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003479 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3480 * in a backgrounded subshell.
3481 */
3482 struct pipe *pi;
3483 struct command *command;
3484
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003485 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003486 pi = ctx->list_head;
3487 while (pi != ctx->pipe) {
3488 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3489 goto no_conv;
3490 pi = pi->next;
3491 }
3492
3493 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3494 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3495 pi = xzalloc(sizeof(*pi));
3496 pi->followup = PIPE_BG;
3497 pi->num_cmds = 1;
3498 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3499 command = &pi->cmds[0];
3500 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3501 command->cmd_type = CMD_NORMAL;
3502 command->group = ctx->list_head;
3503#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003504 command->group_as_string = xstrndup(
3505 ctx->as_string.data,
3506 ctx->as_string.length - 1 /* do not copy last char, "&" */
3507 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003508#endif
3509 /* Replace all pipes in ctx with one newly created */
3510 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003511 } else {
3512 no_conv:
3513 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003514 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003515
3516 /* Without this check, even just <enter> on command line generates
3517 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003518 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003519 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003520#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003521 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003522#endif
3523#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003524 || ctx->ctx_res_w == RES_DONE
3525 || ctx->ctx_res_w == RES_FOR
3526 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003527#endif
3528#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003529 || ctx->ctx_res_w == RES_ESAC
3530#endif
3531 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003532 struct pipe *new_p;
3533 debug_printf_parse("done_pipe: adding new pipe: "
3534 "not_null:%d ctx->ctx_res_w:%d\n",
3535 not_null, ctx->ctx_res_w);
3536 new_p = new_pipe();
3537 ctx->pipe->next = new_p;
3538 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003539 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003540 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003541 * This is used to control execution.
3542 * RES_FOR and RES_IN are NOT sticky (needed to support
3543 * cases where variable or value happens to match a keyword):
3544 */
3545#if ENABLE_HUSH_LOOPS
3546 if (ctx->ctx_res_w == RES_FOR
3547 || ctx->ctx_res_w == RES_IN)
3548 ctx->ctx_res_w = RES_NONE;
3549#endif
3550#if ENABLE_HUSH_CASE
3551 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003552 ctx->ctx_res_w = RES_CASE_BODY;
3553 if (ctx->ctx_res_w == RES_CASE)
3554 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003555#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003556 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003557 /* Create the memory for command, roughly:
3558 * ctx->pipe->cmds = new struct command;
3559 * ctx->command = &ctx->pipe->cmds[0];
3560 */
3561 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003562 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003563 }
3564 debug_printf_parse("done_pipe return\n");
3565}
3566
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003567static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003568{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003569 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003570 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003571 /* Create the memory for command, roughly:
3572 * ctx->pipe->cmds = new struct command;
3573 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003574 */
3575 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003576}
3577
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003578/* If a reserved word is found and processed, parse context is modified
3579 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003580 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003581#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003582struct reserved_combo {
3583 char literal[6];
3584 unsigned char res;
3585 unsigned char assignment_flag;
3586 int flag;
3587};
3588enum {
3589 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003590# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003591 FLAG_IF = (1 << RES_IF ),
3592 FLAG_THEN = (1 << RES_THEN ),
3593 FLAG_ELIF = (1 << RES_ELIF ),
3594 FLAG_ELSE = (1 << RES_ELSE ),
3595 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003596# endif
3597# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003598 FLAG_FOR = (1 << RES_FOR ),
3599 FLAG_WHILE = (1 << RES_WHILE),
3600 FLAG_UNTIL = (1 << RES_UNTIL),
3601 FLAG_DO = (1 << RES_DO ),
3602 FLAG_DONE = (1 << RES_DONE ),
3603 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003604# endif
3605# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003606 FLAG_MATCH = (1 << RES_MATCH),
3607 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003608# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003609 FLAG_START = (1 << RES_XXXX ),
3610};
3611
3612static const struct reserved_combo* match_reserved_word(o_string *word)
3613{
Eric Andersen25f27032001-04-26 23:22:31 +00003614 /* Mostly a list of accepted follow-up reserved words.
3615 * FLAG_END means we are done with the sequence, and are ready
3616 * to turn the compound list into a command.
3617 * FLAG_START means the word must start a new compound list.
3618 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003619 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003620# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003621 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3622 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3623 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3624 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3625 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3626 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003627# endif
3628# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003629 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3630 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3631 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3632 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3633 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3634 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003635# endif
3636# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003637 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3638 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003639# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003640 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003641 const struct reserved_combo *r;
3642
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003643 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003644 if (strcmp(word->data, r->literal) == 0)
3645 return r;
3646 }
3647 return NULL;
3648}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003649/* Return 0: not a keyword, 1: keyword
3650 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003651static int reserved_word(o_string *word, struct parse_context *ctx)
3652{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003653# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003654 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003655 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003656 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003657# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003658 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003659
Denys Vlasenko38292b62010-09-05 14:49:40 +02003660 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003661 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003662 r = match_reserved_word(word);
3663 if (!r)
3664 return 0;
3665
3666 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003667# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003668 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3669 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003670 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003671 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003672# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003673 if (r->flag == 0) { /* '!' */
3674 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003675 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003676 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003677 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003678 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003679 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003680 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003681 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003682 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003683
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003684 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003685 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003686 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003687 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003688 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003689 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003690 ctx->ctx_res_w = RES_SNTX;
3691 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003692 } else {
3693 /* "{...} fi" is ok. "{...} if" is not
3694 * Example:
3695 * if { echo foo; } then { echo bar; } fi */
3696 if (ctx->command->group)
3697 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003698 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003699
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003700 ctx->ctx_res_w = r->res;
3701 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003702 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003703 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003704
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003705 if (ctx->old_flag & FLAG_END) {
3706 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003707
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003708 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003709 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003710 old = ctx->stack;
3711 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003712 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003713# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003714 /* At this point, the compound command's string is in
3715 * ctx->as_string... except for the leading keyword!
3716 * Consider this example: "echo a | if true; then echo a; fi"
3717 * ctx->as_string will contain "true; then echo a; fi",
3718 * with "if " remaining in old->as_string!
3719 */
3720 {
3721 char *str;
3722 int len = old->as_string.length;
3723 /* Concatenate halves */
3724 o_addstr(&old->as_string, ctx->as_string.data);
3725 o_free_unsafe(&ctx->as_string);
3726 /* Find where leading keyword starts in first half */
3727 str = old->as_string.data + len;
3728 if (str > old->as_string.data)
3729 str--; /* skip whitespace after keyword */
3730 while (str > old->as_string.data && isalpha(str[-1]))
3731 str--;
3732 /* Ugh, we're done with this horrid hack */
3733 old->command->group_as_string = xstrdup(str);
3734 debug_printf_parse("pop, remembering as:'%s'\n",
3735 old->command->group_as_string);
3736 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003737# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003738 *ctx = *old; /* physical copy */
3739 free(old);
3740 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003741 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003742}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003743#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003744
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003745/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003746 * Normal return is 0. Syntax errors return 1.
3747 * Note: on return, word is reset, but not o_free'd!
3748 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003749static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003750{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003751 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003752
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003753 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003754 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003755 debug_printf_parse("done_word return 0: true null, ignored\n");
3756 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003757 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003758
Eric Andersen25f27032001-04-26 23:22:31 +00003759 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003760 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3761 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003762 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3763 * "2.7 Redirection
3764 * ...the word that follows the redirection operator
3765 * shall be subjected to tilde expansion, parameter expansion,
3766 * command substitution, arithmetic expansion, and quote
3767 * removal. Pathname expansion shall not be performed
3768 * on the word by a non-interactive shell; an interactive
3769 * shell may perform it, but shall do so only when
3770 * the expansion would result in one word."
3771 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003772 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003773 /* Cater for >\file case:
3774 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3775 * Same with heredocs:
3776 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3777 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003778 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3779 unbackslash(ctx->pending_redirect->rd_filename);
3780 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003781 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003782 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3783 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003784 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003785 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003786 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003787 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003788#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003789# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003790 if (ctx->ctx_dsemicolon
3791 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3792 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003793 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003794 /* ctx->ctx_res_w = RES_MATCH; */
3795 ctx->ctx_dsemicolon = 0;
3796 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003797# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003798 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003799# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003800 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3801 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003802# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003803# if ENABLE_HUSH_CASE
3804 && ctx->ctx_res_w != RES_CASE
3805# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003806 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003807 int reserved = reserved_word(word, ctx);
3808 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3809 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003810 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003811 debug_printf_parse("done_word return %d\n",
3812 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003813 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003814 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01003815# if BASH_TEST2
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003816 if (strcmp(word->data, "[[") == 0) {
3817 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3818 }
3819 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003820# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003821 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003822#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003823 if (command->group) {
3824 /* "{ echo foo; } echo bar" - bad */
3825 syntax_error_at(word->data);
3826 debug_printf_parse("done_word return 1: syntax error, "
3827 "groups and arglists don't mix\n");
3828 return 1;
3829 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003830
3831 /* If this word wasn't an assignment, next ones definitely
3832 * can't be assignments. Even if they look like ones. */
3833 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3834 && word->o_assignment != WORD_IS_KEYWORD
3835 ) {
3836 word->o_assignment = NOT_ASSIGNMENT;
3837 } else {
3838 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3839 command->assignment_cnt++;
3840 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3841 }
3842 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3843 word->o_assignment = MAYBE_ASSIGNMENT;
3844 }
3845 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003846 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003847 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003848 }
Eric Andersen25f27032001-04-26 23:22:31 +00003849
Denis Vlasenko06810332007-05-21 23:30:54 +00003850#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003851 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003852 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003853 || !is_well_formed_var_name(command->argv[0], '\0')
3854 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003855 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003856 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003857 return 1;
3858 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003859 /* Force FOR to have just one word (variable name) */
3860 /* NB: basically, this makes hush see "for v in ..."
3861 * syntax as if it is "for v; in ...". FOR and IN become
3862 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003863 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003864 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003865#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003866#if ENABLE_HUSH_CASE
3867 /* Force CASE to have just one word */
3868 if (ctx->ctx_res_w == RES_CASE) {
3869 done_pipe(ctx, PIPE_SEQ);
3870 }
3871#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003872
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003873 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003874
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003875 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003876 return 0;
3877}
3878
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003879
3880/* Peek ahead in the input to find out if we have a "&n" construct,
3881 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003882 * Return:
3883 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3884 * REDIRFD_SYNTAX_ERR if syntax error,
3885 * REDIRFD_TO_FILE if no & was seen,
3886 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003887 */
3888#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003889#define parse_redir_right_fd(as_string, input) \
3890 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003891#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003892static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003893{
3894 int ch, d, ok;
3895
3896 ch = i_peek(input);
3897 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003898 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003899
3900 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003901 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003902 ch = i_peek(input);
3903 if (ch == '-') {
3904 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003905 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003906 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003907 }
3908 d = 0;
3909 ok = 0;
3910 while (ch != EOF && isdigit(ch)) {
3911 d = d*10 + (ch-'0');
3912 ok = 1;
3913 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003914 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003915 ch = i_peek(input);
3916 }
3917 if (ok) return d;
3918
3919//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3920
3921 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003922 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003923}
3924
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003925/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003926 */
3927static int parse_redirect(struct parse_context *ctx,
3928 int fd,
3929 redir_type style,
3930 struct in_str *input)
3931{
3932 struct command *command = ctx->command;
3933 struct redir_struct *redir;
3934 struct redir_struct **redirp;
3935 int dup_num;
3936
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003937 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003938 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003939 /* Check for a '>&1' type redirect */
3940 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3941 if (dup_num == REDIRFD_SYNTAX_ERR)
3942 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003943 } else {
3944 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003945 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003946 if (dup_num) { /* <<-... */
3947 ch = i_getch(input);
3948 nommu_addchr(&ctx->as_string, ch);
3949 ch = i_peek(input);
3950 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003951 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003952
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003953 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003954 int ch = i_peek(input);
3955 if (ch == '|') {
3956 /* >|FILE redirect ("clobbering" >).
3957 * Since we do not support "set -o noclobber" yet,
3958 * >| and > are the same for now. Just eat |.
3959 */
3960 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003961 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003962 }
3963 }
3964
3965 /* Create a new redir_struct and append it to the linked list */
3966 redirp = &command->redirects;
3967 while ((redir = *redirp) != NULL) {
3968 redirp = &(redir->next);
3969 }
3970 *redirp = redir = xzalloc(sizeof(*redir));
3971 /* redir->next = NULL; */
3972 /* redir->rd_filename = NULL; */
3973 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003974 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003975
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003976 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3977 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003978
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003979 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003980 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003981 /* Erik had a check here that the file descriptor in question
3982 * is legit; I postpone that to "run time"
3983 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003984 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3985 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003986 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003987#if 0 /* Instead we emit error message at run time */
3988 if (ctx->pending_redirect) {
3989 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02003990 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003991 }
3992#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003993 /* Set ctx->pending_redirect, so we know what to do at the
3994 * end of the next parsed word. */
3995 ctx->pending_redirect = redir;
3996 }
3997 return 0;
3998}
3999
Eric Andersen25f27032001-04-26 23:22:31 +00004000/* If a redirect is immediately preceded by a number, that number is
4001 * supposed to tell which file descriptor to redirect. This routine
4002 * looks for such preceding numbers. In an ideal world this routine
4003 * needs to handle all the following classes of redirects...
4004 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4005 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4006 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4007 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004008 *
4009 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4010 * "2.7 Redirection
4011 * ... If n is quoted, the number shall not be recognized as part of
4012 * the redirection expression. For example:
4013 * echo \2>a
4014 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004015 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004016 *
4017 * A -1 return means no valid number was found,
4018 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004019 */
4020static int redirect_opt_num(o_string *o)
4021{
4022 int num;
4023
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004024 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004025 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004026 num = bb_strtou(o->data, NULL, 10);
4027 if (errno || num < 0)
4028 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004029 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004030 return num;
4031}
4032
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004033#if BB_MMU
4034#define fetch_till_str(as_string, input, word, skip_tabs) \
4035 fetch_till_str(input, word, skip_tabs)
4036#endif
4037static char *fetch_till_str(o_string *as_string,
4038 struct in_str *input,
4039 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004040 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004041{
4042 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004043 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004044 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004045 int ch;
4046
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004047 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004048
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004049 while (1) {
4050 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004051 if (ch != EOF)
4052 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004053 if (ch == '\n' || ch == EOF) {
4054 check_heredoc_end:
4055 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4056 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4057 heredoc.data[past_EOL] = '\0';
4058 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4059 return heredoc.data;
4060 }
4061 if (ch == '\n') {
4062 /* This is a new line.
4063 * Remember position and backslash-escaping status.
4064 */
4065 o_addchr(&heredoc, ch);
4066 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004067 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004068 past_EOL = heredoc.length;
4069 /* Get 1st char of next line, possibly skipping leading tabs */
4070 do {
4071 ch = i_getch(input);
4072 if (ch != EOF)
4073 nommu_addchr(as_string, ch);
4074 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4075 /* If this immediately ended the line,
4076 * go back to end-of-line checks.
4077 */
4078 if (ch == '\n')
4079 goto check_heredoc_end;
4080 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004081 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004082 }
4083 if (ch == EOF) {
4084 o_free_unsafe(&heredoc);
4085 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004086 }
4087 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004088 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004089 if (prev == '\\' && ch == '\\')
4090 /* Correctly handle foo\\<eol> (not a line cont.) */
4091 prev = 0; /* not \ */
4092 else
4093 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004094 }
4095}
4096
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004097/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4098 * and load them all. There should be exactly heredoc_cnt of them.
4099 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004100static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4101{
4102 struct pipe *pi = ctx->list_head;
4103
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004104 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004105 int i;
4106 struct command *cmd = pi->cmds;
4107
4108 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4109 pi->num_cmds,
4110 cmd->argv ? cmd->argv[0] : "NONE");
4111 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004112 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004113
4114 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4115 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004116 while (redir) {
4117 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004118 char *p;
4119
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004120 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004121 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004122 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004123 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004124 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004125 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004126 return 1;
4127 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004128 free(redir->rd_filename);
4129 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004130 heredoc_cnt--;
4131 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004132 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004133 }
4134 cmd++;
4135 }
4136 pi = pi->next;
4137 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004138#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004139 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004140 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004141 bb_error_msg_and_die("heredoc BUG 2");
4142#endif
4143 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004144}
4145
4146
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004147static int run_list(struct pipe *pi);
4148#if BB_MMU
4149#define parse_stream(pstring, input, end_trigger) \
4150 parse_stream(input, end_trigger)
4151#endif
4152static struct pipe *parse_stream(char **pstring,
4153 struct in_str *input,
4154 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004155
Eric Andersen25f27032001-04-26 23:22:31 +00004156
Denys Vlasenkoc2704542009-11-20 19:14:19 +01004157#if !ENABLE_HUSH_FUNCTIONS
4158#define parse_group(dest, ctx, input, ch) \
4159 parse_group(ctx, input, ch)
4160#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004161static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004162 struct in_str *input, int ch)
4163{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004164 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004165 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004166 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004167 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004168 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004169 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004170
4171 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004172#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02004173 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004174 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004175 if (done_word(dest, ctx))
4176 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004177 if (!command->argv)
4178 goto skip; /* (... */
4179 if (command->argv[1]) { /* word word ... (... */
4180 syntax_error_unexpected_ch('(');
4181 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004182 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004183 /* it is "word(..." or "word (..." */
4184 do
4185 ch = i_getch(input);
4186 while (ch == ' ' || ch == '\t');
4187 if (ch != ')') {
4188 syntax_error_unexpected_ch(ch);
4189 return 1;
4190 }
4191 nommu_addchr(&ctx->as_string, ch);
4192 do
4193 ch = i_getch(input);
4194 while (ch == ' ' || ch == '\t' || ch == '\n');
4195 if (ch != '{') {
4196 syntax_error_unexpected_ch(ch);
4197 return 1;
4198 }
4199 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004200 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004201 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004202 }
4203#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004204
4205#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004206 if (command->argv /* word [word]{... */
4207 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004208 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004209 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004210 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004211 debug_printf_parse("parse_group return 1: "
4212 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004213 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004214 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004215#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004216
4217#if ENABLE_HUSH_FUNCTIONS
4218 skip:
4219#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004220 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004221 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004222 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004223 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004224 } else {
4225 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004226 ch = i_peek(input);
4227 if (ch != ' ' && ch != '\t' && ch != '\n'
4228 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4229 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004230 syntax_error_unexpected_ch(ch);
4231 return 1;
4232 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004233 if (ch != '(') {
4234 ch = i_getch(input);
4235 nommu_addchr(&ctx->as_string, ch);
4236 }
Eric Andersen25f27032001-04-26 23:22:31 +00004237 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004238
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004239 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004240#if BB_MMU
4241# define as_string NULL
4242#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004243 char *as_string = NULL;
4244#endif
4245 pipe_list = parse_stream(&as_string, input, endch);
4246#if !BB_MMU
4247 if (as_string)
4248 o_addstr(&ctx->as_string, as_string);
4249#endif
4250 /* empty ()/{} or parse error? */
4251 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00004252 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004253 if (!BB_MMU)
4254 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004255 debug_printf_parse("parse_group return 1: "
4256 "parse_stream returned %p\n", pipe_list);
4257 return 1;
4258 }
4259 command->group = pipe_list;
4260#if !BB_MMU
4261 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4262 command->group_as_string = as_string;
4263 debug_printf_parse("end of group, remembering as:'%s'\n",
4264 command->group_as_string);
4265#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004266#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004267 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004268 debug_printf_parse("parse_group return 0\n");
4269 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004270 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004271}
4272
Denys Vlasenko46e64982016-09-29 19:50:55 +02004273static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4274{
4275 for (;;) {
4276 int ch, ch2;
4277
4278 ch = i_getch(input);
4279 if (ch != '\\')
4280 return ch;
4281 ch2 = i_peek(input);
4282 if (ch2 != '\n')
4283 return ch;
4284 /* backslash+newline, skip it */
4285 i_getch(input);
4286 }
4287}
4288
Denys Vlasenko657086a2016-09-29 18:07:42 +02004289static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4290{
4291 for (;;) {
4292 int ch, ch2;
4293
4294 ch = i_peek(input);
4295 if (ch != '\\')
4296 return ch;
4297 ch2 = i_peek2(input);
4298 if (ch2 != '\n')
4299 return ch;
4300 /* backslash+newline, skip it */
4301 i_getch(input);
4302 i_getch(input);
4303 }
4304}
4305
Denys Vlasenko0b883582016-12-23 16:49:07 +01004306#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004307/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004308static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004309/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004310static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004311{
4312 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004313 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004314 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004315 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004316 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004317 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004318 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004319 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004320 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004321 }
4322}
4323/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004324static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004325{
4326 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004327 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004328 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004329 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004330 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004331 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004332 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004333 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004334 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004335 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004336 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004337 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004338 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004339 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004340 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4341 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004342 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004343 continue;
4344 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004345 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004346 }
4347}
4348/* Process `cmd` - copy contents until "`" is seen. Complicated by
4349 * \` quoting.
4350 * "Within the backquoted style of command substitution, backslash
4351 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4352 * The search for the matching backquote shall be satisfied by the first
4353 * backquote found without a preceding backslash; during this search,
4354 * if a non-escaped backquote is encountered within a shell comment,
4355 * a here-document, an embedded command substitution of the $(command)
4356 * form, or a quoted string, undefined results occur. A single-quoted
4357 * or double-quoted string that begins, but does not end, within the
4358 * "`...`" sequence produces undefined results."
4359 * Example Output
4360 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4361 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004362static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004363{
4364 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004365 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004366 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004367 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004368 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004369 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4370 ch = i_getch(input);
4371 if (ch != '`'
4372 && ch != '$'
4373 && ch != '\\'
4374 && (!in_dquote || ch != '"')
4375 ) {
4376 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004377 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004378 }
4379 if (ch == EOF) {
4380 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004381 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004382 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004383 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004384 }
4385}
4386/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4387 * quoting and nested ()s.
4388 * "With the $(command) style of command substitution, all characters
4389 * following the open parenthesis to the matching closing parenthesis
4390 * constitute the command. Any valid shell script can be used for command,
4391 * except a script consisting solely of redirections which produces
4392 * unspecified results."
4393 * Example Output
4394 * echo $(echo '(TEST)' BEST) (TEST) BEST
4395 * echo $(echo 'TEST)' BEST) TEST) BEST
4396 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004397 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004398 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004399 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004400 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4401 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004402 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004403#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004404static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004405{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004406 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004407 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004408# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004409 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004410# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004411 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4412
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004413 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004414 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004415 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004416 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004417 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004418 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004419 if (ch == end_ch
4420# if BASH_SUBSTR || BASH_PATTERN_SUBST
4421 || ch == end_char2
4422# endif
4423 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004424 if (!dbl)
4425 break;
4426 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004427 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004428 i_getch(input); /* eat second ')' */
4429 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004430 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004431 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004432 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004433 if (ch == '(' || ch == '{') {
4434 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004435 if (!add_till_closing_bracket(dest, input, ch))
4436 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004437 o_addchr(dest, ch);
4438 continue;
4439 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004440 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004441 if (!add_till_single_quote(dest, input))
4442 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004443 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004444 continue;
4445 }
4446 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004447 if (!add_till_double_quote(dest, input))
4448 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004449 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004450 continue;
4451 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004452 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004453 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4454 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004455 o_addchr(dest, ch);
4456 continue;
4457 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004458 if (ch == '\\') {
4459 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004460 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004461 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004462 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004463 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004464 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004465#if 0
4466 if (ch == '\n') {
4467 /* "backslash+newline", ignore both */
4468 o_delchr(dest); /* undo insertion of '\' */
4469 continue;
4470 }
4471#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004472 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004473 continue;
4474 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004475 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004476 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004477}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004478#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004479
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004480/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004481#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004482#define parse_dollar(as_string, dest, input, quote_mask) \
4483 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004484#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004485#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004486static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004487 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004488 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004489{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004490 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004491
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004492 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004493 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004494 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004495 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004496 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004497 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004498 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004499 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004500 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004501 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004502 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004503 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004504 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004505 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004506 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004507 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004508 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004509 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004510 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004511 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004512 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004513 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004514 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004515 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004516 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004517 o_addchr(dest, ch | quote_mask);
4518 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004519 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004520 case '$': /* pid */
4521 case '!': /* last bg pid */
4522 case '?': /* last exit code */
4523 case '#': /* number of args */
4524 case '*': /* args */
4525 case '@': /* args */
4526 goto make_one_char_var;
4527 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004528 char len_single_ch;
4529
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004530 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4531
Denys Vlasenko74369502010-05-21 19:52:01 +02004532 ch = i_getch(input); /* eat '{' */
4533 nommu_addchr(as_string, ch);
4534
Denys Vlasenko46e64982016-09-29 19:50:55 +02004535 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004536 /* It should be ${?}, or ${#var},
4537 * or even ${?+subst} - operator acting on a special variable,
4538 * or the beginning of variable name.
4539 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004540 if (ch == EOF
4541 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4542 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004543 bad_dollar_syntax:
4544 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004545 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4546 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004547 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004548 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004549 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004550 ch |= quote_mask;
4551
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004552 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004553 * However, this regresses some of our testsuite cases
4554 * which check invalid constructs like ${%}.
4555 * Oh well... let's check that the var name part is fine... */
4556
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004557 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004558 unsigned pos;
4559
Denys Vlasenko74369502010-05-21 19:52:01 +02004560 o_addchr(dest, ch);
4561 debug_printf_parse(": '%c'\n", ch);
4562
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004563 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004564 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004565 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004566 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004567
Denys Vlasenko74369502010-05-21 19:52:01 +02004568 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004569 unsigned end_ch;
4570 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004571 /* handle parameter expansions
4572 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4573 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004574 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4575 if (len_single_ch != '#'
4576 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4577 || i_peek(input) != '}'
4578 ) {
4579 goto bad_dollar_syntax;
4580 }
4581 /* else: it's "length of C" ${#C} op,
4582 * where C is a single char
4583 * special var name, e.g. ${#!}.
4584 */
4585 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004586 /* Eat everything until closing '}' (or ':') */
4587 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004588 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004589 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004590 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004591 ) {
4592 /* It's ${var:N[:M]} thing */
4593 end_ch = '}' * 0x100 + ':';
4594 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004595 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004596 && ch == '/'
4597 ) {
4598 /* It's ${var/[/]pattern[/repl]} thing */
4599 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4600 i_getch(input);
4601 nommu_addchr(as_string, '/');
4602 ch = '\\';
4603 }
4604 end_ch = '}' * 0x100 + '/';
4605 }
4606 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004607 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004608 if (!BB_MMU)
4609 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004610#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004611 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004612 if (last_ch == 0) /* error? */
4613 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004614#else
4615#error Simple code to only allow ${var} is not implemented
4616#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004617 if (as_string) {
4618 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004619 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004620 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004621
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004622 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4623 && (end_ch & 0xff00)
4624 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004625 /* close the first block: */
4626 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004627 /* while parsing N from ${var:N[:M]}
4628 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004629 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004630 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004631 end_ch = '}';
4632 goto again;
4633 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004634 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004635 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004636 /* it's ${var:N} - emulate :999999999 */
4637 o_addstr(dest, "999999999");
4638 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004639 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004640 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004641 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004642 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004643 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004644 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4645 break;
4646 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004647#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004648 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004649 unsigned pos;
4650
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004651 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004652 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004653# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004654 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004655 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004656 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004657 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4658 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004659 if (!BB_MMU)
4660 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004661 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4662 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004663 if (as_string) {
4664 o_addstr(as_string, dest->data + pos);
4665 o_addchr(as_string, ')');
4666 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004667 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004668 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004669 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004670 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004671# endif
4672# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004673 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4674 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004675 if (!BB_MMU)
4676 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004677 if (!add_till_closing_bracket(dest, input, ')'))
4678 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004679 if (as_string) {
4680 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004681 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004682 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004683 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004684# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004685 break;
4686 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004687#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004688 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004689 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004690 nommu_addchr(as_string, ch);
Denys Vlasenko657086a2016-09-29 18:07:42 +02004691 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004692 if (isalnum(ch)) { /* it's $_name or $_123 */
4693 ch = '_';
4694 goto make_var;
4695 }
4696 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004697 /* TODO: $_ and $-: */
4698 /* $_ Shell or shell script name; or last argument of last command
4699 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4700 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004701 /* $- Option flags set by set builtin or shell options (-i etc) */
4702 default:
4703 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004704 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004705 debug_printf_parse("parse_dollar return 1 (ok)\n");
4706 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004707#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004708}
4709
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004710#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004711# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004712#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4713 encode_string(dest, input, dquote_end, process_bkslash)
4714# else
4715/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4716#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4717 encode_string(dest, input, dquote_end)
4718# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004719#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004720
4721#else /* !MMU */
4722
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004723# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004724/* all parameters are needed, no macro tricks */
4725# else
4726#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4727 encode_string(as_string, dest, input, dquote_end)
4728# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004729#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004730static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004731 o_string *dest,
4732 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004733 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004734 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004735{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004736#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004737 const int process_bkslash = 1;
4738#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004739 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004740 int next;
4741
4742 again:
4743 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004744 if (ch != EOF)
4745 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004746 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004747 debug_printf_parse("encode_string return 1 (ok)\n");
4748 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004749 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004750 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004751 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004752 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004753 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004754 }
4755 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004756 if (ch != '\n') {
4757 next = i_peek(input);
4758 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004759 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004760 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004761 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004762 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004763 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004764 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004765 }
4766 /* bash:
4767 * "The backslash retains its special meaning [in "..."]
4768 * only when followed by one of the following characters:
4769 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004770 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004771 * NB: in (unquoted) heredoc, above does not apply to ",
4772 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004773 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004774 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004775 ch = i_getch(input); /* eat next */
4776 if (ch == '\n')
4777 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004778 } /* else: ch remains == '\\', and we double it below: */
4779 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004780 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004781 goto again;
4782 }
4783 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004784 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4785 debug_printf_parse("encode_string return 0: "
4786 "parse_dollar returned 0 (error)\n");
4787 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004788 }
4789 goto again;
4790 }
4791#if ENABLE_HUSH_TICK
4792 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004793 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004794 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4795 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004796 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4797 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004798 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4799 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004800 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004801 }
4802#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004803 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004804 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004805#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004806}
4807
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004808/*
4809 * Scan input until EOF or end_trigger char.
4810 * Return a list of pipes to execute, or NULL on EOF
4811 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004812 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004813 * reset parsing machinery and start parsing anew,
4814 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004815 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004816static struct pipe *parse_stream(char **pstring,
4817 struct in_str *input,
4818 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004819{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004820 struct parse_context ctx;
4821 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004822 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004823
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004824 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004825 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004826 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004827 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004828 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004829 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004830
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004831 /* If very first arg is "" or '', dest.data may end up NULL.
4832 * Preventing this: */
4833 o_addchr(&dest, '\0');
4834 dest.length = 0;
4835
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004836 /* We used to separate words on $IFS here. This was wrong.
4837 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004838 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004839 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004840
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004841 if (MAYBE_ASSIGNMENT != 0)
4842 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004843 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004844 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004845 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004846 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004847 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004848 int ch;
4849 int next;
4850 int redir_fd;
4851 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004852
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004853 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004854 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004855 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004856 if (ch == EOF) {
4857 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004858
4859 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004860 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004861 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004862 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004863 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004864 syntax_error_unterm_ch('(');
4865 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004866 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004867 if (end_trigger == '}') {
4868 syntax_error_unterm_ch('{');
4869 goto parse_error;
4870 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004871
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004872 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004873 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004874 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004875 o_free(&dest);
4876 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004877 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004878 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004879 /* (this makes bare "&" cmd a no-op.
4880 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004881 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004882 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004883 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004884 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004885 pi = NULL;
4886 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004887#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004888 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004889 if (pstring)
4890 *pstring = ctx.as_string.data;
4891 else
4892 o_free_unsafe(&ctx.as_string);
4893#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004894 debug_leave();
4895 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004896 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004897 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004898 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004899
4900 next = '\0';
4901 if (ch != '\n')
4902 next = i_peek(input);
4903
4904 is_special = "{}<>;&|()#'" /* special outside of "str" */
Denys Vlasenko932b9972018-01-11 12:39:48 +01004905 "\\$\"" IF_HUSH_TICK("`") /* always special */
4906 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004907 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004908 if (ctx.command->argv /* word [word]{... - non-special */
4909 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004910 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004911 || (next != ';' /* }; - special */
4912 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004913 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004914 && next != '&' /* }& and }&& ... - special */
4915 && next != '|' /* }|| ... - special */
4916 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004917 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004918 ) {
4919 /* They are not special, skip "{}" */
4920 is_special += 2;
4921 }
4922 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004923 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004924
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004925 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004926 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004927 o_addQchr(&dest, ch);
4928 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4929 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004930 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004931 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004932 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004933 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004934 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004935 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004936 continue;
4937 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004938
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004939 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004940 if (done_word(&dest, &ctx)) {
4941 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004942 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004943 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004944 /* Is this a case when newline is simply ignored?
4945 * Some examples:
4946 * "cmd | <newline> cmd ..."
4947 * "case ... in <newline> word) ..."
4948 */
4949 if (IS_NULL_CMD(ctx.command)
4950 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004951 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004952 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004953 * Without check #1, interactive shell
4954 * ignores even bare <newline>,
4955 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004956 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004957 * ps2> _ <=== wrong, should be ps1
4958 * Without check #2, "cmd & <newline>"
4959 * is similarly mistreated.
4960 * (BTW, this makes "cmd & cmd"
4961 * and "cmd && cmd" non-orthogonal.
4962 * Really, ask yourself, why
4963 * "cmd && <newline>" doesn't start
4964 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02004965 * The only reason is that it might be
4966 * a "cmd1 && <nl> cmd2 &" construct,
4967 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004968 */
4969 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004970 if (pi->num_cmds != 0 /* check #1 */
4971 && pi->followup != PIPE_BG /* check #2 */
4972 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004973 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004974 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004975 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004976 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004977 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004978 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4979 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004980 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004981 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004982 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004983 heredoc_cnt = 0;
4984 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004985 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004986 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004987 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004988 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004989 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004990 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004991 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004992
4993 /* "cmd}" or "cmd }..." without semicolon or &:
4994 * } is an ordinary char in this case, even inside { cmd; }
4995 * Pathological example: { ""}; } should exec "}" cmd
4996 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004997 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004998 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004999 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005000 ) {
5001 goto ordinary_char;
5002 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005003 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5004 /* Generally, there should be semicolon: "cmd; }"
5005 * However, bash allows to omit it if "cmd" is
5006 * a group. Examples:
5007 * { { echo 1; } }
5008 * {(echo 1)}
5009 * { echo 0 >&2 | { echo 1; } }
5010 * { while false; do :; done }
5011 * { case a in b) ;; esac }
5012 */
5013 if (ctx.command->group)
5014 goto term_group;
5015 goto ordinary_char;
5016 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005017 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005018 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005019 goto skip_end_trigger;
5020 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005021 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005022 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005023 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005024 && (ch != ';' || heredoc_cnt == 0)
5025#if ENABLE_HUSH_CASE
5026 && (ch != ')'
5027 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02005028 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005029 )
5030#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005031 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005032 if (heredoc_cnt) {
5033 /* This is technically valid:
5034 * { cat <<HERE; }; echo Ok
5035 * heredoc
5036 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005037 * HERE
5038 * but we don't support this.
5039 * We require heredoc to be in enclosing {}/(),
5040 * if any.
5041 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005042 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005043 goto parse_error;
5044 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005045 if (done_word(&dest, &ctx)) {
5046 goto parse_error;
5047 }
5048 done_pipe(&ctx, PIPE_SEQ);
5049 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005050 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005051 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005052 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005053 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005054 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005055 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005056#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005057 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005058 if (pstring)
5059 *pstring = ctx.as_string.data;
5060 else
5061 o_free_unsafe(&ctx.as_string);
5062#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005063 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5064 /* Example: bare "{ }", "()" */
5065 G.last_exitcode = 2; /* bash compat */
5066 syntax_error_unexpected_ch(ch);
5067 goto parse_error2;
5068 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005069 debug_printf_parse("parse_stream return %p: "
5070 "end_trigger char found\n",
5071 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005072 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005073 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005074 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005075 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005076 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005077 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005078 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005079
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005080 /* Catch <, > before deciding whether this word is
5081 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5082 switch (ch) {
5083 case '>':
5084 redir_fd = redirect_opt_num(&dest);
5085 if (done_word(&dest, &ctx)) {
5086 goto parse_error;
5087 }
5088 redir_style = REDIRECT_OVERWRITE;
5089 if (next == '>') {
5090 redir_style = REDIRECT_APPEND;
5091 ch = i_getch(input);
5092 nommu_addchr(&ctx.as_string, ch);
5093 }
5094#if 0
5095 else if (next == '(') {
5096 syntax_error(">(process) not supported");
5097 goto parse_error;
5098 }
5099#endif
5100 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5101 goto parse_error;
5102 continue; /* back to top of while (1) */
5103 case '<':
5104 redir_fd = redirect_opt_num(&dest);
5105 if (done_word(&dest, &ctx)) {
5106 goto parse_error;
5107 }
5108 redir_style = REDIRECT_INPUT;
5109 if (next == '<') {
5110 redir_style = REDIRECT_HEREDOC;
5111 heredoc_cnt++;
5112 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5113 ch = i_getch(input);
5114 nommu_addchr(&ctx.as_string, ch);
5115 } else if (next == '>') {
5116 redir_style = REDIRECT_IO;
5117 ch = i_getch(input);
5118 nommu_addchr(&ctx.as_string, ch);
5119 }
5120#if 0
5121 else if (next == '(') {
5122 syntax_error("<(process) not supported");
5123 goto parse_error;
5124 }
5125#endif
5126 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5127 goto parse_error;
5128 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005129 case '#':
5130 if (dest.length == 0 && !dest.has_quoted_part) {
5131 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005132 /* note: we do not add it to &ctx.as_string */
5133/* TODO: in bash:
5134 * comment inside $() goes to the next \n, even inside quoted string (!):
5135 * cmd "$(cmd2 #comment)" - syntax error
5136 * cmd "`cmd2 #comment`" - ok
5137 * We accept both (comment ends where command subst ends, in both cases).
5138 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005139 while (1) {
5140 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005141 if (ch == '\n') {
5142 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005143 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005144 }
5145 ch = i_getch(input);
5146 if (ch == EOF)
5147 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005148 }
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005149 continue; /* back to top of while (1) */
5150 }
5151 break;
5152 case '\\':
5153 if (next == '\n') {
5154 /* It's "\<newline>" */
5155#if !BB_MMU
5156 /* Remove trailing '\' from ctx.as_string */
5157 ctx.as_string.data[--ctx.as_string.length] = '\0';
5158#endif
5159 ch = i_getch(input); /* eat it */
5160 continue; /* back to top of while (1) */
5161 }
5162 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005163 }
5164
5165 if (dest.o_assignment == MAYBE_ASSIGNMENT
5166 /* check that we are not in word in "a=1 2>word b=1": */
5167 && !ctx.pending_redirect
5168 ) {
5169 /* ch is a special char and thus this word
5170 * cannot be an assignment */
5171 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005172 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005173 }
5174
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005175 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5176
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005177 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005178 case SPECIAL_VAR_SYMBOL:
5179 /* Convert raw ^C to corresponding special variable reference */
5180 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5181 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5182 /* fall through */
5183 case '#':
5184 /* non-comment #: "echo a#b" etc */
5185 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005186 break;
5187 case '\\':
5188 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005189 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005190 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005191 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005192 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005193 /* note: ch != '\n' (that case does not reach this place) */
5194 o_addchr(&dest, '\\');
5195 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5196 o_addchr(&dest, ch);
5197 nommu_addchr(&ctx.as_string, ch);
5198 /* Example: echo Hello \2>file
5199 * we need to know that word 2 is quoted */
5200 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005201 break;
5202 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005203 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005204 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005205 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005206 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005207 }
Eric Andersen25f27032001-04-26 23:22:31 +00005208 break;
5209 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005210 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005211 if (next == '\'' && !ctx.pending_redirect) {
5212 insert_empty_quoted_str_marker:
5213 nommu_addchr(&ctx.as_string, next);
5214 i_getch(input); /* eat second ' */
5215 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5216 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5217 } else {
5218 while (1) {
5219 ch = i_getch(input);
5220 if (ch == EOF) {
5221 syntax_error_unterm_ch('\'');
5222 goto parse_error;
5223 }
5224 nommu_addchr(&ctx.as_string, ch);
5225 if (ch == '\'')
5226 break;
5227 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005228 }
Eric Andersen25f27032001-04-26 23:22:31 +00005229 }
Eric Andersen25f27032001-04-26 23:22:31 +00005230 break;
5231 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005232 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005233 if (next == '"' && !ctx.pending_redirect)
5234 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005235 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005236 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005237 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005238 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005239 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00005240 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005241#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005242 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005243 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005244
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005245 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5246 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02005247 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005248 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5249 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005250# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005251 o_addstr(&ctx.as_string, dest.data + pos);
5252 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005253# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005254 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5255 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005256 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005257 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005258#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005259 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005260#if ENABLE_HUSH_CASE
5261 case_semi:
5262#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005263 if (done_word(&dest, &ctx)) {
5264 goto parse_error;
5265 }
5266 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005267#if ENABLE_HUSH_CASE
5268 /* Eat multiple semicolons, detect
5269 * whether it means something special */
5270 while (1) {
5271 ch = i_peek(input);
5272 if (ch != ';')
5273 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005274 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005275 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005276 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005277 ctx.ctx_dsemicolon = 1;
5278 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005279 break;
5280 }
5281 }
5282#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005283 new_cmd:
5284 /* We just finished a cmd. New one may start
5285 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005286 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005287 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00005288 break;
5289 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005290 if (done_word(&dest, &ctx)) {
5291 goto parse_error;
5292 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005293 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005294 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005295 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005296 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005297 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005298 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005299 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005300 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005301 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005302 if (done_word(&dest, &ctx)) {
5303 goto parse_error;
5304 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005305#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005306 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005307 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005308#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005309 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005310 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005311 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005312 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005313 } else {
5314 /* we could pick up a file descriptor choice here
5315 * with redirect_opt_num(), but bash doesn't do it.
5316 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005317 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005318 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005319 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005320 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005321#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005322 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005323 if (ctx.ctx_res_w == RES_MATCH
5324 && ctx.command->argv == NULL /* not (word|(... */
5325 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005326 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005327 ) {
5328 continue;
5329 }
5330#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005331 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005332 if (parse_group(&dest, &ctx, input, ch) != 0) {
5333 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005334 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005335 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005336 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005337#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005338 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005339 goto case_semi;
5340#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005341 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005342 /* proper use of this character is caught by end_trigger:
5343 * if we see {, we call parse_group(..., end_trigger='}')
5344 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005345 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005346 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005347 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005348 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005349 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005350 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005351 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005352 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005353
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005354 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005355 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005356 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005357 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005358 struct parse_context *pctx;
5359 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005360
5361 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005362 * Sample for finding leaks on syntax error recovery path.
5363 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005364 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005365 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005366 * while if (true | { true;}); then echo ok; fi; do break; done
5367 * 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 +00005368 */
5369 pctx = &ctx;
5370 do {
5371 /* Update pipe/command counts,
5372 * otherwise freeing may miss some */
5373 done_pipe(pctx, PIPE_SEQ);
5374 debug_printf_clean("freeing list %p from ctx %p\n",
5375 pctx->list_head, pctx);
5376 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005377 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005378 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005379#if !BB_MMU
5380 o_free_unsafe(&pctx->as_string);
5381#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005382 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005383 if (pctx != &ctx) {
5384 free(pctx);
5385 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005386 IF_HAS_KEYWORDS(pctx = p2;)
5387 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005388
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005389 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005390#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005391 if (pstring)
5392 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005393#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005394 debug_leave();
5395 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005396 }
Eric Andersen25f27032001-04-26 23:22:31 +00005397}
5398
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005399
5400/*** Execution routines ***/
5401
5402/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005403#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005404/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5405#define expand_string_to_string(str, do_unbackslash) \
5406 expand_string_to_string(str)
5407#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005408static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005409#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005410static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005411#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005412
5413/* expand_strvec_to_strvec() takes a list of strings, expands
5414 * all variable references within and returns a pointer to
5415 * a list of expanded strings, possibly with larger number
5416 * of strings. (Think VAR="a b"; echo $VAR).
5417 * This new list is allocated as a single malloc block.
5418 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005419 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005420 * Caller can deallocate entire list by single free(list). */
5421
Denys Vlasenko238081f2010-10-03 14:26:26 +02005422/* A horde of its helpers come first: */
5423
5424static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5425{
5426 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005427 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005428
Denys Vlasenko9e800222010-10-03 14:28:04 +02005429#if ENABLE_HUSH_BRACE_EXPANSION
5430 if (c == '{' || c == '}') {
5431 /* { -> \{, } -> \} */
5432 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005433 /* And now we want to add { or } and continue:
5434 * o_addchr(o, c);
5435 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005436 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005437 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005438 }
5439#endif
5440 o_addchr(o, c);
5441 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005442 /* \z -> \\\z; \<eol> -> \\<eol> */
5443 o_addchr(o, '\\');
5444 if (len) {
5445 len--;
5446 o_addchr(o, '\\');
5447 o_addchr(o, *str++);
5448 }
5449 }
5450 }
5451}
5452
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005453/* Store given string, finalizing the word and starting new one whenever
5454 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005455 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5456 * Return in *ended_with_ifs:
5457 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5458 */
5459static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005460{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005461 int last_is_ifs = 0;
5462
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005463 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005464 int word_len;
5465
5466 if (!*str) /* EOL - do not finalize word */
5467 break;
5468 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005469 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005470 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005471 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005472 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005473 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005474 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005475 * Example: "v='\*'; echo b$v" prints "b\*"
5476 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005477 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005478 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005479 /*/ Why can't we do it easier? */
5480 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5481 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5482 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005483 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005484 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005485 if (!*str) /* EOL - do not finalize word */
5486 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005487 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005488
5489 /* We know str here points to at least one IFS char */
5490 last_is_ifs = 1;
5491 str += strspn(str, G.ifs); /* skip IFS chars */
5492 if (!*str) /* EOL - do not finalize word */
5493 break;
5494
5495 /* Start new word... but not always! */
5496 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005497 if (output->has_quoted_part
5498 /* Case "v=' a'; echo $v":
5499 * here nothing precedes the space in $v expansion,
5500 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005501 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005502 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005503 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005504 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005505 o_addchr(output, '\0');
5506 debug_print_list("expand_on_ifs", output, n);
5507 n = o_save_ptr(output, n);
5508 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005509 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005510
5511 if (ended_with_ifs)
5512 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005513 debug_print_list("expand_on_ifs[1]", output, n);
5514 return n;
5515}
5516
5517/* Helper to expand $((...)) and heredoc body. These act as if
5518 * they are in double quotes, with the exception that they are not :).
5519 * Just the rules are similar: "expand only $var and `cmd`"
5520 *
5521 * Returns malloced string.
5522 * As an optimization, we return NULL if expansion is not needed.
5523 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005524#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005525/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5526#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5527 encode_then_expand_string(str)
5528#endif
5529static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005530{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005531#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005532 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005533#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005534 char *exp_str;
5535 struct in_str input;
5536 o_string dest = NULL_O_STRING;
5537
5538 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005539 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005540#if ENABLE_HUSH_TICK
5541 && !strchr(str, '`')
5542#endif
5543 ) {
5544 return NULL;
5545 }
5546
5547 /* We need to expand. Example:
5548 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5549 */
5550 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005551 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005552//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005553 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005554 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005555 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5556 o_free_unsafe(&dest);
5557 return exp_str;
5558}
5559
Denys Vlasenko0b883582016-12-23 16:49:07 +01005560#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005561static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005562{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005563 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005564 arith_t res;
5565 char *exp_str;
5566
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005567 math_state.lookupvar = get_local_var_value;
5568 math_state.setvar = set_local_var_from_halves;
5569 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005570 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005571 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005572 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005573 if (errmsg_p)
5574 *errmsg_p = math_state.errmsg;
5575 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005576 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005577 return res;
5578}
5579#endif
5580
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005581#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005582/* ${var/[/]pattern[/repl]} helpers */
5583static char *strstr_pattern(char *val, const char *pattern, int *size)
5584{
5585 while (1) {
5586 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5587 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5588 if (end) {
5589 *size = end - val;
5590 return val;
5591 }
5592 if (*val == '\0')
5593 return NULL;
5594 /* Optimization: if "*pat" did not match the start of "string",
5595 * we know that "tring", "ring" etc will not match too:
5596 */
5597 if (pattern[0] == '*')
5598 return NULL;
5599 val++;
5600 }
5601}
5602static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5603{
5604 char *result = NULL;
5605 unsigned res_len = 0;
5606 unsigned repl_len = strlen(repl);
5607
5608 while (1) {
5609 int size;
5610 char *s = strstr_pattern(val, pattern, &size);
5611 if (!s)
5612 break;
5613
5614 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005615 strcpy(mempcpy(result + res_len, val, s - val), repl);
5616 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005617 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5618
5619 val = s + size;
5620 if (exp_op == '/')
5621 break;
5622 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005623 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005624 result = xrealloc(result, res_len + strlen(val) + 1);
5625 strcpy(result + res_len, val);
5626 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5627 }
5628 debug_printf_varexp("result:'%s'\n", result);
5629 return result;
5630}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005631#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005632
5633/* Helper:
5634 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5635 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005636static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005637{
5638 const char *val = NULL;
5639 char *to_be_freed = NULL;
5640 char *p = *pp;
5641 char *var;
5642 char first_char;
5643 char exp_op;
5644 char exp_save = exp_save; /* for compiler */
5645 char *exp_saveptr; /* points to expansion operator */
5646 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005647 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005648
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005649 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005650 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005651 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005652 arg0 = arg[0];
5653 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005654 exp_op = 0;
5655
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005656 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5657 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5658 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5659 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005660 ) {
5661 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005662 var++;
5663 exp_op = 'L';
5664 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005665 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005666 if (exp_saveptr /* if 2nd char is one of expansion operators */
5667 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5668 ) {
5669 /* ${?:0}, ${#[:]%0} etc */
5670 exp_saveptr = var + 1;
5671 } else {
5672 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5673 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5674 }
5675 exp_op = exp_save = *exp_saveptr;
5676 if (exp_op) {
5677 exp_word = exp_saveptr + 1;
5678 if (exp_op == ':') {
5679 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005680//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005681 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005682 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005683 ) {
5684 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5685 exp_op = ':';
5686 exp_word--;
5687 }
5688 }
5689 *exp_saveptr = '\0';
5690 } /* else: it's not an expansion op, but bare ${var} */
5691 }
5692
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005693 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005694 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005695 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005696 int n = xatoi_positive(var);
5697 if (n < G.global_argc)
5698 val = G.global_argv[n];
5699 /* else val remains NULL: $N with too big N */
5700 } else {
5701 switch (var[0]) {
5702 case '$': /* pid */
5703 val = utoa(G.root_pid);
5704 break;
5705 case '!': /* bg pid */
5706 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5707 break;
5708 case '?': /* exitcode */
5709 val = utoa(G.last_exitcode);
5710 break;
5711 case '#': /* argc */
5712 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5713 break;
5714 default:
5715 val = get_local_var_value(var);
5716 }
5717 }
5718
5719 /* Handle any expansions */
5720 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005721 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005722 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005723 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005724 debug_printf_expand("%s\n", val);
5725 } else if (exp_op) {
5726 if (exp_op == '%' || exp_op == '#') {
5727 /* Standard-mandated substring removal ops:
5728 * ${parameter%word} - remove smallest suffix pattern
5729 * ${parameter%%word} - remove largest suffix pattern
5730 * ${parameter#word} - remove smallest prefix pattern
5731 * ${parameter##word} - remove largest prefix pattern
5732 *
5733 * Word is expanded to produce a glob pattern.
5734 * Then var's value is matched to it and matching part removed.
5735 */
5736 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005737 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005738 char *exp_exp_word;
5739 char *loc;
5740 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005741 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005742 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005743 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005744 if (exp_exp_word)
5745 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005746 /* HACK ALERT. We depend here on the fact that
5747 * G.global_argv and results of utoa and get_local_var_value
5748 * are actually in writable memory:
5749 * scan_and_match momentarily stores NULs there. */
5750 t = (char*)val;
5751 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005752 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005753 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005754 free(exp_exp_word);
5755 if (loc) { /* match was found */
5756 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005757 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005758 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005759 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005760 }
5761 }
5762 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005763#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005764 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005765 /* It's ${var/[/]pattern[/repl]} thing.
5766 * Note that in encoded form it has TWO parts:
5767 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005768 * and if // is used, it is encoded as \:
5769 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005770 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005771 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005772 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005773 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005774 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005775 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005776 * by the usual expansion rules:
5777 * >az; >bz;
5778 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5779 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5780 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5781 * v='a bz'; echo ${v/a*z/\z} prints "z"
5782 * (note that a*z _pattern_ is never globbed!)
5783 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005784 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005785 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005786 if (!pattern)
5787 pattern = xstrdup(exp_word);
5788 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5789 *p++ = SPECIAL_VAR_SYMBOL;
5790 exp_word = p;
5791 p = strchr(p, SPECIAL_VAR_SYMBOL);
5792 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005793 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005794 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5795 /* HACK ALERT. We depend here on the fact that
5796 * G.global_argv and results of utoa and get_local_var_value
5797 * are actually in writable memory:
5798 * replace_pattern momentarily stores NULs there. */
5799 t = (char*)val;
5800 to_be_freed = replace_pattern(t,
5801 pattern,
5802 (repl ? repl : exp_word),
5803 exp_op);
5804 if (to_be_freed) /* at least one replace happened */
5805 val = to_be_freed;
5806 free(pattern);
5807 free(repl);
5808 }
5809 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005810#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005811 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005812#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005813 /* It's ${var:N[:M]} bashism.
5814 * Note that in encoded form it has TWO parts:
5815 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5816 */
5817 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005818 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005819
Denys Vlasenko063847d2010-09-15 13:33:02 +02005820 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5821 if (errmsg)
5822 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005823 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5824 *p++ = SPECIAL_VAR_SYMBOL;
5825 exp_word = p;
5826 p = strchr(p, SPECIAL_VAR_SYMBOL);
5827 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005828 len = expand_and_evaluate_arith(exp_word, &errmsg);
5829 if (errmsg)
5830 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005831 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005832 if (beg < 0) {
5833 /* negative beg counts from the end */
5834 beg = (arith_t)strlen(val) + beg;
5835 if (beg < 0) /* ${v: -999999} is "" */
5836 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005837 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005838 debug_printf_varexp("from val:'%s'\n", val);
5839 if (len < 0) {
5840 /* in bash, len=-n means strlen()-n */
5841 len = (arith_t)strlen(val) - beg + len;
5842 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02005843 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005844 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02005845 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005846 arith_err:
5847 val = NULL;
5848 } else {
5849 /* Paranoia. What if user entered 9999999999999
5850 * which fits in arith_t but not int? */
5851 if (len >= INT_MAX)
5852 len = INT_MAX;
5853 val = to_be_freed = xstrndup(val + beg, len);
5854 }
5855 debug_printf_varexp("val:'%s'\n", val);
5856#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02005857 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005858 val = NULL;
5859#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005860 } else { /* one of "-=+?" */
5861 /* Standard-mandated substitution ops:
5862 * ${var?word} - indicate error if unset
5863 * If var is unset, word (or a message indicating it is unset
5864 * if word is null) is written to standard error
5865 * and the shell exits with a non-zero exit status.
5866 * Otherwise, the value of var is substituted.
5867 * ${var-word} - use default value
5868 * If var is unset, word is substituted.
5869 * ${var=word} - assign and use default value
5870 * If var is unset, word is assigned to var.
5871 * In all cases, final value of var is substituted.
5872 * ${var+word} - use alternative value
5873 * If var is unset, null is substituted.
5874 * Otherwise, word is substituted.
5875 *
5876 * Word is subjected to tilde expansion, parameter expansion,
5877 * command substitution, and arithmetic expansion.
5878 * If word is not needed, it is not expanded.
5879 *
5880 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5881 * but also treat null var as if it is unset.
5882 */
5883 int use_word = (!val || ((exp_save == ':') && !val[0]));
5884 if (exp_op == '+')
5885 use_word = !use_word;
5886 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5887 (exp_save == ':') ? "true" : "false", use_word);
5888 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005889 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005890 if (to_be_freed)
5891 exp_word = to_be_freed;
5892 if (exp_op == '?') {
5893 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02005894 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005895 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02005896 exp_word[0]
5897 ? exp_word
5898 : "parameter null or not set"
5899 /* ash has more specific messages, a-la: */
5900 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005901 );
5902//TODO: how interactive bash aborts expansion mid-command?
5903 } else {
5904 val = exp_word;
5905 }
5906
5907 if (exp_op == '=') {
5908 /* ${var=[word]} or ${var:=[word]} */
5909 if (isdigit(var[0]) || var[0] == '#') {
5910 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02005911 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005912 val = NULL;
5913 } else {
5914 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02005915 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005916 }
5917 }
5918 }
5919 } /* one of "-=+?" */
5920
5921 *exp_saveptr = exp_save;
5922 } /* if (exp_op) */
5923
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005924 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005925
5926 *pp = p;
5927 *to_be_freed_pp = to_be_freed;
5928 return val;
5929}
5930
5931/* Expand all variable references in given string, adding words to list[]
5932 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5933 * to be filled). This routine is extremely tricky: has to deal with
5934 * variables/parameters with whitespace, $* and $@, and constructs like
5935 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005936static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005937{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005938 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005939 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005940 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005941 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005942 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005943 char *p;
5944
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005945 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5946 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005947 debug_print_list("expand_vars_to_list", output, n);
5948 n = o_save_ptr(output, n);
5949 debug_print_list("expand_vars_to_list[0]", output, n);
5950
5951 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5952 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005953 char *to_be_freed = NULL;
5954 const char *val = NULL;
5955#if ENABLE_HUSH_TICK
5956 o_string subst_result = NULL_O_STRING;
5957#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01005958#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005959 char arith_buf[sizeof(arith_t)*3 + 2];
5960#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005961
5962 if (ended_in_ifs) {
5963 o_addchr(output, '\0');
5964 n = o_save_ptr(output, n);
5965 ended_in_ifs = 0;
5966 }
5967
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005968 o_addblock(output, arg, p - arg);
5969 debug_print_list("expand_vars_to_list[1]", output, n);
5970 arg = ++p;
5971 p = strchr(p, SPECIAL_VAR_SYMBOL);
5972
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005973 /* Fetch special var name (if it is indeed one of them)
5974 * and quote bit, force the bit on if singleword expansion -
5975 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005976 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005977
5978 /* Is this variable quoted and thus expansion can't be null?
5979 * "$@" is special. Even if quoted, it can still
5980 * expand to nothing (not even an empty string),
5981 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005982 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005983 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005984
5985 switch (first_ch & 0x7f) {
5986 /* Highest bit in first_ch indicates that var is double-quoted */
5987 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005988 case '@': {
5989 int i;
5990 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005991 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005992 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005993 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005994 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005995 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005996 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005997 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5998 if (G.global_argv[i++][0] && G.global_argv[i]) {
5999 /* this argv[] is not empty and not last:
6000 * put terminating NUL, start new word */
6001 o_addchr(output, '\0');
6002 debug_print_list("expand_vars_to_list[2]", output, n);
6003 n = o_save_ptr(output, n);
6004 debug_print_list("expand_vars_to_list[3]", output, n);
6005 }
6006 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006007 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006008 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006009 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006010 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006011 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006012 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006013 while (1) {
6014 o_addQstr(output, G.global_argv[i]);
6015 if (++i >= G.global_argc)
6016 break;
6017 o_addchr(output, '\0');
6018 debug_print_list("expand_vars_to_list[4]", output, n);
6019 n = o_save_ptr(output, n);
6020 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006021 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006022 while (1) {
6023 o_addQstr(output, G.global_argv[i]);
6024 if (!G.global_argv[++i])
6025 break;
6026 if (G.ifs[0])
6027 o_addchr(output, G.ifs[0]);
6028 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006029 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006030 }
6031 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006032 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006033 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6034 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006035 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006036 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006037 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006038 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006039 case SPECIAL_VAR_QUOTED_SVS:
6040 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6041 arg++;
6042 val = SPECIAL_VAR_SYMBOL_STR;
6043 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006044#if ENABLE_HUSH_TICK
6045 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006046 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006047 arg++;
6048 /* Can't just stuff it into output o_string,
6049 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006050 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006051 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6052 G.last_exitcode = process_command_subs(&subst_result, arg);
6053 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6054 val = subst_result.data;
6055 goto store_val;
6056#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006057#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006058 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6059 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006060
6061 arg++; /* skip '+' */
6062 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6063 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006064 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006065 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6066 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006067 val = arith_buf;
6068 break;
6069 }
6070#endif
6071 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006072 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006073 IF_HUSH_TICK(store_val:)
6074 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006075 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6076 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006077 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006078 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006079 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006080 }
6081 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006082 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006083 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6084 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006085 }
6086 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006087 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6088
6089 if (val && val[0]) {
6090 o_addQstr(output, val);
6091 }
6092 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006093
6094 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6095 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006096 if (*p != SPECIAL_VAR_SYMBOL)
6097 *p = SPECIAL_VAR_SYMBOL;
6098
6099#if ENABLE_HUSH_TICK
6100 o_free(&subst_result);
6101#endif
6102 arg = ++p;
6103 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6104
6105 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006106 if (ended_in_ifs) {
6107 o_addchr(output, '\0');
6108 n = o_save_ptr(output, n);
6109 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006110 debug_print_list("expand_vars_to_list[a]", output, n);
6111 /* this part is literal, and it was already pre-quoted
6112 * if needed (much earlier), do not use o_addQstr here! */
6113 o_addstr_with_NUL(output, arg);
6114 debug_print_list("expand_vars_to_list[b]", output, n);
6115 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006116 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006117 ) {
6118 n--;
6119 /* allow to reuse list[n] later without re-growth */
6120 output->has_empty_slot = 1;
6121 } else {
6122 o_addchr(output, '\0');
6123 }
6124
6125 return n;
6126}
6127
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006128static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006129{
6130 int n;
6131 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006132 o_string output = NULL_O_STRING;
6133
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006134 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006135
6136 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006137 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006138 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006139 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006140 }
6141 debug_print_list("expand_variables", &output, n);
6142
6143 /* output.data (malloced in one block) gets returned in "list" */
6144 list = o_finalize_list(&output, n);
6145 debug_print_strings("expand_variables[1]", list);
6146 return list;
6147}
6148
6149static char **expand_strvec_to_strvec(char **argv)
6150{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006151 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006152}
6153
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006154#if BASH_TEST2
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006155static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6156{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006157 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006158}
6159#endif
6160
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006161/* Used for expansion of right hand of assignments,
6162 * $((...)), heredocs, variable espansion parts.
6163 *
6164 * NB: should NOT do globbing!
6165 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6166 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006167static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006168{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006169#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006170 const int do_unbackslash = 1;
6171#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006172 char *argv[2], **list;
6173
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006174 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006175 /* This is generally an optimization, but it also
6176 * handles "", which otherwise trips over !list[0] check below.
6177 * (is this ever happens that we actually get str="" here?)
6178 */
6179 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6180 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006181 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006182 return xstrdup(str);
6183 }
6184
6185 argv[0] = (char*)str;
6186 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006187 list = expand_variables(argv, do_unbackslash
6188 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6189 : EXP_FLAG_SINGLEWORD
6190 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006191 if (HUSH_DEBUG)
6192 if (!list[0] || list[1])
6193 bb_error_msg_and_die("BUG in varexp2");
6194 /* actually, just move string 2*sizeof(char*) bytes back */
6195 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006196 if (do_unbackslash)
6197 unbackslash((char*)list);
6198 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006199 return (char*)list;
6200}
6201
Denys Vlasenko1f191122018-01-11 13:17:30 +01006202#if ENABLE_HUSH_CASE
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006203static char* expand_strvec_to_string(char **argv)
6204{
6205 char **list;
6206
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006207 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006208 /* Convert all NULs to spaces */
6209 if (list[0]) {
6210 int n = 1;
6211 while (list[n]) {
6212 if (HUSH_DEBUG)
6213 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6214 bb_error_msg_and_die("BUG in varexp3");
6215 /* bash uses ' ' regardless of $IFS contents */
6216 list[n][-1] = ' ';
6217 n++;
6218 }
6219 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006220 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006221 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6222 return (char*)list;
6223}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006224#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006225
6226static char **expand_assignments(char **argv, int count)
6227{
6228 int i;
6229 char **p;
6230
6231 G.expanded_assignments = p = NULL;
6232 /* Expand assignments into one string each */
6233 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006234 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006235 }
6236 G.expanded_assignments = NULL;
6237 return p;
6238}
6239
6240
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006241static void switch_off_special_sigs(unsigned mask)
6242{
6243 unsigned sig = 0;
6244 while ((mask >>= 1) != 0) {
6245 sig++;
6246 if (!(mask & 1))
6247 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006248#if ENABLE_HUSH_TRAP
6249 if (G_traps) {
6250 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006251 /* trap is '', has to remain SIG_IGN */
6252 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006253 free(G_traps[sig]);
6254 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006255 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006256#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006257 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006258 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006259 }
6260}
6261
Denys Vlasenkob347df92011-08-09 22:49:15 +02006262#if BB_MMU
6263/* never called */
6264void re_execute_shell(char ***to_free, const char *s,
6265 char *g_argv0, char **g_argv,
6266 char **builtin_argv) NORETURN;
6267
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006268static void reset_traps_to_defaults(void)
6269{
6270 /* This function is always called in a child shell
6271 * after fork (not vfork, NOMMU doesn't use this function).
6272 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006273 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006274 unsigned mask;
6275
6276 /* Child shells are not interactive.
6277 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6278 * Testcase: (while :; do :; done) + ^Z should background.
6279 * Same goes for SIGTERM, SIGHUP, SIGINT.
6280 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006281 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006282 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006283 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006284
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006285 /* Switch off special sigs */
6286 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006287# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006288 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006289# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006290 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006291 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6292 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006293
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006294# if ENABLE_HUSH_TRAP
6295 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006296 return;
6297
6298 /* Reset all sigs to default except ones with empty traps */
6299 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006300 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006301 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006302 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006303 continue; /* empty trap: has to remain SIG_IGN */
6304 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006305 free(G_traps[sig]);
6306 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006307 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006308 if (sig == 0)
6309 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006310 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006311 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006312# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006313}
6314
6315#else /* !BB_MMU */
6316
6317static void re_execute_shell(char ***to_free, const char *s,
6318 char *g_argv0, char **g_argv,
6319 char **builtin_argv) NORETURN;
6320static void re_execute_shell(char ***to_free, const char *s,
6321 char *g_argv0, char **g_argv,
6322 char **builtin_argv)
6323{
6324# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6325 /* delims + 2 * (number of bytes in printed hex numbers) */
6326 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6327 char *heredoc_argv[4];
6328 struct variable *cur;
6329# if ENABLE_HUSH_FUNCTIONS
6330 struct function *funcp;
6331# endif
6332 char **argv, **pp;
6333 unsigned cnt;
6334 unsigned long long empty_trap_mask;
6335
6336 if (!g_argv0) { /* heredoc */
6337 argv = heredoc_argv;
6338 argv[0] = (char *) G.argv0_for_re_execing;
6339 argv[1] = (char *) "-<";
6340 argv[2] = (char *) s;
6341 argv[3] = NULL;
6342 pp = &argv[3]; /* used as pointer to empty environment */
6343 goto do_exec;
6344 }
6345
6346 cnt = 0;
6347 pp = builtin_argv;
6348 if (pp) while (*pp++)
6349 cnt++;
6350
6351 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006352 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006353 int sig;
6354 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006355 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006356 empty_trap_mask |= 1LL << sig;
6357 }
6358 }
6359
6360 sprintf(param_buf, NOMMU_HACK_FMT
6361 , (unsigned) G.root_pid
6362 , (unsigned) G.root_ppid
6363 , (unsigned) G.last_bg_pid
6364 , (unsigned) G.last_exitcode
6365 , cnt
6366 , empty_trap_mask
6367 IF_HUSH_LOOPS(, G.depth_of_loop)
6368 );
6369# undef NOMMU_HACK_FMT
6370 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6371 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6372 */
6373 cnt += 6;
6374 for (cur = G.top_var; cur; cur = cur->next) {
6375 if (!cur->flg_export || cur->flg_read_only)
6376 cnt += 2;
6377 }
6378# if ENABLE_HUSH_FUNCTIONS
6379 for (funcp = G.top_func; funcp; funcp = funcp->next)
6380 cnt += 3;
6381# endif
6382 pp = g_argv;
6383 while (*pp++)
6384 cnt++;
6385 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6386 *pp++ = (char *) G.argv0_for_re_execing;
6387 *pp++ = param_buf;
6388 for (cur = G.top_var; cur; cur = cur->next) {
6389 if (strcmp(cur->varstr, hush_version_str) == 0)
6390 continue;
6391 if (cur->flg_read_only) {
6392 *pp++ = (char *) "-R";
6393 *pp++ = cur->varstr;
6394 } else if (!cur->flg_export) {
6395 *pp++ = (char *) "-V";
6396 *pp++ = cur->varstr;
6397 }
6398 }
6399# if ENABLE_HUSH_FUNCTIONS
6400 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6401 *pp++ = (char *) "-F";
6402 *pp++ = funcp->name;
6403 *pp++ = funcp->body_as_string;
6404 }
6405# endif
6406 /* We can pass activated traps here. Say, -Tnn:trap_string
6407 *
6408 * However, POSIX says that subshells reset signals with traps
6409 * to SIG_DFL.
6410 * I tested bash-3.2 and it not only does that with true subshells
6411 * of the form ( list ), but with any forked children shells.
6412 * I set trap "echo W" WINCH; and then tried:
6413 *
6414 * { echo 1; sleep 20; echo 2; } &
6415 * while true; do echo 1; sleep 20; echo 2; break; done &
6416 * true | { echo 1; sleep 20; echo 2; } | cat
6417 *
6418 * In all these cases sending SIGWINCH to the child shell
6419 * did not run the trap. If I add trap "echo V" WINCH;
6420 * _inside_ group (just before echo 1), it works.
6421 *
6422 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006423 */
6424 *pp++ = (char *) "-c";
6425 *pp++ = (char *) s;
6426 if (builtin_argv) {
6427 while (*++builtin_argv)
6428 *pp++ = *builtin_argv;
6429 *pp++ = (char *) "";
6430 }
6431 *pp++ = g_argv0;
6432 while (*g_argv)
6433 *pp++ = *g_argv++;
6434 /* *pp = NULL; - is already there */
6435 pp = environ;
6436
6437 do_exec:
6438 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006439 /* Don't propagate SIG_IGN to the child */
6440 if (SPECIAL_JOBSTOP_SIGS != 0)
6441 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006442 execve(bb_busybox_exec_path, argv, pp);
6443 /* Fallback. Useful for init=/bin/hush usage etc */
6444 if (argv[0][0] == '/')
6445 execve(argv[0], argv, pp);
6446 xfunc_error_retval = 127;
6447 bb_error_msg_and_die("can't re-execute the shell");
6448}
6449#endif /* !BB_MMU */
6450
6451
6452static int run_and_free_list(struct pipe *pi);
6453
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006454/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006455 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6456 * end_trigger controls how often we stop parsing
6457 * NUL: parse all, execute, return
6458 * ';': parse till ';' or newline, execute, repeat till EOF
6459 */
6460static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006461{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006462 /* Why we need empty flag?
6463 * An obscure corner case "false; ``; echo $?":
6464 * empty command in `` should still set $? to 0.
6465 * But we can't just set $? to 0 at the start,
6466 * this breaks "false; echo `echo $?`" case.
6467 */
6468 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006469 while (1) {
6470 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006471
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006472#if ENABLE_HUSH_INTERACTIVE
6473 if (end_trigger == ';')
6474 inp->promptmode = 0; /* PS1 */
6475#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006476 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006477 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6478 /* If we are in "big" script
6479 * (not in `cmd` or something similar)...
6480 */
6481 if (pipe_list == ERR_PTR && end_trigger == ';') {
6482 /* Discard cached input (rest of line) */
6483 int ch = inp->last_char;
6484 while (ch != EOF && ch != '\n') {
6485 //bb_error_msg("Discarded:'%c'", ch);
6486 ch = i_getch(inp);
6487 }
6488 /* Force prompt */
6489 inp->p = NULL;
6490 /* This stream isn't empty */
6491 empty = 0;
6492 continue;
6493 }
6494 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006495 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006496 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006497 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006498 debug_print_tree(pipe_list, 0);
6499 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6500 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006501 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006502 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006503 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006504 }
Eric Andersen25f27032001-04-26 23:22:31 +00006505}
6506
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006507static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006508{
6509 struct in_str input;
6510 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006511 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006512}
6513
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006514static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006515{
Eric Andersen25f27032001-04-26 23:22:31 +00006516 struct in_str input;
6517 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006518 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006519}
6520
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006521#if ENABLE_HUSH_TICK
6522static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6523{
6524 pid_t pid;
6525 int channel[2];
6526# if !BB_MMU
6527 char **to_free = NULL;
6528# endif
6529
6530 xpipe(channel);
6531 pid = BB_MMU ? xfork() : xvfork();
6532 if (pid == 0) { /* child */
6533 disable_restore_tty_pgrp_on_exit();
6534 /* Process substitution is not considered to be usual
6535 * 'command execution'.
6536 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6537 */
6538 bb_signals(0
6539 + (1 << SIGTSTP)
6540 + (1 << SIGTTIN)
6541 + (1 << SIGTTOU)
6542 , SIG_IGN);
6543 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6544 close(channel[0]); /* NB: close _first_, then move fd! */
6545 xmove_fd(channel[1], 1);
6546 /* Prevent it from trying to handle ctrl-z etc */
6547 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006548# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006549 /* Awful hack for `trap` or $(trap).
6550 *
6551 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6552 * contains an example where "trap" is executed in a subshell:
6553 *
6554 * save_traps=$(trap)
6555 * ...
6556 * eval "$save_traps"
6557 *
6558 * Standard does not say that "trap" in subshell shall print
6559 * parent shell's traps. It only says that its output
6560 * must have suitable form, but then, in the above example
6561 * (which is not supposed to be normative), it implies that.
6562 *
6563 * bash (and probably other shell) does implement it
6564 * (traps are reset to defaults, but "trap" still shows them),
6565 * but as a result, "trap" logic is hopelessly messed up:
6566 *
6567 * # trap
6568 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6569 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6570 * # true | trap <--- trap is in subshell - no output (ditto)
6571 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6572 * trap -- 'echo Ho' SIGWINCH
6573 * # echo `(trap)` <--- in subshell in subshell - output
6574 * trap -- 'echo Ho' SIGWINCH
6575 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6576 * trap -- 'echo Ho' SIGWINCH
6577 *
6578 * The rules when to forget and when to not forget traps
6579 * get really complex and nonsensical.
6580 *
6581 * Our solution: ONLY bare $(trap) or `trap` is special.
6582 */
6583 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006584 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006585 && skip_whitespace(s + 4)[0] == '\0'
6586 ) {
6587 static const char *const argv[] = { NULL, NULL };
6588 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006589 fflush_all(); /* important */
6590 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006591 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006592# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006593# if BB_MMU
6594 reset_traps_to_defaults();
6595 parse_and_run_string(s);
6596 _exit(G.last_exitcode);
6597# else
6598 /* We re-execute after vfork on NOMMU. This makes this script safe:
6599 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6600 * huge=`cat BIG` # was blocking here forever
6601 * echo OK
6602 */
6603 re_execute_shell(&to_free,
6604 s,
6605 G.global_argv[0],
6606 G.global_argv + 1,
6607 NULL);
6608# endif
6609 }
6610
6611 /* parent */
6612 *pid_p = pid;
6613# if ENABLE_HUSH_FAST
6614 G.count_SIGCHLD++;
6615//bb_error_msg("[%d] fork in generate_stream_from_string:"
6616// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6617// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6618# endif
6619 enable_restore_tty_pgrp_on_exit();
6620# if !BB_MMU
6621 free(to_free);
6622# endif
6623 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006624 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006625}
6626
6627/* Return code is exit status of the process that is run. */
6628static int process_command_subs(o_string *dest, const char *s)
6629{
6630 FILE *fp;
6631 struct in_str pipe_str;
6632 pid_t pid;
6633 int status, ch, eol_cnt;
6634
6635 fp = generate_stream_from_string(s, &pid);
6636
6637 /* Now send results of command back into original context */
6638 setup_file_in_str(&pipe_str, fp);
6639 eol_cnt = 0;
6640 while ((ch = i_getch(&pipe_str)) != EOF) {
6641 if (ch == '\n') {
6642 eol_cnt++;
6643 continue;
6644 }
6645 while (eol_cnt) {
6646 o_addchr(dest, '\n');
6647 eol_cnt--;
6648 }
6649 o_addQchr(dest, ch);
6650 }
6651
6652 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006653 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006654 /* We need to extract exitcode. Test case
6655 * "true; echo `sleep 1; false` $?"
6656 * should print 1 */
6657 safe_waitpid(pid, &status, 0);
6658 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6659 return WEXITSTATUS(status);
6660}
6661#endif /* ENABLE_HUSH_TICK */
6662
6663
6664static void setup_heredoc(struct redir_struct *redir)
6665{
6666 struct fd_pair pair;
6667 pid_t pid;
6668 int len, written;
6669 /* the _body_ of heredoc (misleading field name) */
6670 const char *heredoc = redir->rd_filename;
6671 char *expanded;
6672#if !BB_MMU
6673 char **to_free;
6674#endif
6675
6676 expanded = NULL;
6677 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006678 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006679 if (expanded)
6680 heredoc = expanded;
6681 }
6682 len = strlen(heredoc);
6683
6684 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6685 xpiped_pair(pair);
6686 xmove_fd(pair.rd, redir->rd_fd);
6687
6688 /* Try writing without forking. Newer kernels have
6689 * dynamically growing pipes. Must use non-blocking write! */
6690 ndelay_on(pair.wr);
6691 while (1) {
6692 written = write(pair.wr, heredoc, len);
6693 if (written <= 0)
6694 break;
6695 len -= written;
6696 if (len == 0) {
6697 close(pair.wr);
6698 free(expanded);
6699 return;
6700 }
6701 heredoc += written;
6702 }
6703 ndelay_off(pair.wr);
6704
6705 /* Okay, pipe buffer was not big enough */
6706 /* Note: we must not create a stray child (bastard? :)
6707 * for the unsuspecting parent process. Child creates a grandchild
6708 * and exits before parent execs the process which consumes heredoc
6709 * (that exec happens after we return from this function) */
6710#if !BB_MMU
6711 to_free = NULL;
6712#endif
6713 pid = xvfork();
6714 if (pid == 0) {
6715 /* child */
6716 disable_restore_tty_pgrp_on_exit();
6717 pid = BB_MMU ? xfork() : xvfork();
6718 if (pid != 0)
6719 _exit(0);
6720 /* grandchild */
6721 close(redir->rd_fd); /* read side of the pipe */
6722#if BB_MMU
6723 full_write(pair.wr, heredoc, len); /* may loop or block */
6724 _exit(0);
6725#else
6726 /* Delegate blocking writes to another process */
6727 xmove_fd(pair.wr, STDOUT_FILENO);
6728 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6729#endif
6730 }
6731 /* parent */
6732#if ENABLE_HUSH_FAST
6733 G.count_SIGCHLD++;
6734//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6735#endif
6736 enable_restore_tty_pgrp_on_exit();
6737#if !BB_MMU
6738 free(to_free);
6739#endif
6740 close(pair.wr);
6741 free(expanded);
6742 wait(NULL); /* wait till child has died */
6743}
6744
Denys Vlasenko2db74612017-07-07 22:07:28 +02006745struct squirrel {
6746 int orig_fd;
6747 int moved_to;
6748 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6749 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6750};
6751
Denys Vlasenko621fc502017-07-24 12:42:17 +02006752static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6753{
6754 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6755 sq[i].orig_fd = orig;
6756 sq[i].moved_to = moved;
6757 sq[i+1].orig_fd = -1; /* end marker */
6758 return sq;
6759}
6760
Denys Vlasenko2db74612017-07-07 22:07:28 +02006761static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6762{
Denys Vlasenko621fc502017-07-24 12:42:17 +02006763 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006764 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02006765
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006766 i = 0;
6767 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006768 /* If we collide with an already moved fd... */
6769 if (fd == sq[i].moved_to) {
6770 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6771 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6772 if (sq[i].moved_to < 0) /* what? */
6773 xfunc_die();
6774 return sq;
6775 }
6776 if (fd == sq[i].orig_fd) {
6777 /* Example: echo Hello >/dev/null 1>&2 */
6778 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6779 return sq;
6780 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006781 }
6782
Denys Vlasenko2db74612017-07-07 22:07:28 +02006783 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko621fc502017-07-24 12:42:17 +02006784 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6785 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6786 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02006787 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02006788 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006789}
6790
Denys Vlasenko657e9002017-07-30 23:34:04 +02006791static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6792{
6793 int i;
6794
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006795 i = 0;
6796 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006797 /* If we collide with an already moved fd... */
6798 if (fd == sq[i].orig_fd) {
6799 /* Examples:
6800 * "echo 3>FILE 3>&- 3>FILE"
6801 * "echo 3>&- 3>FILE"
6802 * No need for last redirect to insert
6803 * another "need to close 3" indicator.
6804 */
6805 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6806 return sq;
6807 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006808 }
6809
6810 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6811 return append_squirrel(sq, i, fd, -1);
6812}
6813
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006814/* fd: redirect wants this fd to be used (e.g. 3>file).
6815 * Move all conflicting internally used fds,
6816 * and remember them so that we can restore them later.
6817 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006818static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006819{
Denys Vlasenko2db74612017-07-07 22:07:28 +02006820 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6821 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006822
6823#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006824 if (fd == G.interactive_fd) {
6825 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006826 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006827 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6828 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006829 }
6830#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006831 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6832 * (1) Redirect in a forked child. No need to save FILEs' fds,
6833 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02006834 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6835 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006836 * "fileno(fd) = new_fd" can't be done.
6837 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02006838 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006839 return 0;
6840
Denys Vlasenko2db74612017-07-07 22:07:28 +02006841 /* If this one of script's fds? */
6842 if (save_FILEs_on_redirect(fd, avoid_fd))
6843 return 1; /* yes. "we closed fd" */
6844
6845 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6846 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6847 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006848}
6849
Denys Vlasenko2db74612017-07-07 22:07:28 +02006850static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006851{
Denys Vlasenko2db74612017-07-07 22:07:28 +02006852 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006853 int i;
6854 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006855 if (sq[i].moved_to >= 0) {
6856 /* We simply die on error */
6857 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6858 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6859 } else {
6860 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6861 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6862 close(sq[i].orig_fd);
6863 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006864 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006865 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006866 }
6867
Denys Vlasenko2db74612017-07-07 22:07:28 +02006868 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006869
6870 restore_redirected_FILEs();
6871}
6872
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02006873#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02006874static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02006875{
6876 if (G_interactive_fd)
6877 close(G_interactive_fd);
6878 close_all_FILE_list();
6879}
6880#endif
6881
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006882static int internally_opened_fd(int fd, struct squirrel *sq)
6883{
6884 int i;
6885
6886#if ENABLE_HUSH_INTERACTIVE
6887 if (fd == G.interactive_fd)
6888 return 1;
6889#endif
6890 /* If this one of script's fds? */
6891 if (fd_in_FILEs(fd))
6892 return 1;
6893
6894 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6895 if (fd == sq[i].moved_to)
6896 return 1;
6897 }
6898 return 0;
6899}
6900
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006901/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6902 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02006903static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006904{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006905 struct redir_struct *redir;
6906
6907 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006908 int newfd;
6909 int closed;
6910
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006911 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006912 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006913 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006914 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6915 * of the heredoc */
6916 debug_printf_parse("set heredoc '%s'\n",
6917 redir->rd_filename);
6918 setup_heredoc(redir);
6919 continue;
6920 }
6921
6922 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006923 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006924 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02006925 int mode;
6926
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006927 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02006928 /*
6929 * Examples:
6930 * "cmd >" (no filename)
6931 * "cmd > <file" (2nd redirect starts too early)
6932 */
Denys Vlasenko39701202017-08-02 19:44:05 +02006933 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006934 continue;
6935 }
6936 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006937 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02006938 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006939 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02006940 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006941 /* Error message from open_or_warn can be lost
6942 * if stderr has been redirected, but bash
6943 * and ash both lose it as well
6944 * (though zsh doesn't!)
6945 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006946 return 1;
6947 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006948 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02006949 /* open() gave us precisely the fd we wanted.
6950 * This means that this fd was not busy
6951 * (not opened to anywhere).
6952 * Remember to close it on restore:
6953 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006954 *sqp = add_squirrel_closed(*sqp, newfd);
6955 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02006956 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006957 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006958 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
6959 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006960 }
6961
Denys Vlasenko657e9002017-07-30 23:34:04 +02006962 if (newfd == redir->rd_fd)
6963 continue;
6964
6965 /* if "N>FILE": move newfd to redir->rd_fd */
6966 /* if "N>&M": dup newfd to redir->rd_fd */
6967 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
6968
6969 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
6970 if (newfd == REDIRFD_CLOSE) {
6971 /* "N>&-" means "close me" */
6972 if (!closed) {
6973 /* ^^^ optimization: saving may already
6974 * have closed it. If not... */
6975 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006976 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006977 /* Sometimes we do another close on restore, getting EBADF.
6978 * Consider "echo 3>FILE 3>&-"
6979 * first redirect remembers "need to close 3",
6980 * and second redirect closes 3! Restore code then closes 3 again.
6981 */
6982 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006983 /* if newfd is a script fd or saved fd, simulate EBADF */
6984 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
6985 //errno = EBADF;
6986 //bb_perror_msg_and_die("can't duplicate file descriptor");
6987 newfd = -1; /* same effect as code above */
6988 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006989 xdup2(newfd, redir->rd_fd);
6990 if (redir->rd_dup == REDIRFD_TO_FILE)
6991 /* "rd_fd > FILE" */
6992 close(newfd);
6993 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006994 }
6995 }
6996 return 0;
6997}
6998
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006999static char *find_in_path(const char *arg)
7000{
7001 char *ret = NULL;
7002 const char *PATH = get_local_var_value("PATH");
7003
7004 if (!PATH)
7005 return NULL;
7006
7007 while (1) {
7008 const char *end = strchrnul(PATH, ':');
7009 int sz = end - PATH; /* must be int! */
7010
7011 free(ret);
7012 if (sz != 0) {
7013 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7014 } else {
7015 /* We have xxx::yyyy in $PATH,
7016 * it means "use current dir" */
7017 ret = xstrdup(arg);
7018 }
7019 if (access(ret, F_OK) == 0)
7020 break;
7021
7022 if (*end == '\0') {
7023 free(ret);
7024 return NULL;
7025 }
7026 PATH = end + 1;
7027 }
7028
7029 return ret;
7030}
7031
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007032static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007033 const struct built_in_command *x,
7034 const struct built_in_command *end)
7035{
7036 while (x != end) {
7037 if (strcmp(name, x->b_cmd) != 0) {
7038 x++;
7039 continue;
7040 }
7041 debug_printf_exec("found builtin '%s'\n", name);
7042 return x;
7043 }
7044 return NULL;
7045}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007046static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007047{
7048 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7049}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007050static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007051{
7052 const struct built_in_command *x = find_builtin1(name);
7053 if (x)
7054 return x;
7055 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7056}
7057
7058#if ENABLE_HUSH_FUNCTIONS
7059static struct function **find_function_slot(const char *name)
7060{
7061 struct function **funcpp = &G.top_func;
7062 while (*funcpp) {
7063 if (strcmp(name, (*funcpp)->name) == 0) {
7064 break;
7065 }
7066 funcpp = &(*funcpp)->next;
7067 }
7068 return funcpp;
7069}
7070
7071static const struct function *find_function(const char *name)
7072{
7073 const struct function *funcp = *find_function_slot(name);
7074 if (funcp)
7075 debug_printf_exec("found function '%s'\n", name);
7076 return funcp;
7077}
7078
7079/* Note: takes ownership on name ptr */
7080static struct function *new_function(char *name)
7081{
7082 struct function **funcpp = find_function_slot(name);
7083 struct function *funcp = *funcpp;
7084
7085 if (funcp != NULL) {
7086 struct command *cmd = funcp->parent_cmd;
7087 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7088 if (!cmd) {
7089 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7090 free(funcp->name);
7091 /* Note: if !funcp->body, do not free body_as_string!
7092 * This is a special case of "-F name body" function:
7093 * body_as_string was not malloced! */
7094 if (funcp->body) {
7095 free_pipe_list(funcp->body);
7096# if !BB_MMU
7097 free(funcp->body_as_string);
7098# endif
7099 }
7100 } else {
7101 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7102 cmd->argv[0] = funcp->name;
7103 cmd->group = funcp->body;
7104# if !BB_MMU
7105 cmd->group_as_string = funcp->body_as_string;
7106# endif
7107 }
7108 } else {
7109 debug_printf_exec("remembering new function '%s'\n", name);
7110 funcp = *funcpp = xzalloc(sizeof(*funcp));
7111 /*funcp->next = NULL;*/
7112 }
7113
7114 funcp->name = name;
7115 return funcp;
7116}
7117
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007118# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007119static void unset_func(const char *name)
7120{
7121 struct function **funcpp = find_function_slot(name);
7122 struct function *funcp = *funcpp;
7123
7124 if (funcp != NULL) {
7125 debug_printf_exec("freeing function '%s'\n", funcp->name);
7126 *funcpp = funcp->next;
7127 /* funcp is unlinked now, deleting it.
7128 * Note: if !funcp->body, the function was created by
7129 * "-F name body", do not free ->body_as_string
7130 * and ->name as they were not malloced. */
7131 if (funcp->body) {
7132 free_pipe_list(funcp->body);
7133 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007134# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007135 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007136# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007137 }
7138 free(funcp);
7139 }
7140}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007141# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007142
7143# if BB_MMU
7144#define exec_function(to_free, funcp, argv) \
7145 exec_function(funcp, argv)
7146# endif
7147static void exec_function(char ***to_free,
7148 const struct function *funcp,
7149 char **argv) NORETURN;
7150static void exec_function(char ***to_free,
7151 const struct function *funcp,
7152 char **argv)
7153{
7154# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007155 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007156
7157 argv[0] = G.global_argv[0];
7158 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007159 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007160
7161// Example when we are here: "cmd | func"
7162// func will run with saved-redirect fds open.
7163// $ f() { echo /proc/self/fd/*; }
7164// $ true | f
7165// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7166// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7167// Same in script:
7168// $ . ./SCRIPT
7169// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7170// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7171// They are CLOEXEC so external programs won't see them, but
7172// for "more correctness" we might want to close those extra fds here:
7173//? close_saved_fds_and_FILE_fds();
7174
7175 /* "we are in function, ok to use return" */
7176 G_flag_return_in_progress = -1;
7177 IF_HUSH_LOCAL(G.func_nest_level++;)
7178
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007179 /* On MMU, funcp->body is always non-NULL */
7180 n = run_list(funcp->body);
7181 fflush_all();
7182 _exit(n);
7183# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007184//? close_saved_fds_and_FILE_fds();
7185
7186//TODO: check whether "true | func_with_return" works
7187
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007188 re_execute_shell(to_free,
7189 funcp->body_as_string,
7190 G.global_argv[0],
7191 argv + 1,
7192 NULL);
7193# endif
7194}
7195
7196static int run_function(const struct function *funcp, char **argv)
7197{
7198 int rc;
7199 save_arg_t sv;
7200 smallint sv_flg;
7201
7202 save_and_replace_G_args(&sv, argv);
7203
7204 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007205 sv_flg = G_flag_return_in_progress;
7206 G_flag_return_in_progress = -1;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007207 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007208
7209 /* On MMU, funcp->body is always non-NULL */
7210# if !BB_MMU
7211 if (!funcp->body) {
7212 /* Function defined by -F */
7213 parse_and_run_string(funcp->body_as_string);
7214 rc = G.last_exitcode;
7215 } else
7216# endif
7217 {
7218 rc = run_list(funcp->body);
7219 }
7220
7221# if ENABLE_HUSH_LOCAL
7222 {
7223 struct variable *var;
7224 struct variable **var_pp;
7225
7226 var_pp = &G.top_var;
7227 while ((var = *var_pp) != NULL) {
7228 if (var->func_nest_level < G.func_nest_level) {
7229 var_pp = &var->next;
7230 continue;
7231 }
7232 /* Unexport */
7233 if (var->flg_export)
7234 bb_unsetenv(var->varstr);
7235 /* Remove from global list */
7236 *var_pp = var->next;
7237 /* Free */
7238 if (!var->max_len)
7239 free(var->varstr);
7240 free(var);
7241 }
7242 G.func_nest_level--;
7243 }
7244# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007245 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007246
7247 restore_G_args(&sv, argv);
7248
7249 return rc;
7250}
7251#endif /* ENABLE_HUSH_FUNCTIONS */
7252
7253
7254#if BB_MMU
7255#define exec_builtin(to_free, x, argv) \
7256 exec_builtin(x, argv)
7257#else
7258#define exec_builtin(to_free, x, argv) \
7259 exec_builtin(to_free, argv)
7260#endif
7261static void exec_builtin(char ***to_free,
7262 const struct built_in_command *x,
7263 char **argv) NORETURN;
7264static void exec_builtin(char ***to_free,
7265 const struct built_in_command *x,
7266 char **argv)
7267{
7268#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007269 int rcode;
7270 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007271//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007272 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007273 fflush_all();
7274 _exit(rcode);
7275#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007276 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007277 /* On NOMMU, we must never block!
7278 * Example: { sleep 99 | read line; } & echo Ok
7279 */
7280 re_execute_shell(to_free,
7281 argv[0],
7282 G.global_argv[0],
7283 G.global_argv + 1,
7284 argv);
7285#endif
7286}
7287
7288
7289static void execvp_or_die(char **argv) NORETURN;
7290static void execvp_or_die(char **argv)
7291{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007292 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007293 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007294 /* Don't propagate SIG_IGN to the child */
7295 if (SPECIAL_JOBSTOP_SIGS != 0)
7296 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007297 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007298 e = 2;
7299 if (errno == EACCES) e = 126;
7300 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007301 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007302 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007303}
7304
7305#if ENABLE_HUSH_MODE_X
7306static void dump_cmd_in_x_mode(char **argv)
7307{
7308 if (G_x_mode && argv) {
7309 /* We want to output the line in one write op */
7310 char *buf, *p;
7311 int len;
7312 int n;
7313
7314 len = 3;
7315 n = 0;
7316 while (argv[n])
7317 len += strlen(argv[n++]) + 1;
7318 buf = xmalloc(len);
7319 buf[0] = '+';
7320 p = buf + 1;
7321 n = 0;
7322 while (argv[n])
7323 p += sprintf(p, " %s", argv[n++]);
7324 *p++ = '\n';
7325 *p = '\0';
7326 fputs(buf, stderr);
7327 free(buf);
7328 }
7329}
7330#else
7331# define dump_cmd_in_x_mode(argv) ((void)0)
7332#endif
7333
7334#if BB_MMU
7335#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7336 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7337#define pseudo_exec(nommu_save, command, argv_expanded) \
7338 pseudo_exec(command, argv_expanded)
7339#endif
7340
7341/* Called after [v]fork() in run_pipe, or from builtin_exec.
7342 * Never returns.
7343 * Don't exit() here. If you don't exec, use _exit instead.
7344 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007345 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007346 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007347static void pseudo_exec_argv(nommu_save_t *nommu_save,
7348 char **argv, int assignment_cnt,
7349 char **argv_expanded) NORETURN;
7350static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7351 char **argv, int assignment_cnt,
7352 char **argv_expanded)
7353{
7354 char **new_env;
7355
7356 new_env = expand_assignments(argv, assignment_cnt);
7357 dump_cmd_in_x_mode(new_env);
7358
7359 if (!argv[assignment_cnt]) {
7360 /* Case when we are here: ... | var=val | ...
7361 * (note that we do not exit early, i.e., do not optimize out
7362 * expand_assignments(): think about ... | var=`sleep 1` | ...
7363 */
7364 free_strings(new_env);
7365 _exit(EXIT_SUCCESS);
7366 }
7367
7368#if BB_MMU
7369 set_vars_and_save_old(new_env);
7370 free(new_env); /* optional */
7371 /* we can also destroy set_vars_and_save_old's return value,
7372 * to save memory */
7373#else
7374 nommu_save->new_env = new_env;
7375 nommu_save->old_vars = set_vars_and_save_old(new_env);
7376#endif
7377
7378 if (argv_expanded) {
7379 argv = argv_expanded;
7380 } else {
7381 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7382#if !BB_MMU
7383 nommu_save->argv = argv;
7384#endif
7385 }
7386 dump_cmd_in_x_mode(argv);
7387
7388#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7389 if (strchr(argv[0], '/') != NULL)
7390 goto skip;
7391#endif
7392
Denys Vlasenko75481d32017-07-31 05:27:09 +02007393#if ENABLE_HUSH_FUNCTIONS
7394 /* Check if the command matches any functions (this goes before bltins) */
7395 {
7396 const struct function *funcp = find_function(argv[0]);
7397 if (funcp) {
7398 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7399 }
7400 }
7401#endif
7402
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007403 /* Check if the command matches any of the builtins.
7404 * Depending on context, this might be redundant. But it's
7405 * easier to waste a few CPU cycles than it is to figure out
7406 * if this is one of those cases.
7407 */
7408 {
7409 /* On NOMMU, it is more expensive to re-execute shell
7410 * just in order to run echo or test builtin.
7411 * It's better to skip it here and run corresponding
7412 * non-builtin later. */
7413 const struct built_in_command *x;
7414 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7415 if (x) {
7416 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7417 }
7418 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007419
7420#if ENABLE_FEATURE_SH_STANDALONE
7421 /* Check if the command matches any busybox applets */
7422 {
7423 int a = find_applet_by_name(argv[0]);
7424 if (a >= 0) {
7425# if BB_MMU /* see above why on NOMMU it is not allowed */
7426 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007427 /* Do not leak open fds from opened script files etc.
7428 * Testcase: interactive "ls -l /proc/self/fd"
7429 * should not show tty fd open.
7430 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007431 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007432//FIXME: should also close saved redir fds
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007433 /* Without this, "rm -i FILE" can't be ^C'ed: */
7434 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007435 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007436 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007437 }
7438# endif
7439 /* Re-exec ourselves */
7440 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007441 /* Don't propagate SIG_IGN to the child */
7442 if (SPECIAL_JOBSTOP_SIGS != 0)
7443 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007444 execv(bb_busybox_exec_path, argv);
7445 /* If they called chroot or otherwise made the binary no longer
7446 * executable, fall through */
7447 }
7448 }
7449#endif
7450
7451#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7452 skip:
7453#endif
7454 execvp_or_die(argv);
7455}
7456
7457/* Called after [v]fork() in run_pipe
7458 */
7459static void pseudo_exec(nommu_save_t *nommu_save,
7460 struct command *command,
7461 char **argv_expanded) NORETURN;
7462static void pseudo_exec(nommu_save_t *nommu_save,
7463 struct command *command,
7464 char **argv_expanded)
7465{
7466 if (command->argv) {
7467 pseudo_exec_argv(nommu_save, command->argv,
7468 command->assignment_cnt, argv_expanded);
7469 }
7470
7471 if (command->group) {
7472 /* Cases when we are here:
7473 * ( list )
7474 * { list } &
7475 * ... | ( list ) | ...
7476 * ... | { list } | ...
7477 */
7478#if BB_MMU
7479 int rcode;
7480 debug_printf_exec("pseudo_exec: run_list\n");
7481 reset_traps_to_defaults();
7482 rcode = run_list(command->group);
7483 /* OK to leak memory by not calling free_pipe_list,
7484 * since this process is about to exit */
7485 _exit(rcode);
7486#else
7487 re_execute_shell(&nommu_save->argv_from_re_execing,
7488 command->group_as_string,
7489 G.global_argv[0],
7490 G.global_argv + 1,
7491 NULL);
7492#endif
7493 }
7494
7495 /* Case when we are here: ... | >file */
7496 debug_printf_exec("pseudo_exec'ed null command\n");
7497 _exit(EXIT_SUCCESS);
7498}
7499
7500#if ENABLE_HUSH_JOB
7501static const char *get_cmdtext(struct pipe *pi)
7502{
7503 char **argv;
7504 char *p;
7505 int len;
7506
7507 /* This is subtle. ->cmdtext is created only on first backgrounding.
7508 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7509 * On subsequent bg argv is trashed, but we won't use it */
7510 if (pi->cmdtext)
7511 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007512
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007513 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007514 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007515 pi->cmdtext = xzalloc(1);
7516 return pi->cmdtext;
7517 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007518 len = 0;
7519 do {
7520 len += strlen(*argv) + 1;
7521 } while (*++argv);
7522 p = xmalloc(len);
7523 pi->cmdtext = p;
7524 argv = pi->cmds[0].argv;
7525 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007526 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007527 *p++ = ' ';
7528 } while (*++argv);
7529 p[-1] = '\0';
7530 return pi->cmdtext;
7531}
7532
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007533static void remove_job_from_table(struct pipe *pi)
7534{
7535 struct pipe *prev_pipe;
7536
7537 if (pi == G.job_list) {
7538 G.job_list = pi->next;
7539 } else {
7540 prev_pipe = G.job_list;
7541 while (prev_pipe->next != pi)
7542 prev_pipe = prev_pipe->next;
7543 prev_pipe->next = pi->next;
7544 }
7545 G.last_jobid = 0;
7546 if (G.job_list)
7547 G.last_jobid = G.job_list->jobid;
7548}
7549
7550static void delete_finished_job(struct pipe *pi)
7551{
7552 remove_job_from_table(pi);
7553 free_pipe(pi);
7554}
7555
7556static void clean_up_last_dead_job(void)
7557{
7558 if (G.job_list && !G.job_list->alive_cmds)
7559 delete_finished_job(G.job_list);
7560}
7561
Denys Vlasenko16096292017-07-10 10:00:28 +02007562static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007563{
7564 struct pipe *job, **jobp;
7565 int i;
7566
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007567 clean_up_last_dead_job();
7568
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007569 /* Find the end of the list, and find next job ID to use */
7570 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007571 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007572 while ((job = *jobp) != NULL) {
7573 if (job->jobid > i)
7574 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007575 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007576 }
7577 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007578
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007579 /* Create a new job struct at the end */
7580 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007581 job->next = NULL;
7582 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7583 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7584 for (i = 0; i < pi->num_cmds; i++) {
7585 job->cmds[i].pid = pi->cmds[i].pid;
7586 /* all other fields are not used and stay zero */
7587 }
7588 job->cmdtext = xstrdup(get_cmdtext(pi));
7589
7590 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007591 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007592 G.last_jobid = job->jobid;
7593}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007594#endif /* JOB */
7595
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007596static int job_exited_or_stopped(struct pipe *pi)
7597{
7598 int rcode, i;
7599
7600 if (pi->alive_cmds != pi->stopped_cmds)
7601 return -1;
7602
7603 /* All processes in fg pipe have exited or stopped */
7604 rcode = 0;
7605 i = pi->num_cmds;
7606 while (--i >= 0) {
7607 rcode = pi->cmds[i].cmd_exitcode;
7608 /* usually last process gives overall exitstatus,
7609 * but with "set -o pipefail", last *failed* process does */
7610 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7611 break;
7612 }
7613 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7614 return rcode;
7615}
7616
Denys Vlasenko7e675362016-10-28 21:57:31 +02007617static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007618{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007619#if ENABLE_HUSH_JOB
7620 struct pipe *pi;
7621#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007622 int i, dead;
7623
7624 dead = WIFEXITED(status) || WIFSIGNALED(status);
7625
7626#if DEBUG_JOBS
7627 if (WIFSTOPPED(status))
7628 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7629 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7630 if (WIFSIGNALED(status))
7631 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7632 childpid, WTERMSIG(status), WEXITSTATUS(status));
7633 if (WIFEXITED(status))
7634 debug_printf_jobs("pid %d exited, exitcode %d\n",
7635 childpid, WEXITSTATUS(status));
7636#endif
7637 /* Were we asked to wait for a fg pipe? */
7638 if (fg_pipe) {
7639 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007640
Denys Vlasenko7e675362016-10-28 21:57:31 +02007641 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007642 int rcode;
7643
Denys Vlasenko7e675362016-10-28 21:57:31 +02007644 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7645 if (fg_pipe->cmds[i].pid != childpid)
7646 continue;
7647 if (dead) {
7648 int ex;
7649 fg_pipe->cmds[i].pid = 0;
7650 fg_pipe->alive_cmds--;
7651 ex = WEXITSTATUS(status);
7652 /* bash prints killer signal's name for *last*
7653 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7654 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7655 */
7656 if (WIFSIGNALED(status)) {
7657 int sig = WTERMSIG(status);
7658 if (i == fg_pipe->num_cmds-1)
7659 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7660 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7661 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7662 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7663 * Maybe we need to use sig | 128? */
7664 ex = sig + 128;
7665 }
7666 fg_pipe->cmds[i].cmd_exitcode = ex;
7667 } else {
7668 fg_pipe->stopped_cmds++;
7669 }
7670 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7671 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007672 rcode = job_exited_or_stopped(fg_pipe);
7673 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007674/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7675 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7676 * and "killall -STOP cat" */
7677 if (G_interactive_fd) {
7678#if ENABLE_HUSH_JOB
7679 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02007680 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007681#endif
7682 return rcode;
7683 }
7684 if (fg_pipe->alive_cmds == 0)
7685 return rcode;
7686 }
7687 /* There are still running processes in the fg_pipe */
7688 return -1;
7689 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02007690 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02007691 }
7692
7693#if ENABLE_HUSH_JOB
7694 /* We were asked to wait for bg or orphaned children */
7695 /* No need to remember exitcode in this case */
7696 for (pi = G.job_list; pi; pi = pi->next) {
7697 for (i = 0; i < pi->num_cmds; i++) {
7698 if (pi->cmds[i].pid == childpid)
7699 goto found_pi_and_prognum;
7700 }
7701 }
7702 /* Happens when shell is used as init process (init=/bin/sh) */
7703 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7704 return -1; /* this wasn't a process from fg_pipe */
7705
7706 found_pi_and_prognum:
7707 if (dead) {
7708 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02007709 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007710 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02007711 rcode = 128 + WTERMSIG(status);
7712 pi->cmds[i].cmd_exitcode = rcode;
7713 if (G.last_bg_pid == pi->cmds[i].pid)
7714 G.last_bg_pid_exitcode = rcode;
7715 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007716 pi->alive_cmds--;
7717 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007718 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007719 printf(JOB_STATUS_FORMAT, pi->jobid,
7720 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007721 delete_finished_job(pi);
7722 } else {
7723/*
7724 * bash deletes finished jobs from job table only in interactive mode,
7725 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7726 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7727 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7728 * We only retain one "dead" job, if it's the single job on the list.
7729 * This covers most of real-world scenarios where this is useful.
7730 */
7731 if (pi != G.job_list)
7732 delete_finished_job(pi);
7733 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007734 }
7735 } else {
7736 /* child stopped */
7737 pi->stopped_cmds++;
7738 }
7739#endif
7740 return -1; /* this wasn't a process from fg_pipe */
7741}
7742
7743/* Check to see if any processes have exited -- if they have,
7744 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007745 *
7746 * If non-NULL fg_pipe: wait for its completion or stop.
7747 * Return its exitcode or zero if stopped.
7748 *
7749 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7750 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7751 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7752 * or 0 if no children changed status.
7753 *
7754 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7755 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7756 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007757 */
7758static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7759{
7760 int attributes;
7761 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007762 int rcode = 0;
7763
7764 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7765
7766 attributes = WUNTRACED;
7767 if (fg_pipe == NULL)
7768 attributes |= WNOHANG;
7769
7770 errno = 0;
7771#if ENABLE_HUSH_FAST
7772 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7773//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7774//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7775 /* There was neither fork nor SIGCHLD since last waitpid */
7776 /* Avoid doing waitpid syscall if possible */
7777 if (!G.we_have_children) {
7778 errno = ECHILD;
7779 return -1;
7780 }
7781 if (fg_pipe == NULL) { /* is WNOHANG set? */
7782 /* We have children, but they did not exit
7783 * or stop yet (we saw no SIGCHLD) */
7784 return 0;
7785 }
7786 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7787 }
7788#endif
7789
7790/* Do we do this right?
7791 * bash-3.00# sleep 20 | false
7792 * <ctrl-Z pressed>
7793 * [3]+ Stopped sleep 20 | false
7794 * bash-3.00# echo $?
7795 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7796 * [hush 1.14.0: yes we do it right]
7797 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007798 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007799 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007800#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02007801 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007802 i = G.count_SIGCHLD;
7803#endif
7804 childpid = waitpid(-1, &status, attributes);
7805 if (childpid <= 0) {
7806 if (childpid && errno != ECHILD)
7807 bb_perror_msg("waitpid");
7808#if ENABLE_HUSH_FAST
7809 else { /* Until next SIGCHLD, waitpid's are useless */
7810 G.we_have_children = (childpid == 0);
7811 G.handled_SIGCHLD = i;
7812//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7813 }
7814#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007815 /* ECHILD (no children), or 0 (no change in children status) */
7816 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007817 break;
7818 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007819 rcode = process_wait_result(fg_pipe, childpid, status);
7820 if (rcode >= 0) {
7821 /* fg_pipe exited or stopped */
7822 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007823 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007824 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007825 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007826 rcode = WEXITSTATUS(status);
7827 if (WIFSIGNALED(status))
7828 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007829 if (WIFSTOPPED(status))
7830 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7831 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007832 rcode++;
7833 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007834 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007835 /* This wasn't one of our processes, or */
7836 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007837 } /* while (waitpid succeeds)... */
7838
7839 return rcode;
7840}
7841
7842#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007843static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007844{
7845 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007846 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007847 if (G_saved_tty_pgrp) {
7848 /* Job finished, move the shell to the foreground */
7849 p = getpgrp(); /* our process group id */
7850 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7851 tcsetpgrp(G_interactive_fd, p);
7852 }
7853 return rcode;
7854}
7855#endif
7856
7857/* Start all the jobs, but don't wait for anything to finish.
7858 * See checkjobs().
7859 *
7860 * Return code is normally -1, when the caller has to wait for children
7861 * to finish to determine the exit status of the pipe. If the pipe
7862 * is a simple builtin command, however, the action is done by the
7863 * time run_pipe returns, and the exit code is provided as the
7864 * return value.
7865 *
7866 * Returns -1 only if started some children. IOW: we have to
7867 * mask out retvals of builtins etc with 0xff!
7868 *
7869 * The only case when we do not need to [v]fork is when the pipe
7870 * is single, non-backgrounded, non-subshell command. Examples:
7871 * cmd ; ... { list } ; ...
7872 * cmd && ... { list } && ...
7873 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007874 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007875 * or (if SH_STANDALONE) an applet, and we can run the { list }
7876 * with run_list. If it isn't one of these, we fork and exec cmd.
7877 *
7878 * Cases when we must fork:
7879 * non-single: cmd | cmd
7880 * backgrounded: cmd & { list } &
7881 * subshell: ( list ) [&]
7882 */
7883#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007884#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007885 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7886#endif
7887static int redirect_and_varexp_helper(char ***new_env_p,
7888 struct variable **old_vars_p,
7889 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02007890 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007891 char **argv_expanded)
7892{
7893 /* setup_redirects acts on file descriptors, not FILEs.
7894 * This is perfect for work that comes after exec().
7895 * Is it really safe for inline use? Experimentally,
7896 * things seem to work. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007897 int rcode = setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007898 if (rcode == 0) {
7899 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7900 *new_env_p = new_env;
7901 dump_cmd_in_x_mode(new_env);
7902 dump_cmd_in_x_mode(argv_expanded);
7903 if (old_vars_p)
7904 *old_vars_p = set_vars_and_save_old(new_env);
7905 }
7906 return rcode;
7907}
7908static NOINLINE int run_pipe(struct pipe *pi)
7909{
7910 static const char *const null_ptr = NULL;
7911
7912 int cmd_no;
7913 int next_infd;
7914 struct command *command;
7915 char **argv_expanded;
7916 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007917 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007918 int rcode;
7919
7920 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7921 debug_enter();
7922
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007923 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7924 * Result should be 3 lines: q w e, qwe, q w e
7925 */
7926 G.ifs = get_local_var_value("IFS");
7927 if (!G.ifs)
7928 G.ifs = defifs;
7929
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007930 IF_HUSH_JOB(pi->pgrp = -1;)
7931 pi->stopped_cmds = 0;
7932 command = &pi->cmds[0];
7933 argv_expanded = NULL;
7934
7935 if (pi->num_cmds != 1
7936 || pi->followup == PIPE_BG
7937 || command->cmd_type == CMD_SUBSHELL
7938 ) {
7939 goto must_fork;
7940 }
7941
7942 pi->alive_cmds = 1;
7943
7944 debug_printf_exec(": group:%p argv:'%s'\n",
7945 command->group, command->argv ? command->argv[0] : "NONE");
7946
7947 if (command->group) {
7948#if ENABLE_HUSH_FUNCTIONS
7949 if (command->cmd_type == CMD_FUNCDEF) {
7950 /* "executing" func () { list } */
7951 struct function *funcp;
7952
7953 funcp = new_function(command->argv[0]);
7954 /* funcp->name is already set to argv[0] */
7955 funcp->body = command->group;
7956# if !BB_MMU
7957 funcp->body_as_string = command->group_as_string;
7958 command->group_as_string = NULL;
7959# endif
7960 command->group = NULL;
7961 command->argv[0] = NULL;
7962 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7963 funcp->parent_cmd = command;
7964 command->child_func = funcp;
7965
7966 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7967 debug_leave();
7968 return EXIT_SUCCESS;
7969 }
7970#endif
7971 /* { list } */
7972 debug_printf("non-subshell group\n");
7973 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007974 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007975 debug_printf_exec(": run_list\n");
7976 rcode = run_list(command->group) & 0xff;
7977 }
7978 restore_redirects(squirrel);
7979 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7980 debug_leave();
7981 debug_printf_exec("run_pipe: return %d\n", rcode);
7982 return rcode;
7983 }
7984
7985 argv = command->argv ? command->argv : (char **) &null_ptr;
7986 {
7987 const struct built_in_command *x;
7988#if ENABLE_HUSH_FUNCTIONS
7989 const struct function *funcp;
7990#else
7991 enum { funcp = 0 };
7992#endif
7993 char **new_env = NULL;
7994 struct variable *old_vars = NULL;
7995
7996 if (argv[command->assignment_cnt] == NULL) {
7997 /* Assignments, but no command */
7998 /* Ensure redirects take effect (that is, create files).
7999 * Try "a=t >file" */
8000#if 0 /* A few cases in testsuite fail with this code. FIXME */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008001 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008002 /* Set shell variables */
8003 if (new_env) {
8004 argv = new_env;
8005 while (*argv) {
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008006 if (set_local_var(*argv, /*flag:*/ 0)) {
8007 /* assignment to readonly var / putenv error? */
8008 rcode = 1;
8009 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008010 argv++;
8011 }
8012 }
8013 /* Redirect error sets $? to 1. Otherwise,
8014 * if evaluating assignment value set $?, retain it.
8015 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8016 if (rcode == 0)
8017 rcode = G.last_exitcode;
8018 /* Exit, _skipping_ variable restoring code: */
8019 goto clean_up_and_ret0;
8020
8021#else /* Older, bigger, but more correct code */
8022
Denys Vlasenko2db74612017-07-07 22:07:28 +02008023 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008024 restore_redirects(squirrel);
8025 /* Set shell variables */
8026 if (G_x_mode)
8027 bb_putchar_stderr('+');
8028 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02008029 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008030 if (G_x_mode)
8031 fprintf(stderr, " %s", p);
8032 debug_printf_exec("set shell var:'%s'->'%s'\n",
8033 *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008034 if (set_local_var(p, /*flag:*/ 0)) {
8035 /* assignment to readonly var / putenv error? */
8036 rcode = 1;
8037 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008038 argv++;
8039 }
8040 if (G_x_mode)
8041 bb_putchar_stderr('\n');
8042 /* Redirect error sets $? to 1. Otherwise,
8043 * if evaluating assignment value set $?, retain it.
8044 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8045 if (rcode == 0)
8046 rcode = G.last_exitcode;
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#endif
8052 }
8053
8054 /* Expand the rest into (possibly) many strings each */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01008055#if BASH_TEST2
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008056 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008057 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008058 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008059#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008060 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008061 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8062 }
8063
8064 /* if someone gives us an empty string: `cmd with empty output` */
8065 if (!argv_expanded[0]) {
8066 free(argv_expanded);
8067 debug_leave();
8068 return G.last_exitcode;
8069 }
8070
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008071#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko75481d32017-07-31 05:27:09 +02008072 /* Check if argv[0] matches any functions (this goes before bltins) */
8073 funcp = find_function(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008074#endif
Denys Vlasenko75481d32017-07-31 05:27:09 +02008075 x = NULL;
8076 if (!funcp)
8077 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008078 if (x || funcp) {
8079 if (!funcp) {
8080 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8081 debug_printf("exec with redirects only\n");
8082 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008083 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008084 goto clean_up_and_ret1;
8085 }
8086 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02008087 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008088 if (rcode == 0) {
8089 if (!funcp) {
8090 debug_printf_exec(": builtin '%s' '%s'...\n",
8091 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008092 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008093 rcode = x->b_function(argv_expanded) & 0xff;
8094 fflush_all();
8095 }
8096#if ENABLE_HUSH_FUNCTIONS
8097 else {
8098# if ENABLE_HUSH_LOCAL
8099 struct variable **sv;
8100 sv = G.shadowed_vars_pp;
8101 G.shadowed_vars_pp = &old_vars;
8102# endif
8103 debug_printf_exec(": function '%s' '%s'...\n",
8104 funcp->name, argv_expanded[1]);
8105 rcode = run_function(funcp, argv_expanded) & 0xff;
8106# if ENABLE_HUSH_LOCAL
8107 G.shadowed_vars_pp = sv;
8108# endif
8109 }
8110#endif
8111 }
8112 clean_up_and_ret:
8113 unset_vars(new_env);
8114 add_vars(old_vars);
8115/* clean_up_and_ret0: */
8116 restore_redirects(squirrel);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008117 /*
8118 * Try "usleep 99999999" + ^C + "echo $?"
8119 * with FEATURE_SH_NOFORK=y.
8120 */
8121 if (!funcp) {
8122 /* It was builtin or nofork.
8123 * if this would be a real fork/execed program,
8124 * it should have died if a fatal sig was received.
8125 * But OTOH, there was no separate process,
8126 * the sig was sent to _shell_, not to non-existing
8127 * child.
8128 * Let's just handle ^C only, this one is obvious:
8129 * we aren't ok with exitcode 0 when ^C was pressed
8130 * during builtin/nofork.
8131 */
8132 if (sigismember(&G.pending_set, SIGINT))
8133 rcode = 128 + SIGINT;
8134 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008135 clean_up_and_ret1:
8136 free(argv_expanded);
8137 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8138 debug_leave();
8139 debug_printf_exec("run_pipe return %d\n", rcode);
8140 return rcode;
8141 }
8142
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008143 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008144 int n = find_applet_by_name(argv_expanded[0]);
8145 if (n >= 0 && APPLET_IS_NOFORK(n)) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02008146 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008147 if (rcode == 0) {
8148 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8149 argv_expanded[0], argv_expanded[1]);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008150 /*
8151 * Note: signals (^C) can't interrupt here.
8152 * We remember them and they will be acted upon
8153 * after applet returns.
8154 * This makes applets which can run for a long time
8155 * and/or wait for user input ineligible for NOFORK:
8156 * for example, "yes" or "rm" (rm -i waits for input).
8157 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008158 rcode = run_nofork_applet(n, argv_expanded);
8159 }
8160 goto clean_up_and_ret;
8161 }
8162 }
8163 /* It is neither builtin nor applet. We must fork. */
8164 }
8165
8166 must_fork:
8167 /* NB: argv_expanded may already be created, and that
8168 * might include `cmd` runs! Do not rerun it! We *must*
8169 * use argv_expanded if it's non-NULL */
8170
8171 /* Going to fork a child per each pipe member */
8172 pi->alive_cmds = 0;
8173 next_infd = 0;
8174
8175 cmd_no = 0;
8176 while (cmd_no < pi->num_cmds) {
8177 struct fd_pair pipefds;
8178#if !BB_MMU
8179 volatile nommu_save_t nommu_save;
8180 nommu_save.new_env = NULL;
8181 nommu_save.old_vars = NULL;
8182 nommu_save.argv = NULL;
8183 nommu_save.argv_from_re_execing = NULL;
8184#endif
8185 command = &pi->cmds[cmd_no];
8186 cmd_no++;
8187 if (command->argv) {
8188 debug_printf_exec(": pipe member '%s' '%s'...\n",
8189 command->argv[0], command->argv[1]);
8190 } else {
8191 debug_printf_exec(": pipe member with no argv\n");
8192 }
8193
8194 /* pipes are inserted between pairs of commands */
8195 pipefds.rd = 0;
8196 pipefds.wr = 1;
8197 if (cmd_no < pi->num_cmds)
8198 xpiped_pair(pipefds);
8199
8200 command->pid = BB_MMU ? fork() : vfork();
8201 if (!command->pid) { /* child */
8202#if ENABLE_HUSH_JOB
8203 disable_restore_tty_pgrp_on_exit();
8204 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8205
8206 /* Every child adds itself to new process group
8207 * with pgid == pid_of_first_child_in_pipe */
8208 if (G.run_list_level == 1 && G_interactive_fd) {
8209 pid_t pgrp;
8210 pgrp = pi->pgrp;
8211 if (pgrp < 0) /* true for 1st process only */
8212 pgrp = getpid();
8213 if (setpgid(0, pgrp) == 0
8214 && pi->followup != PIPE_BG
8215 && G_saved_tty_pgrp /* we have ctty */
8216 ) {
8217 /* We do it in *every* child, not just first,
8218 * to avoid races */
8219 tcsetpgrp(G_interactive_fd, pgrp);
8220 }
8221 }
8222#endif
8223 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8224 /* 1st cmd in backgrounded pipe
8225 * should have its stdin /dev/null'ed */
8226 close(0);
8227 if (open(bb_dev_null, O_RDONLY))
8228 xopen("/", O_RDONLY);
8229 } else {
8230 xmove_fd(next_infd, 0);
8231 }
8232 xmove_fd(pipefds.wr, 1);
8233 if (pipefds.rd > 1)
8234 close(pipefds.rd);
8235 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008236 * and the pipe fd (fd#1) is available for dup'ing:
8237 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8238 * of cmd1 goes into pipe.
8239 */
8240 if (setup_redirects(command, NULL)) {
8241 /* Happens when redir file can't be opened:
8242 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8243 * FOO
8244 * hush: can't open '/qwe/rty': No such file or directory
8245 * BAZ
8246 * (echo BAR is not executed, it hits _exit(1) below)
8247 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008248 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008249 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008250
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008251 /* Stores to nommu_save list of env vars putenv'ed
8252 * (NOMMU, on MMU we don't need that) */
8253 /* cast away volatility... */
8254 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8255 /* pseudo_exec() does not return */
8256 }
8257
8258 /* parent or error */
8259#if ENABLE_HUSH_FAST
8260 G.count_SIGCHLD++;
8261//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8262#endif
8263 enable_restore_tty_pgrp_on_exit();
8264#if !BB_MMU
8265 /* Clean up after vforked child */
8266 free(nommu_save.argv);
8267 free(nommu_save.argv_from_re_execing);
8268 unset_vars(nommu_save.new_env);
8269 add_vars(nommu_save.old_vars);
8270#endif
8271 free(argv_expanded);
8272 argv_expanded = NULL;
8273 if (command->pid < 0) { /* [v]fork failed */
8274 /* Clearly indicate, was it fork or vfork */
8275 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8276 } else {
8277 pi->alive_cmds++;
8278#if ENABLE_HUSH_JOB
8279 /* Second and next children need to know pid of first one */
8280 if (pi->pgrp < 0)
8281 pi->pgrp = command->pid;
8282#endif
8283 }
8284
8285 if (cmd_no > 1)
8286 close(next_infd);
8287 if (cmd_no < pi->num_cmds)
8288 close(pipefds.wr);
8289 /* Pass read (output) pipe end to next iteration */
8290 next_infd = pipefds.rd;
8291 }
8292
8293 if (!pi->alive_cmds) {
8294 debug_leave();
8295 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8296 return 1;
8297 }
8298
8299 debug_leave();
8300 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8301 return -1;
8302}
8303
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008304/* NB: called by pseudo_exec, and therefore must not modify any
8305 * global data until exec/_exit (we can be a child after vfork!) */
8306static int run_list(struct pipe *pi)
8307{
8308#if ENABLE_HUSH_CASE
8309 char *case_word = NULL;
8310#endif
8311#if ENABLE_HUSH_LOOPS
8312 struct pipe *loop_top = NULL;
8313 char **for_lcur = NULL;
8314 char **for_list = NULL;
8315#endif
8316 smallint last_followup;
8317 smalluint rcode;
8318#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8319 smalluint cond_code = 0;
8320#else
8321 enum { cond_code = 0 };
8322#endif
8323#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008324 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008325 smallint last_rword; /* ditto */
8326#endif
8327
8328 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8329 debug_enter();
8330
8331#if ENABLE_HUSH_LOOPS
8332 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008333 {
8334 struct pipe *cpipe;
8335 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8336 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8337 continue;
8338 /* current word is FOR or IN (BOLD in comments below) */
8339 if (cpipe->next == NULL) {
8340 syntax_error("malformed for");
8341 debug_leave();
8342 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8343 return 1;
8344 }
8345 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8346 if (cpipe->next->res_word == RES_DO)
8347 continue;
8348 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8349 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8350 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8351 ) {
8352 syntax_error("malformed for");
8353 debug_leave();
8354 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8355 return 1;
8356 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008357 }
8358 }
8359#endif
8360
8361 /* Past this point, all code paths should jump to ret: label
8362 * in order to return, no direct "return" statements please.
8363 * This helps to ensure that no memory is leaked. */
8364
8365#if ENABLE_HUSH_JOB
8366 G.run_list_level++;
8367#endif
8368
8369#if HAS_KEYWORDS
8370 rword = RES_NONE;
8371 last_rword = RES_XXXX;
8372#endif
8373 last_followup = PIPE_SEQ;
8374 rcode = G.last_exitcode;
8375
8376 /* Go through list of pipes, (maybe) executing them. */
8377 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008378 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008379 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008380
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008381 if (G.flag_SIGINT)
8382 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008383 if (G_flag_return_in_progress == 1)
8384 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008385
8386 IF_HAS_KEYWORDS(rword = pi->res_word;)
8387 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8388 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008389
8390 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008391 if (
8392#if ENABLE_HUSH_IF
8393 rword == RES_IF || rword == RES_ELIF ||
8394#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008395 pi->followup != PIPE_SEQ
8396 ) {
8397 G.errexit_depth++;
8398 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008399#if ENABLE_HUSH_LOOPS
8400 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8401 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8402 ) {
8403 /* start of a loop: remember where loop starts */
8404 loop_top = pi;
8405 G.depth_of_loop++;
8406 }
8407#endif
8408 /* Still in the same "if...", "then..." or "do..." branch? */
8409 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8410 if ((rcode == 0 && last_followup == PIPE_OR)
8411 || (rcode != 0 && last_followup == PIPE_AND)
8412 ) {
8413 /* It is "<true> || CMD" or "<false> && CMD"
8414 * and we should not execute CMD */
8415 debug_printf_exec("skipped cmd because of || or &&\n");
8416 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008417 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008418 }
8419 }
8420 last_followup = pi->followup;
8421 IF_HAS_KEYWORDS(last_rword = rword;)
8422#if ENABLE_HUSH_IF
8423 if (cond_code) {
8424 if (rword == RES_THEN) {
8425 /* if false; then ... fi has exitcode 0! */
8426 G.last_exitcode = rcode = EXIT_SUCCESS;
8427 /* "if <false> THEN cmd": skip cmd */
8428 continue;
8429 }
8430 } else {
8431 if (rword == RES_ELSE || rword == RES_ELIF) {
8432 /* "if <true> then ... ELSE/ELIF cmd":
8433 * skip cmd and all following ones */
8434 break;
8435 }
8436 }
8437#endif
8438#if ENABLE_HUSH_LOOPS
8439 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8440 if (!for_lcur) {
8441 /* first loop through for */
8442
8443 static const char encoded_dollar_at[] ALIGN1 = {
8444 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8445 }; /* encoded representation of "$@" */
8446 static const char *const encoded_dollar_at_argv[] = {
8447 encoded_dollar_at, NULL
8448 }; /* argv list with one element: "$@" */
8449 char **vals;
8450
8451 vals = (char**)encoded_dollar_at_argv;
8452 if (pi->next->res_word == RES_IN) {
8453 /* if no variable values after "in" we skip "for" */
8454 if (!pi->next->cmds[0].argv) {
8455 G.last_exitcode = rcode = EXIT_SUCCESS;
8456 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8457 break;
8458 }
8459 vals = pi->next->cmds[0].argv;
8460 } /* else: "for var; do..." -> assume "$@" list */
8461 /* create list of variable values */
8462 debug_print_strings("for_list made from", vals);
8463 for_list = expand_strvec_to_strvec(vals);
8464 for_lcur = for_list;
8465 debug_print_strings("for_list", for_list);
8466 }
8467 if (!*for_lcur) {
8468 /* "for" loop is over, clean up */
8469 free(for_list);
8470 for_list = NULL;
8471 for_lcur = NULL;
8472 break;
8473 }
8474 /* Insert next value from for_lcur */
8475 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008476 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008477 continue;
8478 }
8479 if (rword == RES_IN) {
8480 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8481 }
8482 if (rword == RES_DONE) {
8483 continue; /* "done" has no cmds too */
8484 }
8485#endif
8486#if ENABLE_HUSH_CASE
8487 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008488 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008489 case_word = expand_strvec_to_string(pi->cmds->argv);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008490 unbackslash(case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008491 continue;
8492 }
8493 if (rword == RES_MATCH) {
8494 char **argv;
8495
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008496 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008497 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8498 break;
8499 /* all prev words didn't match, does this one match? */
8500 argv = pi->cmds->argv;
8501 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008502 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008503 /* TODO: which FNM_xxx flags to use? */
8504 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008505 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008506 free(pattern);
8507 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008508 free(case_word);
8509 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008510 break;
8511 }
8512 argv++;
8513 }
8514 continue;
8515 }
8516 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008517 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008518 if (cond_code != 0)
8519 continue; /* not matched yet, skip this pipe */
8520 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008521 if (rword == RES_ESAC) {
8522 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8523 if (case_word) {
8524 /* "case" did not match anything: still set $? (to 0) */
8525 G.last_exitcode = rcode = EXIT_SUCCESS;
8526 }
8527 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008528#endif
8529 /* Just pressing <enter> in shell should check for jobs.
8530 * OTOH, in non-interactive shell this is useless
8531 * and only leads to extra job checks */
8532 if (pi->num_cmds == 0) {
8533 if (G_interactive_fd)
8534 goto check_jobs_and_continue;
8535 continue;
8536 }
8537
8538 /* After analyzing all keywords and conditions, we decided
8539 * to execute this pipe. NB: have to do checkjobs(NULL)
8540 * after run_pipe to collect any background children,
8541 * even if list execution is to be stopped. */
8542 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008543#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008544 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008545#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008546 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8547 if (r != -1) {
8548 /* We ran a builtin, function, or group.
8549 * rcode is already known
8550 * and we don't need to wait for anything. */
8551 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8552 G.last_exitcode = rcode;
8553 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008554#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008555 /* Was it "break" or "continue"? */
8556 if (G.flag_break_continue) {
8557 smallint fbc = G.flag_break_continue;
8558 /* We might fall into outer *loop*,
8559 * don't want to break it too */
8560 if (loop_top) {
8561 G.depth_break_continue--;
8562 if (G.depth_break_continue == 0)
8563 G.flag_break_continue = 0;
8564 /* else: e.g. "continue 2" should *break* once, *then* continue */
8565 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8566 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008567 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008568 break;
8569 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008570 /* "continue": simulate end of loop */
8571 rword = RES_DONE;
8572 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008573 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008574#endif
8575 if (G_flag_return_in_progress == 1) {
8576 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8577 break;
8578 }
8579 } else if (pi->followup == PIPE_BG) {
8580 /* What does bash do with attempts to background builtins? */
8581 /* even bash 3.2 doesn't do that well with nested bg:
8582 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8583 * I'm NOT treating inner &'s as jobs */
8584#if ENABLE_HUSH_JOB
8585 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008586 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008587#endif
8588 /* Last command's pid goes to $! */
8589 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008590 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008591 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008592/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008593 rcode = EXIT_SUCCESS;
8594 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008595 } else {
8596#if ENABLE_HUSH_JOB
8597 if (G.run_list_level == 1 && G_interactive_fd) {
8598 /* Waits for completion, then fg's main shell */
8599 rcode = checkjobs_and_fg_shell(pi);
8600 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008601 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008602 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008603#endif
8604 /* This one just waits for completion */
8605 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8606 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8607 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008608 G.last_exitcode = rcode;
8609 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008610 }
8611
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008612 /* Handle "set -e" */
8613 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8614 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8615 if (G.errexit_depth == 0)
8616 hush_exit(rcode);
8617 }
8618 G.errexit_depth = sv_errexit_depth;
8619
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008620 /* Analyze how result affects subsequent commands */
8621#if ENABLE_HUSH_IF
8622 if (rword == RES_IF || rword == RES_ELIF)
8623 cond_code = rcode;
8624#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008625 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008626 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008627 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008628#if ENABLE_HUSH_LOOPS
8629 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008630 if (pi->next
8631 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008632 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008633 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008634 if (rword == RES_WHILE) {
8635 if (rcode) {
8636 /* "while false; do...done" - exitcode 0 */
8637 G.last_exitcode = rcode = EXIT_SUCCESS;
8638 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008639 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008640 }
8641 }
8642 if (rword == RES_UNTIL) {
8643 if (!rcode) {
8644 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008645 break;
8646 }
8647 }
8648 }
8649#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008650 } /* for (pi) */
8651
8652#if ENABLE_HUSH_JOB
8653 G.run_list_level--;
8654#endif
8655#if ENABLE_HUSH_LOOPS
8656 if (loop_top)
8657 G.depth_of_loop--;
8658 free(for_list);
8659#endif
8660#if ENABLE_HUSH_CASE
8661 free(case_word);
8662#endif
8663 debug_leave();
8664 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8665 return rcode;
8666}
8667
8668/* Select which version we will use */
8669static int run_and_free_list(struct pipe *pi)
8670{
8671 int rcode = 0;
8672 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008673 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008674 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8675 rcode = run_list(pi);
8676 }
8677 /* free_pipe_list has the side effect of clearing memory.
8678 * In the long run that function can be merged with run_list,
8679 * but doing that now would hobble the debugging effort. */
8680 free_pipe_list(pi);
8681 debug_printf_exec("run_and_free_list return %d\n", rcode);
8682 return rcode;
8683}
8684
8685
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008686static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008687{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008688 sighandler_t old_handler;
8689 unsigned sig = 0;
8690 while ((mask >>= 1) != 0) {
8691 sig++;
8692 if (!(mask & 1))
8693 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008694 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008695 /* POSIX allows shell to re-enable SIGCHLD
8696 * even if it was SIG_IGN on entry.
8697 * Therefore we skip IGN check for it:
8698 */
8699 if (sig == SIGCHLD)
8700 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02008701 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8702 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8703 */
8704 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008705 if (old_handler == SIG_IGN) {
8706 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008707 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008708#if ENABLE_HUSH_TRAP
8709 if (!G_traps)
8710 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8711 free(G_traps[sig]);
8712 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8713#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008714 }
8715 }
8716}
8717
8718/* Called a few times only (or even once if "sh -c") */
8719static void install_special_sighandlers(void)
8720{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008721 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008722
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008723 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008724 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008725 if (G_interactive_fd) {
8726 mask |= SPECIAL_INTERACTIVE_SIGS;
8727 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008728 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008729 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008730 /* Careful, do not re-install handlers we already installed */
8731 if (G.special_sig_mask != mask) {
8732 unsigned diff = mask & ~G.special_sig_mask;
8733 G.special_sig_mask = mask;
8734 install_sighandlers(diff);
8735 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008736}
8737
8738#if ENABLE_HUSH_JOB
8739/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008740/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008741static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008742{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008743 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008744
8745 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008746 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008747 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8748 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008749 + (1 << SIGBUS ) * HUSH_DEBUG
8750 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008751 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008752 + (1 << SIGABRT)
8753 /* bash 3.2 seems to handle these just like 'fatal' ones */
8754 + (1 << SIGPIPE)
8755 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008756 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008757 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008758 * we never want to restore pgrp on exit, and this fn is not called
8759 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008760 /*+ (1 << SIGHUP )*/
8761 /*+ (1 << SIGTERM)*/
8762 /*+ (1 << SIGINT )*/
8763 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008764 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008765
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008766 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008767}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00008768#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00008769
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008770static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00008771{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008772 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008773 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008774 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008775 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008776 break;
8777 case 'x':
8778 IF_HUSH_MODE_X(G_x_mode = state;)
8779 break;
8780 case 'o':
8781 if (!o_opt) {
8782 /* "set -+o" without parameter.
8783 * in bash, set -o produces this output:
8784 * pipefail off
8785 * and set +o:
8786 * set +o pipefail
8787 * We always use the second form.
8788 */
8789 const char *p = o_opt_strings;
8790 idx = 0;
8791 while (*p) {
8792 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8793 idx++;
8794 p += strlen(p) + 1;
8795 }
8796 break;
8797 }
8798 idx = index_in_strings(o_opt_strings, o_opt);
8799 if (idx >= 0) {
8800 G.o_opt[idx] = state;
8801 break;
8802 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008803 case 'e':
8804 G.o_opt[OPT_O_ERREXIT] = state;
8805 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008806 default:
8807 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008808 }
8809 return EXIT_SUCCESS;
8810}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008811
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00008812int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00008813int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00008814{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008815 enum {
8816 OPT_login = (1 << 0),
8817 };
8818 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00008819 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008820 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008821 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008822 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008823 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00008824
Denis Vlasenko574f2f42008-02-27 18:41:59 +00008825 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02008826 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008827 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008828
Denys Vlasenko10c01312011-05-11 11:49:21 +02008829#if ENABLE_HUSH_FAST
8830 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8831#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008832#if !BB_MMU
8833 G.argv0_for_re_execing = argv[0];
8834#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008835 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008836 shell_ver = xzalloc(sizeof(*shell_ver));
8837 shell_ver->flg_export = 1;
8838 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02008839 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02008840 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008841 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02008842 /* Create shell local variables from the values
8843 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00008844 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008845 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008846 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008847 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008848 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008849 if (e) while (*e) {
8850 char *value = strchr(*e, '=');
8851 if (value) { /* paranoia */
8852 cur_var->next = xzalloc(sizeof(*cur_var));
8853 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008854 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008855 cur_var->max_len = strlen(*e);
8856 cur_var->flg_export = 1;
8857 }
8858 e++;
8859 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008860 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008861 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8862 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008863
8864 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008865 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008866
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01008867#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008868 /* Set (but not export) HOSTNAME unless already set */
8869 if (!get_local_var_value("HOSTNAME")) {
8870 struct utsname uts;
8871 uname(&uts);
8872 set_local_var_from_halves("HOSTNAME", uts.nodename);
8873 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008874 /* bash also exports SHLVL and _,
8875 * and sets (but doesn't export) the following variables:
8876 * BASH=/bin/bash
8877 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8878 * BASH_VERSION='3.2.0(1)-release'
8879 * HOSTTYPE=i386
8880 * MACHTYPE=i386-pc-linux-gnu
8881 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008882 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008883 * EUID=<NNNNN>
8884 * UID=<NNNNN>
8885 * GROUPS=()
8886 * LINES=<NNN>
8887 * COLUMNS=<NNN>
8888 * BASH_ARGC=()
8889 * BASH_ARGV=()
8890 * BASH_LINENO=()
8891 * BASH_SOURCE=()
8892 * DIRSTACK=()
8893 * PIPESTATUS=([0]="0")
8894 * HISTFILE=/<xxx>/.bash_history
8895 * HISTFILESIZE=500
8896 * HISTSIZE=500
8897 * MAILCHECK=60
8898 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8899 * SHELL=/bin/bash
8900 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8901 * TERM=dumb
8902 * OPTERR=1
8903 * OPTIND=1
8904 * IFS=$' \t\n'
8905 * PS1='\s-\v\$ '
8906 * PS2='> '
8907 * PS4='+ '
8908 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008909#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008910
Denis Vlasenko38f63192007-01-22 09:03:07 +00008911#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008912 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008913#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008914
Eric Andersen94ac2442001-05-22 19:05:18 +00008915 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008916 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008917
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008918 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008919
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008920 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008921 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008922 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008923 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008924 * in order to intercept (more) signals.
8925 */
8926
8927 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008928 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008929 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008930 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008931 while (1) {
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008932 opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008933#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00008934 "<:$:R:V:"
8935# if ENABLE_HUSH_FUNCTIONS
8936 "F:"
8937# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008938#endif
8939 );
8940 if (opt <= 0)
8941 break;
Eric Andersen25f27032001-04-26 23:22:31 +00008942 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008943 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008944 /* Possibilities:
8945 * sh ... -c 'script'
8946 * sh ... -c 'script' ARG0 [ARG1...]
8947 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01008948 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008949 * "" needs to be replaced with NULL
8950 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01008951 * Note: the form without ARG0 never happens:
8952 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008953 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02008954 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008955 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008956 G.root_ppid = getppid();
8957 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008958 G.global_argv = argv + optind;
8959 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008960 if (builtin_argc) {
8961 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8962 const struct built_in_command *x;
8963
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008964 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008965 x = find_builtin(optarg);
8966 if (x) { /* paranoia */
8967 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8968 G.global_argv += builtin_argc;
8969 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008970 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01008971 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008972 }
8973 goto final_return;
8974 }
8975 if (!G.global_argv[0]) {
8976 /* -c 'script' (no params): prevent empty $0 */
8977 G.global_argv--; /* points to argv[i] of 'script' */
8978 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02008979 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008980 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008981 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008982 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008983 goto final_return;
8984 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00008985 /* Well, we cannot just declare interactiveness,
8986 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008987 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008988 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008989 case 's':
8990 /* "-s" means "read from stdin", but this is how we always
8991 * operate, so simply do nothing here. */
8992 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008993 case 'l':
8994 flags |= OPT_login;
8995 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008996#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008997 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02008998 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008999 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009000 case '$': {
9001 unsigned long long empty_trap_mask;
9002
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009003 G.root_pid = bb_strtou(optarg, &optarg, 16);
9004 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009005 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9006 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009007 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9008 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009009 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009010 optarg++;
9011 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009012 optarg++;
9013 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9014 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009015 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009016 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009017# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009018 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009019 for (sig = 1; sig < NSIG; sig++) {
9020 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009021 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009022 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009023 }
9024 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009025# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009026 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009027# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009028 optarg++;
9029 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009030# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009031 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009032 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009033 case 'R':
9034 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009035 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009036 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009037# if ENABLE_HUSH_FUNCTIONS
9038 case 'F': {
9039 struct function *funcp = new_function(optarg);
9040 /* funcp->name is already set to optarg */
9041 /* funcp->body is set to NULL. It's a special case. */
9042 funcp->body_as_string = argv[optind];
9043 optind++;
9044 break;
9045 }
9046# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009047#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009048 case 'n':
9049 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009050 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009051 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009052 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009053 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009054#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009055 fprintf(stderr, "Usage: sh [FILE]...\n"
9056 " or: sh -c command [args]...\n\n");
9057 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009058#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009059 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009060#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009061 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009062 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009063
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009064 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9065 G.global_argc = argc - (optind - 1);
9066 G.global_argv = argv + (optind - 1);
9067 G.global_argv[0] = argv[0];
9068
Denys Vlasenkodea47882009-10-09 15:40:49 +02009069 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009070 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009071 G.root_ppid = getppid();
9072 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009073
9074 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009075 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009076 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009077 debug_printf("sourcing /etc/profile\n");
9078 input = fopen_for_read("/etc/profile");
9079 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009080 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009081 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009082 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009083 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009084 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009085 /* bash: after sourcing /etc/profile,
9086 * tries to source (in the given order):
9087 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009088 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009089 * bash also sources ~/.bash_logout on exit.
9090 * If called as sh, skips .bash_XXX files.
9091 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009092 }
9093
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009094 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009095 FILE *input;
9096 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009097 * "bash <script>" (which is never interactive (unless -i?))
9098 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009099 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009100 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009101 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009102 G.global_argc--;
9103 G.global_argv++;
9104 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009105 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009106 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009107 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009108 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009109 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009110 parse_and_run_file(input);
9111#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009112 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009113#endif
9114 goto final_return;
9115 }
9116
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009117 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009118 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009119 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009120
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009121 /* A shell is interactive if the '-i' flag was given,
9122 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009123 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009124 * no arguments remaining or the -s flag given
9125 * standard input is a terminal
9126 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009127 * Refer to Posix.2, the description of the 'sh' utility.
9128 */
9129#if ENABLE_HUSH_JOB
9130 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009131 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9132 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9133 if (G_saved_tty_pgrp < 0)
9134 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009135
9136 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009137 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009138 if (G_interactive_fd < 0) {
9139 /* try to dup to any fd */
9140 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009141 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009142 /* give up */
9143 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009144 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009145 }
9146 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009147// TODO: track & disallow any attempts of user
9148// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009149 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009150 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009151 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009152 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009153
Mike Frysinger38478a62009-05-20 04:48:06 -04009154 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009155 /* If we were run as 'hush &', sleep until we are
9156 * in the foreground (tty pgrp == our pgrp).
9157 * If we get started under a job aware app (like bash),
9158 * make sure we are now in charge so we don't fight over
9159 * who gets the foreground */
9160 while (1) {
9161 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009162 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9163 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009164 break;
9165 /* send TTIN to ourself (should stop us) */
9166 kill(- shell_pgrp, SIGTTIN);
9167 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009168 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009169
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009170 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009171 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009172
Mike Frysinger38478a62009-05-20 04:48:06 -04009173 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009174 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009175 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009176 /* Put ourselves in our own process group
9177 * (bash, too, does this only if ctty is available) */
9178 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9179 /* Grab control of the terminal */
9180 tcsetpgrp(G_interactive_fd, getpid());
9181 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009182 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009183
9184# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9185 {
9186 const char *hp = get_local_var_value("HISTFILE");
9187 if (!hp) {
9188 hp = get_local_var_value("HOME");
9189 if (hp)
9190 hp = concat_path_file(hp, ".hush_history");
9191 } else {
9192 hp = xstrdup(hp);
9193 }
9194 if (hp) {
9195 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009196 //set_local_var(xasprintf("HISTFILE=%s", ...));
9197 }
9198# if ENABLE_FEATURE_SH_HISTFILESIZE
9199 hp = get_local_var_value("HISTFILESIZE");
9200 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9201# endif
9202 }
9203# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009204 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009205 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009206 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009207#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009208 /* No job control compiled in, only prompt/line editing */
9209 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02009210 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009211 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009212 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009213 G_interactive_fd = dup(STDIN_FILENO);
9214 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009215 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009216 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009217 }
9218 }
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 Vlasenkof9375282009-04-05 19:13:39 +00009221 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009222 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009223#else
9224 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009225 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009226#endif
9227 /* bash:
9228 * if interactive but not a login shell, sources ~/.bashrc
9229 * (--norc turns this off, --rcfile <file> overrides)
9230 */
9231
9232 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009233 /* note: ash and hush share this string */
9234 printf("\n\n%s %s\n"
9235 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9236 "\n",
9237 bb_banner,
9238 "hush - the humble shell"
9239 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009240 }
9241
Denis Vlasenkof9375282009-04-05 19:13:39 +00009242 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009243
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009244 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009245 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009246}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009247
9248
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009249/*
9250 * Built-ins
9251 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009252static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009253{
9254 return 0;
9255}
9256
Denys Vlasenko265062d2017-01-10 15:13:30 +01009257#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009258static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009259{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009260 int argc = string_array_len(argv);
9261 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009262}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009263#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009264#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009265static int FAST_FUNC builtin_test(char **argv)
9266{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009267 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009268}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009269#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009270#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009271static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009272{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009273 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009274}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009275#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009276#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009277static int FAST_FUNC builtin_printf(char **argv)
9278{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009279 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009280}
9281#endif
9282
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009283#if ENABLE_HUSH_HELP
9284static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9285{
9286 const struct built_in_command *x;
9287
9288 printf(
9289 "Built-in commands:\n"
9290 "------------------\n");
9291 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9292 if (x->b_descr)
9293 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9294 }
9295 return EXIT_SUCCESS;
9296}
9297#endif
9298
9299#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9300static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9301{
9302 show_history(G.line_input_state);
9303 return EXIT_SUCCESS;
9304}
9305#endif
9306
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009307static char **skip_dash_dash(char **argv)
9308{
9309 argv++;
9310 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9311 argv++;
9312 return argv;
9313}
9314
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009315static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009316{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009317 const char *newdir;
9318
9319 argv = skip_dash_dash(argv);
9320 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009321 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009322 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009323 * bash says "bash: cd: HOME not set" and does nothing
9324 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009325 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009326 const char *home = get_local_var_value("HOME");
9327 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009328 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009329 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009330 /* Mimic bash message exactly */
9331 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009332 return EXIT_FAILURE;
9333 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009334 /* Read current dir (get_cwd(1) is inside) and set PWD.
9335 * Note: do not enforce exporting. If PWD was unset or unexported,
9336 * set it again, but do not export. bash does the same.
9337 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009338 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009339 return EXIT_SUCCESS;
9340}
9341
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009342static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9343{
9344 puts(get_cwd(0));
9345 return EXIT_SUCCESS;
9346}
9347
9348static int FAST_FUNC builtin_eval(char **argv)
9349{
9350 int rcode = EXIT_SUCCESS;
9351
9352 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009353 if (argv[0]) {
9354 char *str = NULL;
9355
9356 if (argv[1]) {
9357 /* "The eval utility shall construct a command by
9358 * concatenating arguments together, separating
9359 * each with a <space> character."
9360 */
9361 char *p;
9362 unsigned len = 0;
9363 char **pp = argv;
9364 do
9365 len += strlen(*pp) + 1;
9366 while (*++pp);
9367 str = p = xmalloc(len);
9368 pp = argv;
9369 do {
9370 p = stpcpy(p, *pp);
9371 *p++ = ' ';
9372 } while (*++pp);
9373 p[-1] = '\0';
9374 }
9375
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009376 /* bash:
9377 * eval "echo Hi; done" ("done" is syntax error):
9378 * "echo Hi" will not execute too.
9379 */
Denys Vlasenko1f191122018-01-11 13:17:30 +01009380 parse_and_run_string(str ? str : argv[0]);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009381 free(str);
9382 rcode = G.last_exitcode;
9383 }
9384 return rcode;
9385}
9386
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009387static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009388{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009389 argv = skip_dash_dash(argv);
9390 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009391 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009392
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009393 /* Careful: we can end up here after [v]fork. Do not restore
9394 * tty pgrp then, only top-level shell process does that */
9395 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9396 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9397
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009398 /* Saved-redirect fds, script fds and G_interactive_fd are still
9399 * open here. However, they are all CLOEXEC, and execv below
9400 * closes them. Try interactive "exec ls -l /proc/self/fd",
9401 * it should show no extra open fds in the "ls" process.
9402 * If we'd try to run builtins/NOEXECs, this would need improving.
9403 */
9404 //close_saved_fds_and_FILE_fds();
9405
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009406 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009407 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009408 * and tcsetpgrp, and this is inherently racy.
9409 */
9410 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009411}
9412
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009413static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009414{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009415 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009416
9417 /* interactive bash:
9418 * # trap "echo EEE" EXIT
9419 * # exit
9420 * exit
9421 * There are stopped jobs.
9422 * (if there are _stopped_ jobs, running ones don't count)
9423 * # exit
9424 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009425 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009426 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009427 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009428 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009429
9430 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009431 argv = skip_dash_dash(argv);
9432 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009433 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009434 /* mimic bash: exit 123abc == exit 255 + error msg */
9435 xfunc_error_retval = 255;
9436 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009437 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009438}
9439
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009440#if ENABLE_HUSH_TYPE
9441/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9442static int FAST_FUNC builtin_type(char **argv)
9443{
9444 int ret = EXIT_SUCCESS;
9445
9446 while (*++argv) {
9447 const char *type;
9448 char *path = NULL;
9449
9450 if (0) {} /* make conditional compile easier below */
9451 /*else if (find_alias(*argv))
9452 type = "an alias";*/
9453#if ENABLE_HUSH_FUNCTIONS
9454 else if (find_function(*argv))
9455 type = "a function";
9456#endif
9457 else if (find_builtin(*argv))
9458 type = "a shell builtin";
9459 else if ((path = find_in_path(*argv)) != NULL)
9460 type = path;
9461 else {
9462 bb_error_msg("type: %s: not found", *argv);
9463 ret = EXIT_FAILURE;
9464 continue;
9465 }
9466
9467 printf("%s is %s\n", *argv, type);
9468 free(path);
9469 }
9470
9471 return ret;
9472}
9473#endif
9474
9475#if ENABLE_HUSH_READ
9476/* Interruptibility of read builtin in bash
9477 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9478 *
9479 * Empty trap makes read ignore corresponding signal, for any signal.
9480 *
9481 * SIGINT:
9482 * - terminates non-interactive shell;
9483 * - interrupts read in interactive shell;
9484 * if it has non-empty trap:
9485 * - executes trap and returns to command prompt in interactive shell;
9486 * - executes trap and returns to read in non-interactive shell;
9487 * SIGTERM:
9488 * - is ignored (does not interrupt) read in interactive shell;
9489 * - terminates non-interactive shell;
9490 * if it has non-empty trap:
9491 * - executes trap and returns to read;
9492 * SIGHUP:
9493 * - terminates shell (regardless of interactivity);
9494 * if it has non-empty trap:
9495 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009496 * SIGCHLD from children:
9497 * - does not interrupt read regardless of interactivity:
9498 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009499 */
9500static int FAST_FUNC builtin_read(char **argv)
9501{
9502 const char *r;
9503 char *opt_n = NULL;
9504 char *opt_p = NULL;
9505 char *opt_t = NULL;
9506 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009507 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009508 const char *ifs;
9509 int read_flags;
9510
9511 /* "!": do not abort on errors.
9512 * Option string must start with "sr" to match BUILTIN_READ_xxx
9513 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009514 read_flags = getopt32(argv,
9515#if BASH_READ_D
9516 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9517#else
9518 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9519#endif
9520 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009521 if (read_flags == (uint32_t)-1)
9522 return EXIT_FAILURE;
9523 argv += optind;
9524 ifs = get_local_var_value("IFS"); /* can be NULL */
9525
9526 again:
9527 r = shell_builtin_read(set_local_var_from_halves,
9528 argv,
9529 ifs,
9530 read_flags,
9531 opt_n,
9532 opt_p,
9533 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009534 opt_u,
9535 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009536 );
9537
9538 if ((uintptr_t)r == 1 && errno == EINTR) {
9539 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009540 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009541 goto again;
9542 }
9543
9544 if ((uintptr_t)r > 1) {
9545 bb_error_msg("%s", r);
9546 r = (char*)(uintptr_t)1;
9547 }
9548
9549 return (uintptr_t)r;
9550}
9551#endif
9552
9553#if ENABLE_HUSH_UMASK
9554static int FAST_FUNC builtin_umask(char **argv)
9555{
9556 int rc;
9557 mode_t mask;
9558
9559 rc = 1;
9560 mask = umask(0);
9561 argv = skip_dash_dash(argv);
9562 if (argv[0]) {
9563 mode_t old_mask = mask;
9564
9565 /* numeric umasks are taken as-is */
9566 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9567 if (!isdigit(argv[0][0]))
9568 mask ^= 0777;
9569 mask = bb_parse_mode(argv[0], mask);
9570 if (!isdigit(argv[0][0]))
9571 mask ^= 0777;
9572 if ((unsigned)mask > 0777) {
9573 mask = old_mask;
9574 /* bash messages:
9575 * bash: umask: 'q': invalid symbolic mode operator
9576 * bash: umask: 999: octal number out of range
9577 */
9578 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9579 rc = 0;
9580 }
9581 } else {
9582 /* Mimic bash */
9583 printf("%04o\n", (unsigned) mask);
9584 /* fall through and restore mask which we set to 0 */
9585 }
9586 umask(mask);
9587
9588 return !rc; /* rc != 0 - success */
9589}
9590#endif
9591
Denys Vlasenko41ade052017-01-08 18:56:24 +01009592#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009593static void print_escaped(const char *s)
9594{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009595 if (*s == '\'')
9596 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009597 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009598 const char *p = strchrnul(s, '\'');
9599 /* print 'xxxx', possibly just '' */
9600 printf("'%.*s'", (int)(p - s), s);
9601 if (*p == '\0')
9602 break;
9603 s = p;
9604 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009605 /* s points to '; print "'''...'''" */
9606 putchar('"');
9607 do putchar('\''); while (*++s == '\'');
9608 putchar('"');
9609 } while (*s);
9610}
Denys Vlasenko41ade052017-01-08 18:56:24 +01009611#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009612
Denys Vlasenko1e660422017-07-17 21:10:50 +02009613#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009614static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009615{
9616 do {
9617 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009618 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02009619
9620 /* So far we do not check that name is valid (TODO?) */
9621
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009622 if (*name_end == '\0') {
9623 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009624
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009625 vpp = get_ptr_to_local_var(name, name_end - name);
9626 var = vpp ? *vpp : NULL;
9627
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009628 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009629 /* export -n NAME (without =VALUE) */
9630 if (var) {
9631 var->flg_export = 0;
9632 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9633 unsetenv(name);
9634 } /* else: export -n NOT_EXISTING_VAR: no-op */
9635 continue;
9636 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009637 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009638 /* export NAME (without =VALUE) */
9639 if (var) {
9640 var->flg_export = 1;
9641 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9642 putenv(var->varstr);
9643 continue;
9644 }
9645 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009646 if (flags & SETFLAG_MAKE_RO) {
9647 /* readonly NAME (without =VALUE) */
9648 if (var) {
9649 var->flg_read_only = 1;
9650 continue;
9651 }
9652 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009653# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009654 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009655 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9656 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009657 if (var && var->func_nest_level == lvl) {
9658 /* "local x=abc; ...; local x" - ignore second local decl */
9659 continue;
9660 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02009661 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009662# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009663 /* Exporting non-existing variable.
9664 * bash does not put it in environment,
9665 * but remembers that it is exported,
9666 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +02009667 * We just set it to "" and export.
9668 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009669 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +02009670 * bash sets the value to "".
9671 */
9672 /* Or, it's "readonly NAME" (without =VALUE).
9673 * bash remembers NAME and disallows its creation
9674 * in the future.
9675 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009676 name = xasprintf("%s=", name);
9677 } else {
9678 /* (Un)exporting/making local NAME=VALUE */
9679 name = xstrdup(name);
9680 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009681 if (set_local_var(name, flags))
9682 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009683 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +02009684 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009685}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009686#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009687
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009688#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009689static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009690{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00009691 unsigned opt_unexport;
9692
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02009693#if ENABLE_HUSH_EXPORT_N
9694 /* "!": do not abort on errors */
9695 opt_unexport = getopt32(argv, "!n");
9696 if (opt_unexport == (uint32_t)-1)
9697 return EXIT_FAILURE;
9698 argv += optind;
9699#else
9700 opt_unexport = 0;
9701 argv++;
9702#endif
9703
9704 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009705 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009706 if (e) {
9707 while (*e) {
9708#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009709 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009710#else
9711 /* ash emits: export VAR='VAL'
9712 * bash: declare -x VAR="VAL"
9713 * we follow ash example */
9714 const char *s = *e++;
9715 const char *p = strchr(s, '=');
9716
9717 if (!p) /* wtf? take next variable */
9718 continue;
9719 /* export var= */
9720 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009721 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009722 putchar('\n');
9723#endif
9724 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009725 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009726 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009727 return EXIT_SUCCESS;
9728 }
9729
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009730 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009731}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009732#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009733
Denys Vlasenko295fef82009-06-03 12:47:26 +02009734#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009735static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009736{
9737 if (G.func_nest_level == 0) {
9738 bb_error_msg("%s: not in a function", argv[0]);
9739 return EXIT_FAILURE; /* bash compat */
9740 }
Denys Vlasenko1e660422017-07-17 21:10:50 +02009741 argv++;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009742 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +02009743}
9744#endif
9745
Denys Vlasenko1e660422017-07-17 21:10:50 +02009746#if ENABLE_HUSH_READONLY
9747static int FAST_FUNC builtin_readonly(char **argv)
9748{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009749 argv++;
9750 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +02009751 /* bash: readonly [-p]: list all readonly VARs
9752 * (-p has no effect in bash)
9753 */
9754 struct variable *e;
9755 for (e = G.top_var; e; e = e->next) {
9756 if (e->flg_read_only) {
9757//TODO: quote value: readonly VAR='VAL'
9758 printf("readonly %s\n", e->varstr);
9759 }
9760 }
9761 return EXIT_SUCCESS;
9762 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009763 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +02009764}
9765#endif
9766
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009767#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009768/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9769static int FAST_FUNC builtin_unset(char **argv)
9770{
9771 int ret;
9772 unsigned opts;
9773
9774 /* "!": do not abort on errors */
9775 /* "+": stop at 1st non-option */
9776 opts = getopt32(argv, "!+vf");
9777 if (opts == (unsigned)-1)
9778 return EXIT_FAILURE;
9779 if (opts == 3) {
9780 bb_error_msg("unset: -v and -f are exclusive");
9781 return EXIT_FAILURE;
9782 }
9783 argv += optind;
9784
9785 ret = EXIT_SUCCESS;
9786 while (*argv) {
9787 if (!(opts & 2)) { /* not -f */
9788 if (unset_local_var(*argv)) {
9789 /* unset <nonexistent_var> doesn't fail.
9790 * Error is when one tries to unset RO var.
9791 * Message was printed by unset_local_var. */
9792 ret = EXIT_FAILURE;
9793 }
9794 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009795# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +02009796 else {
9797 unset_func(*argv);
9798 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009799# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009800 argv++;
9801 }
9802 return ret;
9803}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009804#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009805
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009806#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009807/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9808 * built-in 'set' handler
9809 * SUSv3 says:
9810 * set [-abCefhmnuvx] [-o option] [argument...]
9811 * set [+abCefhmnuvx] [+o option] [argument...]
9812 * set -- [argument...]
9813 * set -o
9814 * set +o
9815 * Implementations shall support the options in both their hyphen and
9816 * plus-sign forms. These options can also be specified as options to sh.
9817 * Examples:
9818 * Write out all variables and their values: set
9819 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9820 * Turn on the -x and -v options: set -xv
9821 * Unset all positional parameters: set --
9822 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9823 * Set the positional parameters to the expansion of x, even if x expands
9824 * with a leading '-' or '+': set -- $x
9825 *
9826 * So far, we only support "set -- [argument...]" and some of the short names.
9827 */
9828static int FAST_FUNC builtin_set(char **argv)
9829{
9830 int n;
9831 char **pp, **g_argv;
9832 char *arg = *++argv;
9833
9834 if (arg == NULL) {
9835 struct variable *e;
9836 for (e = G.top_var; e; e = e->next)
9837 puts(e->varstr);
9838 return EXIT_SUCCESS;
9839 }
9840
9841 do {
9842 if (strcmp(arg, "--") == 0) {
9843 ++argv;
9844 goto set_argv;
9845 }
9846 if (arg[0] != '+' && arg[0] != '-')
9847 break;
9848 for (n = 1; arg[n]; ++n) {
9849 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9850 goto error;
9851 if (arg[n] == 'o' && argv[1])
9852 argv++;
9853 }
9854 } while ((arg = *++argv) != NULL);
9855 /* Now argv[0] is 1st argument */
9856
9857 if (arg == NULL)
9858 return EXIT_SUCCESS;
9859 set_argv:
9860
9861 /* NB: G.global_argv[0] ($0) is never freed/changed */
9862 g_argv = G.global_argv;
9863 if (G.global_args_malloced) {
9864 pp = g_argv;
9865 while (*++pp)
9866 free(*pp);
9867 g_argv[1] = NULL;
9868 } else {
9869 G.global_args_malloced = 1;
9870 pp = xzalloc(sizeof(pp[0]) * 2);
9871 pp[0] = g_argv[0]; /* retain $0 */
9872 g_argv = pp;
9873 }
9874 /* This realloc's G.global_argv */
9875 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9876
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009877 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +02009878
9879 return EXIT_SUCCESS;
9880
9881 /* Nothing known, so abort */
9882 error:
9883 bb_error_msg("set: %s: invalid option", arg);
9884 return EXIT_FAILURE;
9885}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009886#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009887
9888static int FAST_FUNC builtin_shift(char **argv)
9889{
9890 int n = 1;
9891 argv = skip_dash_dash(argv);
9892 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +02009893 n = bb_strtou(argv[0], NULL, 10);
9894 if (errno || n < 0) {
9895 /* shared string with ash.c */
9896 bb_error_msg("Illegal number: %s", argv[0]);
9897 /*
9898 * ash aborts in this case.
9899 * bash prints error message and set $? to 1.
9900 * Interestingly, for "shift 99999" bash does not
9901 * print error message, but does set $? to 1
9902 * (and does no shifting at all).
9903 */
9904 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02009905 }
9906 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01009907 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +02009908 int m = 1;
9909 while (m <= n)
9910 free(G.global_argv[m++]);
9911 }
9912 G.global_argc -= n;
9913 memmove(&G.global_argv[1], &G.global_argv[n+1],
9914 G.global_argc * sizeof(G.global_argv[0]));
9915 return EXIT_SUCCESS;
9916 }
9917 return EXIT_FAILURE;
9918}
9919
Denys Vlasenko74d40582017-08-11 01:32:46 +02009920#if ENABLE_HUSH_GETOPTS
9921static int FAST_FUNC builtin_getopts(char **argv)
9922{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +02009923/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
9924
Denys Vlasenko74d40582017-08-11 01:32:46 +02009925TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +02009926If a required argument is not found, and getopts is not silent,
9927a question mark (?) is placed in VAR, OPTARG is unset, and a
9928diagnostic message is printed. If getopts is silent, then a
9929colon (:) is placed in VAR and OPTARG is set to the option
9930character found.
9931
9932Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +02009933
9934"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +02009935*/
9936 char cbuf[2];
9937 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +02009938 int c, n, exitcode, my_opterr;
9939 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +02009940
9941 optstring = *++argv;
9942 if (!optstring || !(var = *++argv)) {
9943 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
9944 return EXIT_FAILURE;
9945 }
9946
Denys Vlasenko238ff982017-08-29 13:38:30 +02009947 if (argv[1])
9948 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
9949 else
9950 argv = G.global_argv;
9951 cbuf[1] = '\0';
9952
9953 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +02009954 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +02009955 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +02009956 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +02009957 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +02009958 }
Denys Vlasenko74d40582017-08-11 01:32:46 +02009959
9960 /* getopts stops on first non-option. Add "+" to force that */
9961 /*if (optstring[0] != '+')*/ {
9962 char *s = alloca(strlen(optstring) + 2);
9963 sprintf(s, "+%s", optstring);
9964 optstring = s;
9965 }
9966
Denys Vlasenko238ff982017-08-29 13:38:30 +02009967 /* Naively, now we should just
9968 * cp = get_local_var_value("OPTIND");
9969 * optind = cp ? atoi(cp) : 0;
9970 * optarg = NULL;
9971 * opterr = my_opterr;
9972 * c = getopt(string_array_len(argv), argv, optstring);
9973 * and be done? Not so fast...
9974 * Unlike normal getopt() usage in C programs, here
9975 * each successive call will (usually) have the same argv[] CONTENTS,
9976 * but not the ADDRESSES. Worse yet, it's possible that between
9977 * invocations of "getopts", there will be calls to shell builtins
9978 * which use getopt() internally. Example:
9979 * while getopts "abc" RES -a -bc -abc de; do
9980 * unset -ff func
9981 * done
9982 * This would not work correctly: getopt() call inside "unset"
9983 * modifies internal libc state which is tracking position in
9984 * multi-option strings ("-abc"). At best, it can skip options
9985 * or return the same option infinitely. With glibc implementation
9986 * of getopt(), it would use outright invalid pointers and return
9987 * garbage even _without_ "unset" mangling internal state.
9988 *
9989 * We resort to resetting getopt() state and calling it N times,
9990 * until we get Nth result (or failure).
9991 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
9992 */
Denys Vlasenko60161812017-08-29 14:32:17 +02009993 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +02009994 count = 0;
9995 n = string_array_len(argv);
9996 do {
9997 optarg = NULL;
9998 opterr = (count < G.getopt_count) ? 0 : my_opterr;
9999 c = getopt(n, argv, optstring);
10000 if (c < 0)
10001 break;
10002 count++;
10003 } while (count <= G.getopt_count);
10004
10005 /* Set OPTIND. Prevent resetting of the magic counter! */
10006 set_local_var_from_halves("OPTIND", utoa(optind));
10007 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010008 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010009
10010 /* Set OPTARG */
10011 /* Always set or unset, never left as-is, even on exit/error:
10012 * "If no option was found, or if the option that was found
10013 * does not have an option-argument, OPTARG shall be unset."
10014 */
10015 cp = optarg;
10016 if (c == '?') {
10017 /* If ":optstring" and unknown option is seen,
10018 * it is stored to OPTARG.
10019 */
10020 if (optstring[1] == ':') {
10021 cbuf[0] = optopt;
10022 cp = cbuf;
10023 }
10024 }
10025 if (cp)
10026 set_local_var_from_halves("OPTARG", cp);
10027 else
10028 unset_local_var("OPTARG");
10029
10030 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010031 exitcode = EXIT_SUCCESS;
10032 if (c < 0) { /* -1: end of options */
10033 exitcode = EXIT_FAILURE;
10034 c = '?';
10035 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010036
Denys Vlasenko238ff982017-08-29 13:38:30 +020010037 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010038 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010039 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010040
Denys Vlasenko74d40582017-08-11 01:32:46 +020010041 return exitcode;
10042}
10043#endif
10044
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010045static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010046{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010047 char *arg_path, *filename;
10048 FILE *input;
10049 save_arg_t sv;
10050 char *args_need_save;
10051#if ENABLE_HUSH_FUNCTIONS
10052 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010053#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010054
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010055 argv = skip_dash_dash(argv);
10056 filename = argv[0];
10057 if (!filename) {
10058 /* bash says: "bash: .: filename argument required" */
10059 return 2; /* bash compat */
10060 }
10061 arg_path = NULL;
10062 if (!strchr(filename, '/')) {
10063 arg_path = find_in_path(filename);
10064 if (arg_path)
10065 filename = arg_path;
10066 }
10067 input = remember_FILE(fopen_or_warn(filename, "r"));
10068 free(arg_path);
10069 if (!input) {
10070 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10071 /* POSIX: non-interactive shell should abort here,
10072 * not merely fail. So far no one complained :)
10073 */
10074 return EXIT_FAILURE;
10075 }
10076
10077#if ENABLE_HUSH_FUNCTIONS
10078 sv_flg = G_flag_return_in_progress;
10079 /* "we are inside sourced file, ok to use return" */
10080 G_flag_return_in_progress = -1;
10081#endif
10082 args_need_save = argv[1]; /* used as a boolean variable */
10083 if (args_need_save)
10084 save_and_replace_G_args(&sv, argv);
10085
10086 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10087 G.last_exitcode = 0;
10088 parse_and_run_file(input);
10089 fclose_and_forget(input);
10090
10091 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10092 restore_G_args(&sv, argv);
10093#if ENABLE_HUSH_FUNCTIONS
10094 G_flag_return_in_progress = sv_flg;
10095#endif
10096
10097 return G.last_exitcode;
10098}
10099
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010100#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010101static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010102{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010103 int sig;
10104 char *new_cmd;
10105
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010106 if (!G_traps)
10107 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010108
10109 argv++;
10110 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010111 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010112 /* No args: print all trapped */
10113 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010114 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010115 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010116 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010117 /* note: bash adds "SIG", but only if invoked
10118 * as "bash". If called as "sh", or if set -o posix,
10119 * then it prints short signal names.
10120 * We are printing short names: */
10121 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010122 }
10123 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010124 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010125 return EXIT_SUCCESS;
10126 }
10127
10128 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010129 /* If first arg is a number: reset all specified signals */
10130 sig = bb_strtou(*argv, NULL, 10);
10131 if (errno == 0) {
10132 int ret;
10133 process_sig_list:
10134 ret = EXIT_SUCCESS;
10135 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010136 sighandler_t handler;
10137
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010138 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010139 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010140 ret = EXIT_FAILURE;
10141 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010142 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010143 continue;
10144 }
10145
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010146 free(G_traps[sig]);
10147 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010148
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010149 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010150 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010151
10152 /* There is no signal for 0 (EXIT) */
10153 if (sig == 0)
10154 continue;
10155
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010156 if (new_cmd)
10157 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10158 else
10159 /* We are removing trap handler */
10160 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010161 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010162 }
10163 return ret;
10164 }
10165
10166 if (!argv[1]) { /* no second arg */
10167 bb_error_msg("trap: invalid arguments");
10168 return EXIT_FAILURE;
10169 }
10170
10171 /* First arg is "-": reset all specified to default */
10172 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10173 /* Everything else: set arg as signal handler
10174 * (includes "" case, which ignores signal) */
10175 if (argv[0][0] == '-') {
10176 if (argv[0][1] == '\0') { /* "-" */
10177 /* new_cmd remains NULL: "reset these sigs" */
10178 goto reset_traps;
10179 }
10180 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10181 argv++;
10182 }
10183 /* else: "-something", no special meaning */
10184 }
10185 new_cmd = *argv;
10186 reset_traps:
10187 argv++;
10188 goto process_sig_list;
10189}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010190#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010191
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010192#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010193static struct pipe *parse_jobspec(const char *str)
10194{
10195 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010196 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010197
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010198 if (sscanf(str, "%%%u", &jobnum) != 1) {
10199 if (str[0] != '%'
10200 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10201 ) {
10202 bb_error_msg("bad argument '%s'", str);
10203 return NULL;
10204 }
10205 /* It is "%%", "%+" or "%" - current job */
10206 jobnum = G.last_jobid;
10207 if (jobnum == 0) {
10208 bb_error_msg("no current job");
10209 return NULL;
10210 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010211 }
10212 for (pi = G.job_list; pi; pi = pi->next) {
10213 if (pi->jobid == jobnum) {
10214 return pi;
10215 }
10216 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010217 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010218 return NULL;
10219}
10220
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010221static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10222{
10223 struct pipe *job;
10224 const char *status_string;
10225
10226 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10227 for (job = G.job_list; job; job = job->next) {
10228 if (job->alive_cmds == job->stopped_cmds)
10229 status_string = "Stopped";
10230 else
10231 status_string = "Running";
10232
10233 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10234 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010235
10236 clean_up_last_dead_job();
10237
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010238 return EXIT_SUCCESS;
10239}
10240
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010241/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010242static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010243{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010244 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010245 struct pipe *pi;
10246
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010247 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010248 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010249
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010250 /* If they gave us no args, assume they want the last backgrounded task */
10251 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010252 for (pi = G.job_list; pi; pi = pi->next) {
10253 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010254 goto found;
10255 }
10256 }
10257 bb_error_msg("%s: no current job", argv[0]);
10258 return EXIT_FAILURE;
10259 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010260
10261 pi = parse_jobspec(argv[1]);
10262 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010263 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010264 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010265 /* TODO: bash prints a string representation
10266 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010267 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010268 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010269 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010270 }
10271
10272 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010273 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10274 for (i = 0; i < pi->num_cmds; i++) {
10275 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010276 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010277 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010278
10279 i = kill(- pi->pgrp, SIGCONT);
10280 if (i < 0) {
10281 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010282 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010283 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010284 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010285 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010286 }
10287
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010288 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010289 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010290 return checkjobs_and_fg_shell(pi);
10291 }
10292 return EXIT_SUCCESS;
10293}
10294#endif
10295
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010296#if ENABLE_HUSH_KILL
10297static int FAST_FUNC builtin_kill(char **argv)
10298{
10299 int ret = 0;
10300
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010301# if ENABLE_HUSH_JOB
10302 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10303 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010304
10305 do {
10306 struct pipe *pi;
10307 char *dst;
10308 int j, n;
10309
10310 if (argv[i][0] != '%')
10311 continue;
10312 /*
10313 * "kill %N" - job kill
10314 * Converting to pgrp / pid kill
10315 */
10316 pi = parse_jobspec(argv[i]);
10317 if (!pi) {
10318 /* Eat bad jobspec */
10319 j = i;
10320 do {
10321 j++;
10322 argv[j - 1] = argv[j];
10323 } while (argv[j]);
10324 ret = 1;
10325 i--;
10326 continue;
10327 }
10328 /*
10329 * In jobs started under job control, we signal
10330 * entire process group by kill -PGRP_ID.
10331 * This happens, f.e., in interactive shell.
10332 *
10333 * Otherwise, we signal each child via
10334 * kill PID1 PID2 PID3.
10335 * Testcases:
10336 * sh -c 'sleep 1|sleep 1 & kill %1'
10337 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10338 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10339 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010340 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010341 dst = alloca(n * sizeof(int)*4);
10342 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010343 if (G_interactive_fd)
10344 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010345 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010346 struct command *cmd = &pi->cmds[j];
10347 /* Skip exited members of the job */
10348 if (cmd->pid == 0)
10349 continue;
10350 /*
10351 * kill_main has matching code to expect
10352 * leading space. Needed to not confuse
10353 * negative pids with "kill -SIGNAL_NO" syntax
10354 */
10355 dst += sprintf(dst, " %u", (int)cmd->pid);
10356 }
10357 *dst = '\0';
10358 } while (argv[++i]);
10359 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010360# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010361
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010362 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010363 ret = run_applet_main(argv, kill_main);
10364 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010365 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010366 return ret;
10367}
10368#endif
10369
10370#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010371/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010372#if !ENABLE_HUSH_JOB
10373# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10374#endif
10375static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010376{
10377 int ret = 0;
10378 for (;;) {
10379 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010380 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010381
Denys Vlasenko830ea352016-11-08 04:59:11 +010010382 if (!sigisemptyset(&G.pending_set))
10383 goto check_sig;
10384
Denys Vlasenko7e675362016-10-28 21:57:31 +020010385 /* waitpid is not interruptible by SA_RESTARTed
10386 * signals which we use. Thus, this ugly dance:
10387 */
10388
10389 /* Make sure possible SIGCHLD is stored in kernel's
10390 * pending signal mask before we call waitpid.
10391 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010392 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010393 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010394 sigfillset(&oldset); /* block all signals, remember old set */
10395 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010396
10397 if (!sigisemptyset(&G.pending_set)) {
10398 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010399 goto restore;
10400 }
10401
10402 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010403/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010404 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010405 debug_printf_exec("checkjobs:%d\n", ret);
10406#if ENABLE_HUSH_JOB
10407 if (waitfor_pipe) {
10408 int rcode = job_exited_or_stopped(waitfor_pipe);
10409 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10410 if (rcode >= 0) {
10411 ret = rcode;
10412 sigprocmask(SIG_SETMASK, &oldset, NULL);
10413 break;
10414 }
10415 }
10416#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010417 /* if ECHILD, there are no children (ret is -1 or 0) */
10418 /* if ret == 0, no children changed state */
10419 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010420 if (errno == ECHILD || ret) {
10421 ret--;
10422 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010423 ret = 0;
10424 sigprocmask(SIG_SETMASK, &oldset, NULL);
10425 break;
10426 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010427 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010428 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10429 /* Note: sigsuspend invokes signal handler */
10430 sigsuspend(&oldset);
10431 restore:
10432 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010433 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010434 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010435 sig = check_and_run_traps();
10436 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010437 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010438 ret = 128 + sig;
10439 break;
10440 }
10441 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10442 }
10443 return ret;
10444}
10445
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010446static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010447{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010448 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010449 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010450
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010451 argv = skip_dash_dash(argv);
10452 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010453 /* Don't care about wait results */
10454 /* Note 1: must wait until there are no more children */
10455 /* Note 2: must be interruptible */
10456 /* Examples:
10457 * $ sleep 3 & sleep 6 & wait
10458 * [1] 30934 sleep 3
10459 * [2] 30935 sleep 6
10460 * [1] Done sleep 3
10461 * [2] Done sleep 6
10462 * $ sleep 3 & sleep 6 & wait
10463 * [1] 30936 sleep 3
10464 * [2] 30937 sleep 6
10465 * [1] Done sleep 3
10466 * ^C <-- after ~4 sec from keyboard
10467 * $
10468 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010469 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010470 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010471
Denys Vlasenko7e675362016-10-28 21:57:31 +020010472 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010473 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010474 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010475#if ENABLE_HUSH_JOB
10476 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010477 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010478 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010479 wait_pipe = parse_jobspec(*argv);
10480 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010481 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010482 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010483 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010484 } else {
10485 /* waiting on "last dead job" removes it */
10486 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010487 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010488 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010489 /* else: parse_jobspec() already emitted error msg */
10490 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010491 }
10492#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010493 /* mimic bash message */
10494 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010495 ret = EXIT_FAILURE;
10496 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010497 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010498
Denys Vlasenko7e675362016-10-28 21:57:31 +020010499 /* Do we have such child? */
10500 ret = waitpid(pid, &status, WNOHANG);
10501 if (ret < 0) {
10502 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010503 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010504 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010505 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010506 /* "wait $!" but last bg task has already exited. Try:
10507 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10508 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010509 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010510 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010511 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010512 } else {
10513 /* Example: "wait 1". mimic bash message */
10514 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010515 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010516 } else {
10517 /* ??? */
10518 bb_perror_msg("wait %s", *argv);
10519 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010520 continue; /* bash checks all argv[] */
10521 }
10522 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010523 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010524 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010525 } else {
10526 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010527 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010528 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010529 if (WIFSIGNALED(status))
10530 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010531 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010532 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010533
10534 return ret;
10535}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010536#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010537
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010538#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10539static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10540{
10541 if (argv[1]) {
10542 def = bb_strtou(argv[1], NULL, 10);
10543 if (errno || def < def_min || argv[2]) {
10544 bb_error_msg("%s: bad arguments", argv[0]);
10545 def = UINT_MAX;
10546 }
10547 }
10548 return def;
10549}
10550#endif
10551
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010552#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010553static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010554{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010555 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010556 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010557 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010558 /* if we came from builtin_continue(), need to undo "= 1" */
10559 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010560 return EXIT_SUCCESS; /* bash compat */
10561 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010562 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010563
10564 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10565 if (depth == UINT_MAX)
10566 G.flag_break_continue = BC_BREAK;
10567 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010568 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010569
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010570 return EXIT_SUCCESS;
10571}
10572
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010573static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010574{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010575 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10576 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010577}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010578#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010579
10580#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010581static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010582{
10583 int rc;
10584
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010585 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010586 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10587 return EXIT_FAILURE; /* bash compat */
10588 }
10589
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010590 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010591
10592 /* bash:
10593 * out of range: wraps around at 256, does not error out
10594 * non-numeric param:
10595 * f() { false; return qwe; }; f; echo $?
10596 * bash: return: qwe: numeric argument required <== we do this
10597 * 255 <== we also do this
10598 */
10599 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10600 return rc;
10601}
10602#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010603
Denys Vlasenko11f2e992017-08-10 16:34:03 +020010604#if ENABLE_HUSH_TIMES
10605static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10606{
10607 static const uint8_t times_tbl[] ALIGN1 = {
10608 ' ', offsetof(struct tms, tms_utime),
10609 '\n', offsetof(struct tms, tms_stime),
10610 ' ', offsetof(struct tms, tms_cutime),
10611 '\n', offsetof(struct tms, tms_cstime),
10612 0
10613 };
10614 const uint8_t *p;
10615 unsigned clk_tck;
10616 struct tms buf;
10617
10618 clk_tck = bb_clk_tck();
10619
10620 times(&buf);
10621 p = times_tbl;
10622 do {
10623 unsigned sec, frac;
10624 unsigned long t;
10625 t = *(clock_t *)(((char *) &buf) + p[1]);
10626 sec = t / clk_tck;
10627 frac = t % clk_tck;
10628 printf("%um%u.%03us%c",
10629 sec / 60, sec % 60,
10630 (frac * 1000) / clk_tck,
10631 p[0]);
10632 p += 2;
10633 } while (*p);
10634
10635 return EXIT_SUCCESS;
10636}
10637#endif
10638
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010639#if ENABLE_HUSH_MEMLEAK
10640static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10641{
10642 void *p;
10643 unsigned long l;
10644
10645# ifdef M_TRIM_THRESHOLD
10646 /* Optional. Reduces probability of false positives */
10647 malloc_trim(0);
10648# endif
10649 /* Crude attempt to find where "free memory" starts,
10650 * sans fragmentation. */
10651 p = malloc(240);
10652 l = (unsigned long)p;
10653 free(p);
10654 p = malloc(3400);
10655 if (l < (unsigned long)p) l = (unsigned long)p;
10656 free(p);
10657
10658
10659# if 0 /* debug */
10660 {
10661 struct mallinfo mi = mallinfo();
10662 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10663 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10664 }
10665# endif
10666
10667 if (!G.memleak_value)
10668 G.memleak_value = l;
10669
10670 l -= G.memleak_value;
10671 if ((long)l < 0)
10672 l = 0;
10673 l /= 1024;
10674 if (l > 127)
10675 l = 127;
10676
10677 /* Exitcode is "how many kilobytes we leaked since 1st call" */
10678 return l;
10679}
10680#endif