blob: df1b046abc982ad597ca47144dc88a7b7b78f55e [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
465#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000466
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200467struct variable;
468
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000469static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
470
471/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000472 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000473 */
474#if !BB_MMU
475typedef struct nommu_save_t {
476 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200477 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000478 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000479 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000480} nommu_save_t;
481#endif
482
Denys Vlasenko9b782552010-09-08 13:33:26 +0200483enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000484 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000485#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000486 RES_IF ,
487 RES_THEN ,
488 RES_ELIF ,
489 RES_ELSE ,
490 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000491#endif
492#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000493 RES_FOR ,
494 RES_WHILE ,
495 RES_UNTIL ,
496 RES_DO ,
497 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000498#endif
499#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000500 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000501#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000502#if ENABLE_HUSH_CASE
503 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200504 /* three pseudo-keywords support contrived "case" syntax: */
505 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
506 RES_MATCH , /* "word)" */
507 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000508 RES_ESAC ,
509#endif
510 RES_XXXX ,
511 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200512};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000513
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000514typedef struct o_string {
515 char *data;
516 int length; /* position where data is appended */
517 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200518 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000519 /* At least some part of the string was inside '' or "",
520 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200521 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000522 smallint has_empty_slot;
523 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
524} o_string;
525enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200526 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
527 EXP_FLAG_GLOB = 0x2,
528 /* Protect newly added chars against globbing
529 * by prepending \ to *, ?, [, \ */
530 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
531};
532enum {
533 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000534 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200535 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200536 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200537 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000538};
539/* Used for initialization: o_string foo = NULL_O_STRING; */
540#define NULL_O_STRING { NULL }
541
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200542#ifndef debug_printf_parse
543static const char *const assignment_flag[] = {
544 "MAYBE_ASSIGNMENT",
545 "DEFINITELY_ASSIGNMENT",
546 "NOT_ASSIGNMENT",
547 "WORD_IS_KEYWORD",
548};
549#endif
550
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000551typedef struct in_str {
552 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000553#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000554 smallint promptmode; /* 0: PS1, 1: PS2 */
555#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200556 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200557 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000558 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000559} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000560
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200561/* The descrip member of this structure is only used to make
562 * debugging output pretty */
563static const struct {
564 int mode;
565 signed char default_fd;
566 char descrip[3];
567} redir_table[] = {
568 { O_RDONLY, 0, "<" },
569 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
570 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
571 { O_CREAT|O_RDWR, 1, "<>" },
572 { O_RDONLY, 0, "<<" },
573/* Should not be needed. Bogus default_fd helps in debugging */
574/* { O_RDONLY, 77, "<<" }, */
575};
576
Eric Andersen25f27032001-04-26 23:22:31 +0000577struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000578 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000579 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000580 int rd_fd; /* fd to redirect */
581 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
582 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000583 smallint rd_type; /* (enum redir_type) */
584 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000585 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200586 * bit 0: do we need to trim leading tabs?
587 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000588 */
Eric Andersen25f27032001-04-26 23:22:31 +0000589};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000590typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200591 REDIRECT_INPUT = 0,
592 REDIRECT_OVERWRITE = 1,
593 REDIRECT_APPEND = 2,
594 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000595 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200596 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000597
598 REDIRFD_CLOSE = -3,
599 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000600 REDIRFD_TO_FILE = -1,
601 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000602
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000603 HEREDOC_SKIPTABS = 1,
604 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000605} redir_type;
606
Eric Andersen25f27032001-04-26 23:22:31 +0000607
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000608struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000609 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000610 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200611 smallint cmd_type; /* CMD_xxx */
612#define CMD_NORMAL 0
613#define CMD_SUBSHELL 1
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100614#if BASH_TEST2
Denys Vlasenkod383b492010-09-06 10:22:13 +0200615/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200616# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000617#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200618#if ENABLE_HUSH_FUNCTIONS
619# define CMD_FUNCDEF 3
620#endif
621
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100622 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200623 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
624 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000625#if !BB_MMU
626 char *group_as_string;
627#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000628#if ENABLE_HUSH_FUNCTIONS
629 struct function *child_func;
630/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200631 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000632 * When we execute "f1() {a;}" cmd, we create new function and clear
633 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200634 * When we execute "f1() {b;}", we notice that f1 exists,
635 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000636 * we put those fields back into cmd->xxx
637 * (struct function has ->parent_cmd ptr to facilitate that).
638 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
639 * Without this trick, loop would execute a;b;b;b;...
640 * instead of correct sequence a;b;a;b;...
641 * When command is freed, it severs the link
642 * (sets ->child_func->parent_cmd to NULL).
643 */
644#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000645 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000646/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
647 * and on execution these are substituted with their values.
648 * Substitution can make _several_ words out of one argv[n]!
649 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000650 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000651 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000652 struct redir_struct *redirects; /* I/O redirections */
653};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000654/* Is there anything in this command at all? */
655#define IS_NULL_CMD(cmd) \
656 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
657
Eric Andersen25f27032001-04-26 23:22:31 +0000658struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000659 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000660 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000661 int alive_cmds; /* number of commands running (not exited) */
662 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000663#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100664 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000665 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000666 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000667#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000668 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000669 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000670 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
671 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000672};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000673typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100674 PIPE_SEQ = 0,
675 PIPE_AND = 1,
676 PIPE_OR = 2,
677 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000678} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000679/* Is there anything in this pipe at all? */
680#define IS_NULL_PIPE(pi) \
681 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000682
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000683/* This holds pointers to the various results of parsing */
684struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000685 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000686 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000687 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000688 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000689 /* last command in pipe (being constructed right now) */
690 struct command *command;
691 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000692 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000693#if !BB_MMU
694 o_string as_string;
695#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000696#if HAS_KEYWORDS
697 smallint ctx_res_w;
698 smallint ctx_inverted; /* "! cmd | cmd" */
699#if ENABLE_HUSH_CASE
700 smallint ctx_dsemicolon; /* ";;" seen */
701#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000702 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
703 int old_flag;
704 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000705 * example: "if pipe1; pipe2; then pipe3; fi"
706 * when we see "if" or "then", we malloc and copy current context,
707 * and make ->stack point to it. then we parse pipeN.
708 * when closing "then" / fi" / whatever is found,
709 * we move list_head into ->stack->command->group,
710 * copy ->stack into current context, and delete ->stack.
711 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000712 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000713 struct parse_context *stack;
714#endif
715};
716
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000717/* On program start, environ points to initial environment.
718 * putenv adds new pointers into it, unsetenv removes them.
719 * Neither of these (de)allocates the strings.
720 * setenv allocates new strings in malloc space and does putenv,
721 * and thus setenv is unusable (leaky) for shell's purposes */
722#define setenv(...) setenv_is_leaky_dont_use()
723struct variable {
724 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000725 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200726#if ENABLE_HUSH_LOCAL
727 unsigned func_nest_level;
728#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000729 int max_len; /* if > 0, name is part of initial env; else name is malloced */
730 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000731 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000732};
733
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000734enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000735 BC_BREAK = 1,
736 BC_CONTINUE = 2,
737};
738
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000739#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000740struct function {
741 struct function *next;
742 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000743 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000744 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200745# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000746 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200747# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000748};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000749#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000750
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000751
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100752/* set -/+o OPT support. (TODO: make it optional)
753 * bash supports the following opts:
754 * allexport off
755 * braceexpand on
756 * emacs on
757 * errexit off
758 * errtrace off
759 * functrace off
760 * hashall on
761 * histexpand off
762 * history on
763 * ignoreeof off
764 * interactive-comments on
765 * keyword off
766 * monitor on
767 * noclobber off
768 * noexec off
769 * noglob off
770 * nolog off
771 * notify off
772 * nounset off
773 * onecmd off
774 * physical off
775 * pipefail off
776 * posix off
777 * privileged off
778 * verbose off
779 * vi off
780 * xtrace off
781 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800782static const char o_opt_strings[] ALIGN1 =
783 "pipefail\0"
784 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200785 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800786#if ENABLE_HUSH_MODE_X
787 "xtrace\0"
788#endif
789 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100790enum {
791 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800792 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200793 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800794#if ENABLE_HUSH_MODE_X
795 OPT_O_XTRACE,
796#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100797 NUM_OPT_O
798};
799
800
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200801struct FILE_list {
802 struct FILE_list *next;
803 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200804 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200805};
806
807
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000808/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000809/* Sorted roughly by size (smaller offsets == smaller code) */
810struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000811 /* interactive_fd != 0 means we are an interactive shell.
812 * If we are, then saved_tty_pgrp can also be != 0, meaning
813 * that controlling tty is available. With saved_tty_pgrp == 0,
814 * job control still works, but terminal signals
815 * (^C, ^Z, ^Y, ^\) won't work at all, and background
816 * process groups can only be created with "cmd &".
817 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
818 * to give tty to the foreground process group,
819 * and will take it back when the group is stopped (^Z)
820 * or killed (^C).
821 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000822#if ENABLE_HUSH_INTERACTIVE
823 /* 'interactive_fd' is a fd# open to ctty, if we have one
824 * _AND_ if we decided to act interactively */
825 int interactive_fd;
826 const char *PS1;
827 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000828# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000829#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000830# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000831#endif
832#if ENABLE_FEATURE_EDITING
833 line_input_t *line_input_state;
834#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000835 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200836 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000837 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200838#if ENABLE_HUSH_RANDOM_SUPPORT
839 random_t random_gen;
840#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000841#if ENABLE_HUSH_JOB
842 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100843 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000844 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000845 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400846# define G_saved_tty_pgrp (G.saved_tty_pgrp)
847#else
848# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000849#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200850 /* How deeply are we in context where "set -e" is ignored */
851 int errexit_depth;
852 /* "set -e" rules (do we follow them correctly?):
853 * Exit if pipe, list, or compound command exits with a non-zero status.
854 * Shell does not exit if failed command is part of condition in
855 * if/while, part of && or || list except the last command, any command
856 * in a pipe but the last, or if the command's return value is being
857 * inverted with !. If a compound command other than a subshell returns a
858 * non-zero status because a command failed while -e was being ignored, the
859 * shell does not exit. A trap on ERR, if set, is executed before the shell
860 * exits [ERR is a bashism].
861 *
862 * If a compound command or function executes in a context where -e is
863 * ignored, none of the commands executed within are affected by the -e
864 * setting. If a compound command or function sets -e while executing in a
865 * context where -e is ignored, that setting does not have any effect until
866 * the compound command or the command containing the function call completes.
867 */
868
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100869 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100870#if ENABLE_HUSH_MODE_X
871# define G_x_mode (G.o_opt[OPT_O_XTRACE])
872#else
873# define G_x_mode 0
874#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000875 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000876#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000877 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000878#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000879#if ENABLE_HUSH_FUNCTIONS
880 /* 0: outside of a function (or sourced file)
881 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000882 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000883 */
884 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200885# define G_flag_return_in_progress (G.flag_return_in_progress)
886#else
887# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000888#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000889 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000890 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000891 smalluint last_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200892 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100893#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000894 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000895 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100896# define G_global_args_malloced (G.global_args_malloced)
897#else
898# define G_global_args_malloced 0
899#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000900 /* how many non-NULL argv's we have. NB: $# + 1 */
901 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000902 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000903#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000904 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000905#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000906#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000907 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000908 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000909#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200910#if ENABLE_HUSH_GETOPTS
911 unsigned getopt_count;
912#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000913 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000914 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200915 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200916 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000917#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000918 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200919# if ENABLE_HUSH_LOCAL
920 struct variable **shadowed_vars_pp;
921 unsigned func_nest_level;
922# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000923#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000924 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200925#if ENABLE_HUSH_FAST
926 unsigned count_SIGCHLD;
927 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200928 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200929#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200930 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200931 /* Which signals have non-DFL handler (even with no traps set)?
932 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200933 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200934 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200935 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200936 * Other than these two times, never modified.
937 */
938 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200939#if ENABLE_HUSH_JOB
940 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100941# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200942#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200943# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200944#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100945#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000946 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100947# define G_traps G.traps
948#else
949# define G_traps ((char**)NULL)
950#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200951 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100952#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000953 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100954#endif
955#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000956 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000957#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200958 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200959#if ENABLE_FEATURE_EDITING
960 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
961#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000962};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000963#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000964/* Not #defining name to G.name - this quickly gets unwieldy
965 * (too many defines). Also, I actually prefer to see when a variable
966 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000967#define INIT_G() do { \
968 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200969 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
970 sigfillset(&G.sa.sa_mask); \
971 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000972} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000973
974
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000975/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200976static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100977#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200978static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100979#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200980static int builtin_eval(char **argv) FAST_FUNC;
981static int builtin_exec(char **argv) FAST_FUNC;
982static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100983#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200984static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100985#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +0200986#if ENABLE_HUSH_READONLY
987static int builtin_readonly(char **argv) FAST_FUNC;
988#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000989#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200990static int builtin_fg_bg(char **argv) FAST_FUNC;
991static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000992#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +0200993#if ENABLE_HUSH_GETOPTS
994static int builtin_getopts(char **argv) FAST_FUNC;
995#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000996#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200997static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000998#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200999#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001000static int builtin_history(char **argv) FAST_FUNC;
1001#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001002#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001003static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001004#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001005#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001006static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001007#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001008#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001009static int builtin_printf(char **argv) FAST_FUNC;
1010#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001011static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001012#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001013static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001014#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001015#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001016static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001017#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001018static int builtin_shift(char **argv) FAST_FUNC;
1019static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001020#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001021static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001022#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001023#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001024static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001025#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001026#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001027static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001028#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001029#if ENABLE_HUSH_TIMES
1030static int builtin_times(char **argv) FAST_FUNC;
1031#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001032static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001033#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001034static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001035#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001036#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001037static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001038#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001039#if ENABLE_HUSH_KILL
1040static int builtin_kill(char **argv) FAST_FUNC;
1041#endif
1042#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001043static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001044#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001045#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001046static int builtin_break(char **argv) FAST_FUNC;
1047static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001048#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001049#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001050static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001051#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001052
1053/* Table of built-in functions. They can be forked or not, depending on
1054 * context: within pipes, they fork. As simple commands, they do not.
1055 * When used in non-forking context, they can change global variables
1056 * in the parent shell process. If forked, of course they cannot.
1057 * For example, 'unset foo | whatever' will parse and run, but foo will
1058 * still be set at the end. */
1059struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001060 const char *b_cmd;
1061 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001062#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001063 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001064# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001065#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001066# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001067#endif
1068};
1069
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001070static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001071 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001072 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001073#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001074 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001075#endif
1076#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001077 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001078#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001079 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001080#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001081 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001082#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001083 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1084 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001085 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001086#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001087 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001088#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001089#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001090 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001091#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001092#if ENABLE_HUSH_GETOPTS
1093 BLTIN("getopts" , builtin_getopts , NULL),
1094#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001095#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001096 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001097#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001098#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001099 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001100#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001101#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001102 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001103#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001104#if ENABLE_HUSH_KILL
1105 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1106#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001107#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001108 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001109#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001110#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001111 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001112#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001113#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001114 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001115#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001116#if ENABLE_HUSH_READONLY
1117 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1118#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001119#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001120 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001121#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001122#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001123 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001124#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001125 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001126#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001127 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001128#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001129#if ENABLE_HUSH_TIMES
1130 BLTIN("times" , builtin_times , NULL),
1131#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001132#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001133 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001134#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001135 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001136#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001137 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001138#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001139#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001140 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001141#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001142#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001143 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001144#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001145#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001146 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001147#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001148#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001149 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001150#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001151};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001152/* These builtins won't be used if we are on NOMMU and need to re-exec
1153 * (it's cheaper to run an external program in this case):
1154 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001155static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001156#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001157 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001158#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001159#if BASH_TEST2
1160 BLTIN("[[" , builtin_test , NULL),
1161#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001162#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001163 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001164#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001165#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001166 BLTIN("printf" , builtin_printf , NULL),
1167#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001168 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001169#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001170 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001171#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001172};
1173
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001174
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001175/* Debug printouts.
1176 */
1177#if HUSH_DEBUG
1178/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001179# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001180# define debug_enter() (G.debug_indent++)
1181# define debug_leave() (G.debug_indent--)
1182#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001183# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001184# define debug_enter() ((void)0)
1185# define debug_leave() ((void)0)
1186#endif
1187
1188#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001189# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001190#endif
1191
1192#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001193# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001194#endif
1195
1196#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001197#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001198#endif
1199
1200#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001201# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001202#endif
1203
1204#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001205# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001206# define DEBUG_JOBS 1
1207#else
1208# define DEBUG_JOBS 0
1209#endif
1210
1211#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001212# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001213# define DEBUG_EXPAND 1
1214#else
1215# define DEBUG_EXPAND 0
1216#endif
1217
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001218#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001219# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001220#endif
1221
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001222#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001223# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001224# define DEBUG_GLOB 1
1225#else
1226# define DEBUG_GLOB 0
1227#endif
1228
Denys Vlasenko2db74612017-07-07 22:07:28 +02001229#ifndef debug_printf_redir
1230# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1231#endif
1232
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001233#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001234# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001235#endif
1236
1237#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001238# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001239#endif
1240
1241#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001242# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001243# define DEBUG_CLEAN 1
1244#else
1245# define DEBUG_CLEAN 0
1246#endif
1247
1248#if DEBUG_EXPAND
1249static void debug_print_strings(const char *prefix, char **vv)
1250{
1251 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001252 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001253 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001254 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001255}
1256#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001257# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258#endif
1259
1260
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001261/* Leak hunting. Use hush_leaktool.sh for post-processing.
1262 */
1263#if LEAK_HUNTING
1264static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001265{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001266 void *ptr = xmalloc((size + 0xff) & ~0xff);
1267 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1268 return ptr;
1269}
1270static void *xxrealloc(int lineno, void *ptr, size_t size)
1271{
1272 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1273 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1274 return ptr;
1275}
1276static char *xxstrdup(int lineno, const char *str)
1277{
1278 char *ptr = xstrdup(str);
1279 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1280 return ptr;
1281}
1282static void xxfree(void *ptr)
1283{
1284 fdprintf(2, "free %p\n", ptr);
1285 free(ptr);
1286}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001287# define xmalloc(s) xxmalloc(__LINE__, s)
1288# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1289# define xstrdup(s) xxstrdup(__LINE__, s)
1290# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001291#endif
1292
1293
1294/* Syntax and runtime errors. They always abort scripts.
1295 * In interactive use they usually discard unparsed and/or unexecuted commands
1296 * and return to the prompt.
1297 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1298 */
1299#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001300# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001301# define syntax_error(lineno, msg) syntax_error(msg)
1302# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1303# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1304# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1305# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001306#endif
1307
Denys Vlasenko39701202017-08-02 19:44:05 +02001308static void die_if_script(void)
1309{
1310 if (!G_interactive_fd) {
1311 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1312 xfunc_error_retval = G.last_exitcode;
1313 xfunc_die();
1314 }
1315}
1316
1317static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001318{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001319 va_list p;
1320
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001321#if HUSH_DEBUG >= 2
1322 bb_error_msg("hush.c:%u", lineno);
1323#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001324 va_start(p, fmt);
1325 bb_verror_msg(fmt, p, NULL);
1326 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001327 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001328}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001329
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001330static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001331{
1332 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001333 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001334 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001335 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001336 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001337}
1338
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001339static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001340{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001341 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001342 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001343}
1344
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001345static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001346{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001347 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001348//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1349// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001350}
1351
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001352static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001353{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001354 char msg[2] = { ch, '\0' };
1355 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001356}
1357
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001358static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001359{
1360 char msg[2];
1361 msg[0] = ch;
1362 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001363#if HUSH_DEBUG >= 2
1364 bb_error_msg("hush.c:%u", lineno);
1365#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001366 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001367 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001368}
1369
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001370#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001371# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001372# undef syntax_error
1373# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001374# undef syntax_error_unterm_ch
1375# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001376# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001377#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001378# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001379# define syntax_error(msg) syntax_error(__LINE__, msg)
1380# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1381# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1382# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1383# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001384#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001385
Denis Vlasenko552433b2009-04-04 19:29:21 +00001386
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001387#if ENABLE_HUSH_INTERACTIVE
1388static void cmdedit_update_prompt(void);
1389#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001390# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001391#endif
1392
1393
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001394/* Utility functions
1395 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001396/* Replace each \x with x in place, return ptr past NUL. */
1397static char *unbackslash(char *src)
1398{
Denys Vlasenko71885402009-09-24 01:44:13 +02001399 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001400 while (1) {
1401 if (*src == '\\')
1402 src++;
1403 if ((*dst++ = *src++) == '\0')
1404 break;
1405 }
1406 return dst;
1407}
1408
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001409static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001410{
1411 int i;
1412 unsigned count1;
1413 unsigned count2;
1414 char **v;
1415
1416 v = strings;
1417 count1 = 0;
1418 if (v) {
1419 while (*v) {
1420 count1++;
1421 v++;
1422 }
1423 }
1424 count2 = 0;
1425 v = add;
1426 while (*v) {
1427 count2++;
1428 v++;
1429 }
1430 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1431 v[count1 + count2] = NULL;
1432 i = count2;
1433 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001434 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001435 return v;
1436}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001437#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001438static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1439{
1440 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1441 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1442 return ptr;
1443}
1444#define add_strings_to_strings(strings, add, need_to_dup) \
1445 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1446#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001447
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001448/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001449static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001450{
1451 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001452 v[0] = add;
1453 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001454 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001455}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001456#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001457static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1458{
1459 char **ptr = add_string_to_strings(strings, add);
1460 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1461 return ptr;
1462}
1463#define add_string_to_strings(strings, add) \
1464 xx_add_string_to_strings(__LINE__, strings, add)
1465#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001466
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001467static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001468{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001469 char **v;
1470
1471 if (!strings)
1472 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001473 v = strings;
1474 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001475 free(*v);
1476 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001477 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001478 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001479}
1480
Denys Vlasenko2db74612017-07-07 22:07:28 +02001481static int fcntl_F_DUPFD(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001482{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001483 int newfd;
1484 repeat:
1485 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001486 if (newfd < 0) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001487 if (errno == EBUSY)
1488 goto repeat;
1489 if (errno == EINTR)
1490 goto repeat;
1491 }
1492 return newfd;
1493}
1494
Denys Vlasenko657e9002017-07-30 23:34:04 +02001495static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001496{
1497 int newfd;
1498 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001499 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001500 if (newfd < 0) {
1501 if (errno == EBUSY)
1502 goto repeat;
1503 if (errno == EINTR)
1504 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001505 /* fd was not open? */
1506 if (errno == EBADF)
1507 return fd;
1508 xfunc_die();
1509 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001510 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1511 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001512 close(fd);
1513 return newfd;
1514}
1515
1516
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001517/* Manipulating the list of open FILEs */
1518static FILE *remember_FILE(FILE *fp)
1519{
1520 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001521 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001522 n->next = G.FILE_list;
1523 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001524 n->fp = fp;
1525 n->fd = fileno(fp);
1526 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001527 }
1528 return fp;
1529}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001530static void fclose_and_forget(FILE *fp)
1531{
1532 struct FILE_list **pp = &G.FILE_list;
1533 while (*pp) {
1534 struct FILE_list *cur = *pp;
1535 if (cur->fp == fp) {
1536 *pp = cur->next;
1537 free(cur);
1538 break;
1539 }
1540 pp = &cur->next;
1541 }
1542 fclose(fp);
1543}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001544static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001545{
1546 struct FILE_list *fl = G.FILE_list;
1547 while (fl) {
1548 if (fd == fl->fd) {
1549 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001550 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001551 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 +02001552 return 1;
1553 }
1554 fl = fl->next;
1555 }
1556 return 0;
1557}
1558static void restore_redirected_FILEs(void)
1559{
1560 struct FILE_list *fl = G.FILE_list;
1561 while (fl) {
1562 int should_be = fileno(fl->fp);
1563 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001564 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001565 xmove_fd(fl->fd, should_be);
1566 fl->fd = should_be;
1567 }
1568 fl = fl->next;
1569 }
1570}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001571#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001572static void close_all_FILE_list(void)
1573{
1574 struct FILE_list *fl = G.FILE_list;
1575 while (fl) {
1576 /* fclose would also free FILE object.
1577 * It is disastrous if we share memory with a vforked parent.
1578 * I'm not sure we never come here after vfork.
1579 * Therefore just close fd, nothing more.
1580 */
1581 /*fclose(fl->fp); - unsafe */
1582 close(fl->fd);
1583 fl = fl->next;
1584 }
1585}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001586#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001587static int fd_in_FILEs(int fd)
1588{
1589 struct FILE_list *fl = G.FILE_list;
1590 while (fl) {
1591 if (fl->fd == fd)
1592 return 1;
1593 fl = fl->next;
1594 }
1595 return 0;
1596}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001597
1598
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001599/* Helpers for setting new $n and restoring them back
1600 */
1601typedef struct save_arg_t {
1602 char *sv_argv0;
1603 char **sv_g_argv;
1604 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001605 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001606} save_arg_t;
1607
1608static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1609{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001610 sv->sv_argv0 = argv[0];
1611 sv->sv_g_argv = G.global_argv;
1612 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001613 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001614
1615 argv[0] = G.global_argv[0]; /* retain $0 */
1616 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001617 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001618
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001619 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001620}
1621
1622static void restore_G_args(save_arg_t *sv, char **argv)
1623{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001624#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001625 if (G.global_args_malloced) {
1626 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001627 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001628 while (*++pp) /* note: does not free $0 */
1629 free(*pp);
1630 free(G.global_argv);
1631 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001632#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001633 argv[0] = sv->sv_argv0;
1634 G.global_argv = sv->sv_g_argv;
1635 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001636 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001637}
1638
1639
Denis Vlasenkod5762932009-03-31 11:22:57 +00001640/* Basic theory of signal handling in shell
1641 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001642 * This does not describe what hush does, rather, it is current understanding
1643 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001644 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1645 *
1646 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1647 * is finished or backgrounded. It is the same in interactive and
1648 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001649 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001650 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001651 * backgrounds (i.e. stops) or kills all members of currently running
1652 * pipe.
1653 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001654 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001655 * or by SIGINT in interactive shell.
1656 *
1657 * Trap handlers will execute even within trap handlers. (right?)
1658 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001659 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1660 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001661 *
1662 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001663 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001664 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001665 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001666 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001667 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001668 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001669 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001670 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001671 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001672 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001673 *
1674 * SIGQUIT: ignore
1675 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001676 * SIGHUP (interactive):
1677 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001678 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001679 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1680 * that all pipe members are stopped. Try this in bash:
1681 * while :; do :; done - ^Z does not background it
1682 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001683 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001684 * of the command line, show prompt. NB: ^C does not send SIGINT
1685 * to interactive shell while shell is waiting for a pipe,
1686 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001687 * Example 1: this waits 5 sec, but does not execute ls:
1688 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1689 * Example 2: this does not wait and does not execute ls:
1690 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1691 * Example 3: this does not wait 5 sec, but executes ls:
1692 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001693 * Example 4: this does not wait and does not execute ls:
1694 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001695 *
1696 * (What happens to signals which are IGN on shell start?)
1697 * (What happens with signal mask on shell start?)
1698 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001699 * Old implementation
1700 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001701 * We use in-kernel pending signal mask to determine which signals were sent.
1702 * We block all signals which we don't want to take action immediately,
1703 * i.e. we block all signals which need to have special handling as described
1704 * above, and all signals which have traps set.
1705 * After each pipe execution, we extract any pending signals via sigtimedwait()
1706 * and act on them.
1707 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001708 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001709 * sigset_t blocked_set: current blocked signal set
1710 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001711 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001712 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001713 * "trap 'cmd' SIGxxx":
1714 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001715 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001716 * unblock signals with special interactive handling
1717 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001718 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001719 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001720 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001721 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001722 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001723 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001724 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001725 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001726 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001727 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001728 * Standard says "When a subshell is entered, traps that are not being ignored
1729 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001730 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001731 *
1732 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001733 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001734 * masked signals are not visible!
1735 *
1736 * New implementation
1737 * ==================
1738 * We record each signal we are interested in by installing signal handler
1739 * for them - a bit like emulating kernel pending signal mask in userspace.
1740 * We are interested in: signals which need to have special handling
1741 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001742 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001743 * After each pipe execution, we extract any pending signals
1744 * and act on them.
1745 *
1746 * unsigned special_sig_mask: a mask of shell-special signals.
1747 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1748 * char *traps[sig] if trap for sig is set (even if it's '').
1749 * sigset_t pending_set: set of sigs we received.
1750 *
1751 * "trap - SIGxxx":
1752 * if sig is in special_sig_mask, set handler back to:
1753 * record_pending_signo, or to IGN if it's a tty stop signal
1754 * if sig is in fatal_sig_mask, set handler back to sigexit.
1755 * else: set handler back to SIG_DFL
1756 * "trap 'cmd' SIGxxx":
1757 * set handler to record_pending_signo.
1758 * "trap '' SIGxxx":
1759 * set handler to SIG_IGN.
1760 * after [v]fork, if we plan to be a shell:
1761 * set signals with special interactive handling to SIG_DFL
1762 * (because child shell is not interactive),
1763 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1764 * after [v]fork, if we plan to exec:
1765 * POSIX says fork clears pending signal mask in child - no need to clear it.
1766 *
1767 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1768 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1769 *
1770 * Note (compat):
1771 * Standard says "When a subshell is entered, traps that are not being ignored
1772 * are set to the default actions". bash interprets it so that traps which
1773 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001774 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001775enum {
1776 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001777 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001778 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001779 | (1 << SIGHUP)
1780 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001781 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001782#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001783 | (1 << SIGTTIN)
1784 | (1 << SIGTTOU)
1785 | (1 << SIGTSTP)
1786#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001787 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001788};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001789
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001790static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001791{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001792 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001793#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001794 if (sig == SIGCHLD) {
1795 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001796//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 +02001797 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001798#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001799}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001800
Denys Vlasenko0806e402011-05-12 23:06:20 +02001801static sighandler_t install_sighandler(int sig, sighandler_t handler)
1802{
1803 struct sigaction old_sa;
1804
1805 /* We could use signal() to install handlers... almost:
1806 * except that we need to mask ALL signals while handlers run.
1807 * I saw signal nesting in strace, race window isn't small.
1808 * SA_RESTART is also needed, but in Linux, signal()
1809 * sets SA_RESTART too.
1810 */
1811 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1812 /* sigfillset(&G.sa.sa_mask); - already done */
1813 /* G.sa.sa_flags = SA_RESTART; - already done */
1814 G.sa.sa_handler = handler;
1815 sigaction(sig, &G.sa, &old_sa);
1816 return old_sa.sa_handler;
1817}
1818
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001819static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001820
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001821static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001822static void restore_ttypgrp_and__exit(void)
1823{
1824 /* xfunc has failed! die die die */
1825 /* no EXIT traps, this is an escape hatch! */
1826 G.exiting = 1;
1827 hush_exit(xfunc_error_retval);
1828}
1829
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001830#if ENABLE_HUSH_JOB
1831
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001832/* Needed only on some libc:
1833 * It was observed that on exit(), fgetc'ed buffered data
1834 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1835 * With the net effect that even after fork(), not vfork(),
1836 * exit() in NOEXECed applet in "sh SCRIPT":
1837 * noexec_applet_here
1838 * echo END_OF_SCRIPT
1839 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1840 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001841 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001842 * and in `cmd` handling.
1843 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1844 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001845static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001846static void fflush_and__exit(void)
1847{
1848 fflush_all();
1849 _exit(xfunc_error_retval);
1850}
1851
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001852/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001853# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001854/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001855# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001856
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001857/* Restores tty foreground process group, and exits.
1858 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001859 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001860 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001861 * We also call it if xfunc is exiting.
1862 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001863static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001864static void sigexit(int sig)
1865{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001866 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001867 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001868 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1869 /* Disable all signals: job control, SIGPIPE, etc.
1870 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1871 */
1872 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001873 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001874 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001875
1876 /* Not a signal, just exit */
1877 if (sig <= 0)
1878 _exit(- sig);
1879
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001880 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001881}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001882#else
1883
Denys Vlasenko8391c482010-05-22 17:50:43 +02001884# define disable_restore_tty_pgrp_on_exit() ((void)0)
1885# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001886
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001887#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001888
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001889static sighandler_t pick_sighandler(unsigned sig)
1890{
1891 sighandler_t handler = SIG_DFL;
1892 if (sig < sizeof(unsigned)*8) {
1893 unsigned sigmask = (1 << sig);
1894
1895#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001896 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001897 if (G_fatal_sig_mask & sigmask)
1898 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001899 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001900#endif
1901 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001902 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001903 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001904 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001905 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001906 * in an endless loop when we try to do some
1907 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001908 */
1909 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1910 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001911 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001912 }
1913 return handler;
1914}
1915
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001916/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001917static void hush_exit(int exitcode)
1918{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001919#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1920 save_history(G.line_input_state);
1921#endif
1922
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001923 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001924 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001925 char *argv[3];
1926 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001927 argv[1] = G_traps[0];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001928 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001929 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001930 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001931 * "trap" will still show it, if executed
1932 * in the handler */
1933 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001934 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001935
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001936#if ENABLE_FEATURE_CLEAN_UP
1937 {
1938 struct variable *cur_var;
1939 if (G.cwd != bb_msg_unknown)
1940 free((char*)G.cwd);
1941 cur_var = G.top_var;
1942 while (cur_var) {
1943 struct variable *tmp = cur_var;
1944 if (!cur_var->max_len)
1945 free(cur_var->varstr);
1946 cur_var = cur_var->next;
1947 free(tmp);
1948 }
1949 }
1950#endif
1951
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001952 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001953#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001954 sigexit(- (exitcode & 0xff));
1955#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001956 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001957#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001958}
1959
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001960
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001961//TODO: return a mask of ALL handled sigs?
1962static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001963{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001964 int last_sig = 0;
1965
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001966 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001967 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001968
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001969 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001970 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001971 sig = 0;
1972 do {
1973 sig++;
1974 if (sigismember(&G.pending_set, sig)) {
1975 sigdelset(&G.pending_set, sig);
1976 goto got_sig;
1977 }
1978 } while (sig < NSIG);
1979 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001980 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001981 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001982 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001983 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001984 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001985 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001986 char *argv[3];
1987 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001988 argv[1] = G_traps[sig];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001989 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001990 save_rcode = G.last_exitcode;
1991 builtin_eval(argv);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01001992//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001993 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001994 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001995 } /* else: "" trap, ignoring signal */
1996 continue;
1997 }
1998 /* not a trap: special action */
1999 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002000 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002001 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002002 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002003 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002004 break;
2005#if ENABLE_HUSH_JOB
2006 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002007//TODO: why are we doing this? ash and dash don't do this,
2008//they have no handler for SIGHUP at all,
2009//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002010 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002011 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002012 /* bash is observed to signal whole process groups,
2013 * not individual processes */
2014 for (job = G.job_list; job; job = job->next) {
2015 if (job->pgrp <= 0)
2016 continue;
2017 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2018 if (kill(- job->pgrp, SIGHUP) == 0)
2019 kill(- job->pgrp, SIGCONT);
2020 }
2021 sigexit(SIGHUP);
2022 }
2023#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002024#if ENABLE_HUSH_FAST
2025 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002026 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002027 G.count_SIGCHLD++;
2028//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2029 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002030 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002031 * This simplifies wait builtin a bit.
2032 */
2033 break;
2034#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002035 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002036 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002037 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002038 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002039 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002040 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002041 * in interactive shell, because TERM is ignored.
2042 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002043 break;
2044 }
2045 }
2046 return last_sig;
2047}
2048
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002049
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002050static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002051{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002052 if (force || G.cwd == NULL) {
2053 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2054 * we must not try to free(bb_msg_unknown) */
2055 if (G.cwd == bb_msg_unknown)
2056 G.cwd = NULL;
2057 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2058 if (!G.cwd)
2059 G.cwd = bb_msg_unknown;
2060 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002061 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002062}
2063
Denis Vlasenko83506862007-11-23 13:11:42 +00002064
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002065/*
2066 * Shell and environment variable support
2067 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002068static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002069{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002070 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002071 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002072
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002073 pp = &G.top_var;
2074 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002075 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002076 return pp;
2077 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002078 }
2079 return NULL;
2080}
2081
Denys Vlasenko03dad222010-01-12 23:29:57 +01002082static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002083{
Denys Vlasenko29082232010-07-16 13:52:32 +02002084 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002085 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002086
2087 if (G.expanded_assignments) {
2088 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002089 while (*cpp) {
2090 char *cp = *cpp;
2091 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2092 return cp + len + 1;
2093 cpp++;
2094 }
2095 }
2096
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002097 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002098 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002099 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002100
Denys Vlasenkodea47882009-10-09 15:40:49 +02002101 if (strcmp(name, "PPID") == 0)
2102 return utoa(G.root_ppid);
2103 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002104#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002105 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002106 return utoa(next_random(&G.random_gen));
2107#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002108 return NULL;
2109}
2110
2111/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002112 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002113 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002114#define SETFLAG_EXPORT (1 << 0)
2115#define SETFLAG_UNEXPORT (1 << 1)
2116#define SETFLAG_MAKE_RO (1 << 2)
2117#define SETFLAG_LOCAL_SHIFT 3
2118static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002119{
Denys Vlasenko295fef82009-06-03 12:47:26 +02002120 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002121 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002122 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002123 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002124 int name_len;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002125 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002126
Denis Vlasenko950bd722009-04-21 11:23:56 +00002127 eq_sign = strchr(str, '=');
2128 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129 free(str);
2130 return -1;
2131 }
2132
Denis Vlasenko950bd722009-04-21 11:23:56 +00002133 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002134 var_pp = &G.top_var;
2135 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002136 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002137 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002138 continue;
2139 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002140
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002142 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002143 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002144 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002145//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2146//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002147 return -1;
2148 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002149 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002150 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2151 *eq_sign = '\0';
2152 unsetenv(str);
2153 *eq_sign = '=';
2154 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002155#if ENABLE_HUSH_LOCAL
2156 if (cur->func_nest_level < local_lvl) {
2157 /* New variable is declared as local,
2158 * and existing one is global, or local
2159 * from enclosing function.
2160 * Remove and save old one: */
2161 *var_pp = cur->next;
2162 cur->next = *G.shadowed_vars_pp;
2163 *G.shadowed_vars_pp = cur;
2164 /* bash 3.2.33(1) and exported vars:
2165 * # export z=z
2166 * # f() { local z=a; env | grep ^z; }
2167 * # f
2168 * z=a
2169 * # env | grep ^z
2170 * z=z
2171 */
2172 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002173 flags |= SETFLAG_EXPORT;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002174 break;
2175 }
2176#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00002177 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002178 free_and_exp:
2179 free(str);
2180 goto exp;
2181 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002182 if (cur->max_len != 0) {
2183 if (cur->max_len >= strlen(str)) {
2184 /* This one is from startup env, reuse space */
2185 strcpy(cur->varstr, str);
2186 goto free_and_exp;
2187 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002188 /* Can't reuse */
2189 cur->max_len = 0;
2190 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002191 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002192 /* max_len == 0 signifies "malloced" var, which we can
2193 * (and have to) free. But we can't free(cur->varstr) here:
2194 * if cur->flg_export is 1, it is in the environment.
2195 * We should either unsetenv+free, or wait until putenv,
2196 * then putenv(new)+free(old).
2197 */
2198 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002199 goto set_str_and_exp;
2200 }
2201
Denys Vlasenko295fef82009-06-03 12:47:26 +02002202 /* Not found - create new variable struct */
2203 cur = xzalloc(sizeof(*cur));
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002204 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
Denys Vlasenko295fef82009-06-03 12:47:26 +02002205 cur->next = *var_pp;
2206 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002207
2208 set_str_and_exp:
2209 cur->varstr = str;
2210 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002211#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002212 if (flags & SETFLAG_MAKE_RO) {
2213 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002214 }
2215#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002216 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002217 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002218 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2219 cmdedit_update_prompt();
Denys Vlasenko238ff982017-08-29 13:38:30 +02002220#if ENABLE_HUSH_GETOPTS
Denys Vlasenko55af51c2017-08-29 13:48:49 +02002221 /* defoptindvar is a "OPTIND=..." constant string */
2222 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
Denys Vlasenko238ff982017-08-29 13:38:30 +02002223 G.getopt_count = 0;
2224#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002225 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002226 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002227 cur->flg_export = 0;
2228 /* unsetenv was already done */
2229 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002230 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002231 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002232 i = putenv(cur->varstr);
2233 /* only now we can free old exported malloced string */
2234 free(free_me);
2235 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002236 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002237 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002238 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002239 return 0;
2240}
2241
Denys Vlasenko6db47842009-09-05 20:15:17 +02002242/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002243static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002244{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002245 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002246}
2247
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002248static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002249{
2250 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002251 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002252
2253 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002254 return EXIT_SUCCESS;
Denys Vlasenko238ff982017-08-29 13:38:30 +02002255#if ENABLE_HUSH_GETOPTS
2256 if (name_len == 6 && strncmp(name, "OPTIND", 6) == 0)
2257 G.getopt_count = 0;
2258#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002259 var_pp = &G.top_var;
2260 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002261 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2262 if (cur->flg_read_only) {
2263 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002264 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002265 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002266 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002267 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2268 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002269 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2270 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002271 if (!cur->max_len)
2272 free(cur->varstr);
2273 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002274 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002275 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002276 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002277 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002278 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002279}
2280
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002281#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002282static int unset_local_var(const char *name)
2283{
2284 return unset_local_var_len(name, strlen(name));
2285}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002286#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002287
2288static void unset_vars(char **strings)
2289{
2290 char **v;
2291
2292 if (!strings)
2293 return;
2294 v = strings;
2295 while (*v) {
2296 const char *eq = strchrnul(*v, '=');
2297 unset_local_var_len(*v, (int)(eq - *v));
2298 v++;
2299 }
2300 free(strings);
2301}
2302
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002303#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002304static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002305{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002306 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002307 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002308}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002309#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002310
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002311
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002312/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002313 * Helpers for "var1=val1 var2=val2 cmd" feature
2314 */
2315static void add_vars(struct variable *var)
2316{
2317 struct variable *next;
2318
2319 while (var) {
2320 next = var->next;
2321 var->next = G.top_var;
2322 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002323 if (var->flg_export) {
2324 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002325 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002326 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002327 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002328 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002329 var = next;
2330 }
2331}
2332
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002333static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002334{
2335 char **s;
2336 struct variable *old = NULL;
2337
2338 if (!strings)
2339 return old;
2340 s = strings;
2341 while (*s) {
2342 struct variable *var_p;
2343 struct variable **var_pp;
2344 char *eq;
2345
2346 eq = strchr(*s, '=');
2347 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002348 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002349 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002350 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002351 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002352 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002353 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002354 /*
2355 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2356 * If VAR is readonly, leaving it in the list
2357 * after asssignment error (msg above)
2358 * causes doubled error message later, on unset.
2359 */
2360 debug_printf_env("removing/freeing '%s' element\n", *s);
2361 free(*s);
2362 p = s;
2363 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002364 goto next;
2365 }
2366 /* Remove variable from global linked list */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002367 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002368 *var_pp = var_p->next;
2369 /* Add it to returned list */
2370 var_p->next = old;
2371 old = var_p;
2372 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002373 set_local_var(*s, SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002374 }
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002375 next:
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002376 s++;
2377 }
2378 return old;
2379}
2380
2381
2382/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002383 * Unicode helper
2384 */
2385static void reinit_unicode_for_hush(void)
2386{
2387 /* Unicode support should be activated even if LANG is set
2388 * _during_ shell execution, not only if it was set when
2389 * shell was started. Therefore, re-check LANG every time:
2390 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002391 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2392 || ENABLE_UNICODE_USING_LOCALE
2393 ) {
2394 const char *s = get_local_var_value("LC_ALL");
2395 if (!s) s = get_local_var_value("LC_CTYPE");
2396 if (!s) s = get_local_var_value("LANG");
2397 reinit_unicode(s);
2398 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002399}
2400
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002401/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002402 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002403 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002404
2405#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002406/* To test correct lineedit/interactive behavior, type from command line:
2407 * echo $P\
2408 * \
2409 * AT\
2410 * H\
2411 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002412 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002413 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002414static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002415{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002416 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002417 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002418 if (G.PS1 == NULL)
2419 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002420 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002421 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002422 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002423 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002424 if (G.PS2 == NULL)
2425 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002426}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002427static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002428{
2429 const char *prompt_str;
2430 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002431 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2432 /* Set up the prompt */
2433 if (promptmode == 0) { /* PS1 */
2434 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002435 /* bash uses $PWD value, even if it is set by user.
2436 * It uses current dir only if PWD is unset.
2437 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002438 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002439 prompt_str = G.PS1;
2440 } else
2441 prompt_str = G.PS2;
2442 } else
2443 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002444 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002445 return prompt_str;
2446}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002447static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002448{
2449 int r;
2450 const char *prompt_str;
2451
2452 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002453# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002454 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002455 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002456 if (G.flag_SIGINT) {
2457 /* There was ^C'ed, make it look prettier: */
2458 bb_putchar('\n');
2459 G.flag_SIGINT = 0;
2460 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002461 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002462 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002463 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002464 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002465 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002466 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002467 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002468 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002469 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002470 if (r != 0 && !G.flag_SIGINT)
2471 break;
2472 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002473 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2474 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002475 G.last_exitcode = 128 + SIGINT;
2476 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002477 if (r < 0) {
2478 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002479 i->p = NULL;
2480 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002481 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002482 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002483 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002484 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002485# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002486 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002487 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002488 if (i->last_char == '\0' || i->last_char == '\n') {
2489 /* Why check_and_run_traps here? Try this interactively:
2490 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2491 * $ <[enter], repeatedly...>
2492 * Without check_and_run_traps, handler never runs.
2493 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002494 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002495 fputs(prompt_str, stdout);
2496 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002497 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002498//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002499 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002500 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2501 * no ^C masking happens during fgetc, no special code for ^C:
2502 * it generates SIGINT as usual.
2503 */
2504 check_and_run_traps();
2505 if (G.flag_SIGINT)
2506 G.last_exitcode = 128 + SIGINT;
2507 if (r != '\0')
2508 break;
2509 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002510 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002511# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002512}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002513/* This is the magic location that prints prompts
2514 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002515static int fgetc_interactive(struct in_str *i)
2516{
2517 int ch;
2518 /* If it's interactive stdin, get new line. */
2519 if (G_interactive_fd && i->file == stdin) {
2520 /* Returns first char (or EOF), the rest is in i->p[] */
2521 ch = get_user_input(i);
2522 i->promptmode = 1; /* PS2 */
2523 } else {
2524 /* Not stdin: script file, sourced file, etc */
2525 do ch = fgetc(i->file); while (ch == '\0');
2526 }
2527 return ch;
2528}
2529#else
2530static inline int fgetc_interactive(struct in_str *i)
2531{
2532 int ch;
2533 do ch = fgetc(i->file); while (ch == '\0');
2534 return ch;
2535}
2536#endif /* INTERACTIVE */
2537
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002538static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002539{
2540 int ch;
2541
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002542 if (!i->file) {
2543 /* string-based in_str */
2544 ch = (unsigned char)*i->p;
2545 if (ch != '\0') {
2546 i->p++;
2547 i->last_char = ch;
2548 return ch;
2549 }
2550 return EOF;
2551 }
2552
2553 /* FILE-based in_str */
2554
Denys Vlasenko4074d492016-09-30 01:49:53 +02002555#if ENABLE_FEATURE_EDITING
2556 /* This can be stdin, check line editing char[] buffer */
2557 if (i->p && *i->p != '\0') {
2558 ch = (unsigned char)*i->p++;
2559 goto out;
2560 }
2561#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002562 /* peek_buf[] is an int array, not char. Can contain EOF. */
2563 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002564 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002565 int ch2 = i->peek_buf[1];
2566 i->peek_buf[0] = ch2;
2567 if (ch2 == 0) /* very likely, avoid redundant write */
2568 goto out;
2569 i->peek_buf[1] = 0;
2570 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002571 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002572
Denys Vlasenko4074d492016-09-30 01:49:53 +02002573 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002574 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002575 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002576 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002577 return ch;
2578}
2579
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002580static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002581{
2582 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002583
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002584 if (!i->file) {
2585 /* string-based in_str */
2586 /* Doesn't report EOF on NUL. None of the callers care. */
2587 return (unsigned char)*i->p;
2588 }
2589
2590 /* FILE-based in_str */
2591
Denys Vlasenko4074d492016-09-30 01:49:53 +02002592#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002593 /* This can be stdin, check line editing char[] buffer */
2594 if (i->p && *i->p != '\0')
2595 return (unsigned char)*i->p;
2596#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002597 /* peek_buf[] is an int array, not char. Can contain EOF. */
2598 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002599 if (ch != 0)
2600 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002601
Denys Vlasenko4074d492016-09-30 01:49:53 +02002602 /* Need to get a new char */
2603 ch = fgetc_interactive(i);
2604 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2605
2606 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2607#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2608 if (i->p) {
2609 i->p -= 1;
2610 return ch;
2611 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002612#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002613 i->peek_buf[0] = ch;
2614 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002615 return ch;
2616}
2617
Denys Vlasenko4074d492016-09-30 01:49:53 +02002618/* Only ever called if i_peek() was called, and did not return EOF.
2619 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2620 * not end-of-line. Therefore we never need to read a new editing line here.
2621 */
2622static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002623{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002624 int ch;
2625
2626 /* There are two cases when i->p[] buffer exists.
2627 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002628 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002629 * In both cases, we know that i->p[0] exists and not NUL, and
2630 * the peek2 result is in i->p[1].
2631 */
2632 if (i->p)
2633 return (unsigned char)i->p[1];
2634
2635 /* Now we know it is a file-based in_str. */
2636
2637 /* peek_buf[] is an int array, not char. Can contain EOF. */
2638 /* Is there 2nd char? */
2639 ch = i->peek_buf[1];
2640 if (ch == 0) {
2641 /* We did not read it yet, get it now */
2642 do ch = fgetc(i->file); while (ch == '\0');
2643 i->peek_buf[1] = ch;
2644 }
2645
2646 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2647 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002648}
2649
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002650static void setup_file_in_str(struct in_str *i, FILE *f)
2651{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002652 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002653 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002654 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002655 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002656}
2657
2658static void setup_string_in_str(struct in_str *i, const char *s)
2659{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002660 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002661 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002662 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002663 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002664}
2665
2666
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002667/*
2668 * o_string support
2669 */
2670#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002671
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002672static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002673{
2674 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002675 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002676 if (o->data)
2677 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002678}
2679
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002680static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002681{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002682 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002683 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002684}
2685
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002686static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2687{
2688 free(o->data);
2689}
2690
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002691static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002692{
2693 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002694 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002695 o->data = xrealloc(o->data, 1 + o->maxlen);
2696 }
2697}
2698
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002699static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002700{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002701 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002702 if (o->length < o->maxlen) {
2703 /* likely. avoid o_grow_by() call */
2704 add:
2705 o->data[o->length] = ch;
2706 o->length++;
2707 o->data[o->length] = '\0';
2708 return;
2709 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002710 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002711 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002712}
2713
Denys Vlasenko657086a2016-09-29 18:07:42 +02002714#if 0
2715/* Valid only if we know o_string is not empty */
2716static void o_delchr(o_string *o)
2717{
2718 o->length--;
2719 o->data[o->length] = '\0';
2720}
2721#endif
2722
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002723static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002724{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002725 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002726 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002727 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002728}
2729
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002730static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002731{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002732 o_addblock(o, str, strlen(str));
2733}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002734
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002735#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002736static void nommu_addchr(o_string *o, int ch)
2737{
2738 if (o)
2739 o_addchr(o, ch);
2740}
2741#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002742# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002743#endif
2744
2745static void o_addstr_with_NUL(o_string *o, const char *str)
2746{
2747 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002748}
2749
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002750/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002751 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002752 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2753 * Apparently, on unquoted $v bash still does globbing
2754 * ("v='*.txt'; echo $v" prints all .txt files),
2755 * but NOT brace expansion! Thus, there should be TWO independent
2756 * quoting mechanisms on $v expansion side: one protects
2757 * $v from brace expansion, and other additionally protects "$v" against globbing.
2758 * We have only second one.
2759 */
2760
Denys Vlasenko9e800222010-10-03 14:28:04 +02002761#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002762# define MAYBE_BRACES "{}"
2763#else
2764# define MAYBE_BRACES ""
2765#endif
2766
Eric Andersen25f27032001-04-26 23:22:31 +00002767/* My analysis of quoting semantics tells me that state information
2768 * is associated with a destination, not a source.
2769 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002770static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002771{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002772 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002773 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002774 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002775 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002776 o_grow_by(o, sz);
2777 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002778 o->data[o->length] = '\\';
2779 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002780 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002781 o->data[o->length] = ch;
2782 o->length++;
2783 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002784}
2785
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002786static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002787{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002788 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002789 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2790 && strchr("*?[\\" MAYBE_BRACES, ch)
2791 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002792 sz++;
2793 o->data[o->length] = '\\';
2794 o->length++;
2795 }
2796 o_grow_by(o, sz);
2797 o->data[o->length] = ch;
2798 o->length++;
2799 o->data[o->length] = '\0';
2800}
2801
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002802static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002803{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002804 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002805 char ch;
2806 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002807 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002808 if (ordinary_cnt > len) /* paranoia */
2809 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002810 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002811 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002812 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002813 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002814 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002815
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002816 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002817 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002818 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002819 sz++;
2820 o->data[o->length] = '\\';
2821 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002822 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002823 o_grow_by(o, sz);
2824 o->data[o->length] = ch;
2825 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002826 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002827 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002828}
2829
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002830static void o_addQblock(o_string *o, const char *str, int len)
2831{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002832 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002833 o_addblock(o, str, len);
2834 return;
2835 }
2836 o_addqblock(o, str, len);
2837}
2838
Denys Vlasenko38292b62010-09-05 14:49:40 +02002839static void o_addQstr(o_string *o, const char *str)
2840{
2841 o_addQblock(o, str, strlen(str));
2842}
2843
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002844/* A special kind of o_string for $VAR and `cmd` expansion.
2845 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002846 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002847 * list[i] contains an INDEX (int!) into this string data.
2848 * It means that if list[] needs to grow, data needs to be moved higher up
2849 * but list[i]'s need not be modified.
2850 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002851 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002852 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2853 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002854#if DEBUG_EXPAND || DEBUG_GLOB
2855static void debug_print_list(const char *prefix, o_string *o, int n)
2856{
2857 char **list = (char**)o->data;
2858 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2859 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002860
2861 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002862 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 +02002863 prefix, list, n, string_start, o->length, o->maxlen,
2864 !!(o->o_expflags & EXP_FLAG_GLOB),
2865 o->has_quoted_part,
2866 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002867 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002868 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002869 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2870 o->data + (int)(uintptr_t)list[i] + string_start,
2871 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002872 i++;
2873 }
2874 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002875 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002876 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002877 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002878 }
2879}
2880#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002881# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002882#endif
2883
2884/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2885 * in list[n] so that it points past last stored byte so far.
2886 * It returns n+1. */
2887static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002888{
2889 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002890 int string_start;
2891 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002892
2893 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002894 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2895 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002896 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002897 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002898 /* list[n] points to string_start, make space for 16 more pointers */
2899 o->maxlen += 0x10 * sizeof(list[0]);
2900 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002901 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002902 memmove(list + n + 0x10, list + n, string_len);
2903 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002904 } else {
2905 debug_printf_list("list[%d]=%d string_start=%d\n",
2906 n, string_len, string_start);
2907 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002908 } else {
2909 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002910 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2911 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002912 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2913 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002914 o->has_empty_slot = 0;
2915 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002916 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002917 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002918 return n + 1;
2919}
2920
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002921/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002922static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002923{
2924 char **list = (char**)o->data;
2925 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2926
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002927 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002928}
2929
Denys Vlasenko9e800222010-10-03 14:28:04 +02002930#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002931/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2932 * first, it processes even {a} (no commas), second,
2933 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002934 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002935 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002936
2937/* Helper */
2938static int glob_needed(const char *s)
2939{
2940 while (*s) {
2941 if (*s == '\\') {
2942 if (!s[1])
2943 return 0;
2944 s += 2;
2945 continue;
2946 }
2947 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2948 return 1;
2949 s++;
2950 }
2951 return 0;
2952}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002953/* Return pointer to next closing brace or to comma */
2954static const char *next_brace_sub(const char *cp)
2955{
2956 unsigned depth = 0;
2957 cp++;
2958 while (*cp != '\0') {
2959 if (*cp == '\\') {
2960 if (*++cp == '\0')
2961 break;
2962 cp++;
2963 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002964 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002965 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002966 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002967 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002968 depth++;
2969 }
2970
2971 return *cp != '\0' ? cp : NULL;
2972}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002973/* Recursive brace globber. Note: may garble pattern[]. */
2974static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002975{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002976 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002977 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002978 const char *next;
2979 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002980 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002981 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002982
2983 debug_printf_glob("glob_brace('%s')\n", pattern);
2984
2985 begin = pattern;
2986 while (1) {
2987 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002988 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002989 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002990 /* Find the first sub-pattern and at the same time
2991 * find the rest after the closing brace */
2992 next = next_brace_sub(begin);
2993 if (next == NULL) {
2994 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002995 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002996 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002997 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002998 /* "{abc}" with no commas - illegal
2999 * brace expr, disregard and skip it */
3000 begin = next + 1;
3001 continue;
3002 }
3003 break;
3004 }
3005 if (*begin == '\\' && begin[1] != '\0')
3006 begin++;
3007 begin++;
3008 }
3009 debug_printf_glob("begin:%s\n", begin);
3010 debug_printf_glob("next:%s\n", next);
3011
3012 /* Now find the end of the whole brace expression */
3013 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003014 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003015 rest = next_brace_sub(rest);
3016 if (rest == NULL) {
3017 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003018 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003019 }
3020 debug_printf_glob("rest:%s\n", rest);
3021 }
3022 rest_len = strlen(++rest) + 1;
3023
3024 /* We are sure the brace expression is well-formed */
3025
3026 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003027 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003028
3029 /* We have a brace expression. BEGIN points to the opening {,
3030 * NEXT points past the terminator of the first element, and REST
3031 * points past the final }. We will accumulate result names from
3032 * recursive runs for each brace alternative in the buffer using
3033 * GLOB_APPEND. */
3034
3035 p = begin + 1;
3036 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003037 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003038 memcpy(
3039 mempcpy(
3040 mempcpy(new_pattern_buf,
3041 /* We know the prefix for all sub-patterns */
3042 pattern, begin - pattern),
3043 p, next - p),
3044 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003045
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003046 /* Note: glob_brace() may garble new_pattern_buf[].
3047 * That's why we re-copy prefix every time (1st memcpy above).
3048 */
3049 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003050 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003051 /* We saw the last entry */
3052 break;
3053 }
3054 p = next + 1;
3055 next = next_brace_sub(next);
3056 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003057 free(new_pattern_buf);
3058 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003059
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003060 simple_glob:
3061 {
3062 int gr;
3063 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003064
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003065 memset(&globdata, 0, sizeof(globdata));
3066 gr = glob(pattern, 0, NULL, &globdata);
3067 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3068 if (gr != 0) {
3069 if (gr == GLOB_NOMATCH) {
3070 globfree(&globdata);
3071 /* NB: garbles parameter */
3072 unbackslash(pattern);
3073 o_addstr_with_NUL(o, pattern);
3074 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3075 return o_save_ptr_helper(o, n);
3076 }
3077 if (gr == GLOB_NOSPACE)
3078 bb_error_msg_and_die(bb_msg_memory_exhausted);
3079 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3080 * but we didn't specify it. Paranoia again. */
3081 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3082 }
3083 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3084 char **argv = globdata.gl_pathv;
3085 while (1) {
3086 o_addstr_with_NUL(o, *argv);
3087 n = o_save_ptr_helper(o, n);
3088 argv++;
3089 if (!*argv)
3090 break;
3091 }
3092 }
3093 globfree(&globdata);
3094 }
3095 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003096}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003097/* Performs globbing on last list[],
3098 * saving each result as a new list[].
3099 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003100static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003101{
3102 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003103
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003104 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003105 if (!o->data)
3106 return o_save_ptr_helper(o, n);
3107 pattern = o->data + o_get_last_ptr(o, n);
3108 debug_printf_glob("glob pattern '%s'\n", pattern);
3109 if (!glob_needed(pattern)) {
3110 /* unbackslash last string in o in place, fix length */
3111 o->length = unbackslash(pattern) - o->data;
3112 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3113 return o_save_ptr_helper(o, n);
3114 }
3115
3116 copy = xstrdup(pattern);
3117 /* "forget" pattern in o */
3118 o->length = pattern - o->data;
3119 n = glob_brace(copy, o, n);
3120 free(copy);
3121 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003122 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003123 return n;
3124}
3125
Denys Vlasenko238081f2010-10-03 14:26:26 +02003126#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003127
3128/* Helper */
3129static int glob_needed(const char *s)
3130{
3131 while (*s) {
3132 if (*s == '\\') {
3133 if (!s[1])
3134 return 0;
3135 s += 2;
3136 continue;
3137 }
3138 if (*s == '*' || *s == '[' || *s == '?')
3139 return 1;
3140 s++;
3141 }
3142 return 0;
3143}
3144/* Performs globbing on last list[],
3145 * saving each result as a new list[].
3146 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003147static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003148{
3149 glob_t globdata;
3150 int gr;
3151 char *pattern;
3152
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003153 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003154 if (!o->data)
3155 return o_save_ptr_helper(o, n);
3156 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003157 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003158 if (!glob_needed(pattern)) {
3159 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003160 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003161 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003162 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003163 return o_save_ptr_helper(o, n);
3164 }
3165
3166 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003167 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3168 * If we glob "*.\*" and don't find anything, we need
3169 * to fall back to using literal "*.*", but GLOB_NOCHECK
3170 * will return "*.\*"!
3171 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003172 gr = glob(pattern, 0, NULL, &globdata);
3173 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003174 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003175 if (gr == GLOB_NOMATCH) {
3176 globfree(&globdata);
3177 goto literal;
3178 }
3179 if (gr == GLOB_NOSPACE)
3180 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003181 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3182 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003183 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003184 }
3185 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3186 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003187 /* "forget" pattern in o */
3188 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003189 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003190 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003191 n = o_save_ptr_helper(o, n);
3192 argv++;
3193 if (!*argv)
3194 break;
3195 }
3196 }
3197 globfree(&globdata);
3198 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003199 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003200 return n;
3201}
3202
Denys Vlasenko238081f2010-10-03 14:26:26 +02003203#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003204
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003205/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003206 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003207static int o_save_ptr(o_string *o, int n)
3208{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003209 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003210 /* If o->has_empty_slot, list[n] was already globbed
3211 * (if it was requested back then when it was filled)
3212 * so don't do that again! */
3213 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003214 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003215 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003216 return o_save_ptr_helper(o, n);
3217}
3218
3219/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003220static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003221{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003222 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003223 int string_start;
3224
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003225 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3226 if (DEBUG_EXPAND)
3227 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003228 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003229 list = (char**)o->data;
3230 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3231 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003232 while (n) {
3233 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003234 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003235 }
3236 return list;
3237}
3238
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003239static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003240
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003241/* Returns pi->next - next pipe in the list */
3242static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003243{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003244 struct pipe *next;
3245 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003246
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003247 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003248 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003249 struct command *command;
3250 struct redir_struct *r, *rnext;
3251
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003252 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003253 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003254 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003255 if (DEBUG_CLEAN) {
3256 int a;
3257 char **p;
3258 for (a = 0, p = command->argv; *p; a++, p++) {
3259 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3260 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003261 }
3262 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003263 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003264 }
3265 /* not "else if": on syntax error, we may have both! */
3266 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003267 debug_printf_clean(" begin group (cmd_type:%d)\n",
3268 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003269 free_pipe_list(command->group);
3270 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003271 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003272 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003273 /* else is crucial here.
3274 * If group != NULL, child_func is meaningless */
3275#if ENABLE_HUSH_FUNCTIONS
3276 else if (command->child_func) {
3277 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3278 command->child_func->parent_cmd = NULL;
3279 }
3280#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003281#if !BB_MMU
3282 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003283 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003284#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003285 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003286 debug_printf_clean(" redirect %d%s",
3287 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003288 /* guard against the case >$FOO, where foo is unset or blank */
3289 if (r->rd_filename) {
3290 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3291 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003292 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003293 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003294 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003295 rnext = r->next;
3296 free(r);
3297 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003298 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003299 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003300 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003301 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003302#if ENABLE_HUSH_JOB
3303 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003304 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003305#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003306
3307 next = pi->next;
3308 free(pi);
3309 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003310}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003311
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003312static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003313{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003314 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003315#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003316 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003317#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003318 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003319 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003320 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003321}
3322
3323
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003324/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003325
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003326#ifndef debug_print_tree
3327static void debug_print_tree(struct pipe *pi, int lvl)
3328{
3329 static const char *const PIPE[] = {
3330 [PIPE_SEQ] = "SEQ",
3331 [PIPE_AND] = "AND",
3332 [PIPE_OR ] = "OR" ,
3333 [PIPE_BG ] = "BG" ,
3334 };
3335 static const char *RES[] = {
3336 [RES_NONE ] = "NONE" ,
3337# if ENABLE_HUSH_IF
3338 [RES_IF ] = "IF" ,
3339 [RES_THEN ] = "THEN" ,
3340 [RES_ELIF ] = "ELIF" ,
3341 [RES_ELSE ] = "ELSE" ,
3342 [RES_FI ] = "FI" ,
3343# endif
3344# if ENABLE_HUSH_LOOPS
3345 [RES_FOR ] = "FOR" ,
3346 [RES_WHILE] = "WHILE",
3347 [RES_UNTIL] = "UNTIL",
3348 [RES_DO ] = "DO" ,
3349 [RES_DONE ] = "DONE" ,
3350# endif
3351# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3352 [RES_IN ] = "IN" ,
3353# endif
3354# if ENABLE_HUSH_CASE
3355 [RES_CASE ] = "CASE" ,
3356 [RES_CASE_IN ] = "CASE_IN" ,
3357 [RES_MATCH] = "MATCH",
3358 [RES_CASE_BODY] = "CASE_BODY",
3359 [RES_ESAC ] = "ESAC" ,
3360# endif
3361 [RES_XXXX ] = "XXXX" ,
3362 [RES_SNTX ] = "SNTX" ,
3363 };
3364 static const char *const CMDTYPE[] = {
3365 "{}",
3366 "()",
3367 "[noglob]",
3368# if ENABLE_HUSH_FUNCTIONS
3369 "func()",
3370# endif
3371 };
3372
3373 int pin, prn;
3374
3375 pin = 0;
3376 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003377 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003378 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3379 prn = 0;
3380 while (prn < pi->num_cmds) {
3381 struct command *command = &pi->cmds[prn];
3382 char **argv = command->argv;
3383
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003384 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003385 lvl*2, "", prn,
3386 command->assignment_cnt);
3387 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003388 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003389 CMDTYPE[command->cmd_type],
3390 argv
3391# if !BB_MMU
3392 , " group_as_string:", command->group_as_string
3393# else
3394 , "", ""
3395# endif
3396 );
3397 debug_print_tree(command->group, lvl+1);
3398 prn++;
3399 continue;
3400 }
3401 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003402 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003403 argv++;
3404 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003405 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003406 prn++;
3407 }
3408 pi = pi->next;
3409 pin++;
3410 }
3411}
3412#endif /* debug_print_tree */
3413
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003414static struct pipe *new_pipe(void)
3415{
Eric Andersen25f27032001-04-26 23:22:31 +00003416 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003417 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003418 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003419 return pi;
3420}
3421
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003422/* Command (member of a pipe) is complete, or we start a new pipe
3423 * if ctx->command is NULL.
3424 * No errors possible here.
3425 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003426static int done_command(struct parse_context *ctx)
3427{
3428 /* The command is really already in the pipe structure, so
3429 * advance the pipe counter and make a new, null command. */
3430 struct pipe *pi = ctx->pipe;
3431 struct command *command = ctx->command;
3432
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003433#if 0 /* Instead we emit error message at run time */
3434 if (ctx->pending_redirect) {
3435 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003436 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003437 ctx->pending_redirect = NULL;
3438 }
3439#endif
3440
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003441 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003442 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003443 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003444 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003445 }
3446 pi->num_cmds++;
3447 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003448 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003449 } else {
3450 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3451 }
3452
3453 /* Only real trickiness here is that the uncommitted
3454 * command structure is not counted in pi->num_cmds. */
3455 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003456 ctx->command = command = &pi->cmds[pi->num_cmds];
3457 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003458 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003459 return pi->num_cmds; /* used only for 0/nonzero check */
3460}
3461
3462static void done_pipe(struct parse_context *ctx, pipe_style type)
3463{
3464 int not_null;
3465
3466 debug_printf_parse("done_pipe entered, followup %d\n", type);
3467 /* Close previous command */
3468 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003469#if HAS_KEYWORDS
3470 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3471 ctx->ctx_inverted = 0;
3472 ctx->pipe->res_word = ctx->ctx_res_w;
3473#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003474 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3475 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003476 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3477 * in a backgrounded subshell.
3478 */
3479 struct pipe *pi;
3480 struct command *command;
3481
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003482 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003483 pi = ctx->list_head;
3484 while (pi != ctx->pipe) {
3485 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3486 goto no_conv;
3487 pi = pi->next;
3488 }
3489
3490 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3491 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3492 pi = xzalloc(sizeof(*pi));
3493 pi->followup = PIPE_BG;
3494 pi->num_cmds = 1;
3495 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3496 command = &pi->cmds[0];
3497 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3498 command->cmd_type = CMD_NORMAL;
3499 command->group = ctx->list_head;
3500#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003501 command->group_as_string = xstrndup(
3502 ctx->as_string.data,
3503 ctx->as_string.length - 1 /* do not copy last char, "&" */
3504 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003505#endif
3506 /* Replace all pipes in ctx with one newly created */
3507 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003508 } else {
3509 no_conv:
3510 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003511 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003512
3513 /* Without this check, even just <enter> on command line generates
3514 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003515 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003516 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003517#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003518 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003519#endif
3520#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003521 || ctx->ctx_res_w == RES_DONE
3522 || ctx->ctx_res_w == RES_FOR
3523 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003524#endif
3525#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003526 || ctx->ctx_res_w == RES_ESAC
3527#endif
3528 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003529 struct pipe *new_p;
3530 debug_printf_parse("done_pipe: adding new pipe: "
3531 "not_null:%d ctx->ctx_res_w:%d\n",
3532 not_null, ctx->ctx_res_w);
3533 new_p = new_pipe();
3534 ctx->pipe->next = new_p;
3535 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003536 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003537 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003538 * This is used to control execution.
3539 * RES_FOR and RES_IN are NOT sticky (needed to support
3540 * cases where variable or value happens to match a keyword):
3541 */
3542#if ENABLE_HUSH_LOOPS
3543 if (ctx->ctx_res_w == RES_FOR
3544 || ctx->ctx_res_w == RES_IN)
3545 ctx->ctx_res_w = RES_NONE;
3546#endif
3547#if ENABLE_HUSH_CASE
3548 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003549 ctx->ctx_res_w = RES_CASE_BODY;
3550 if (ctx->ctx_res_w == RES_CASE)
3551 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003552#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003553 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003554 /* Create the memory for command, roughly:
3555 * ctx->pipe->cmds = new struct command;
3556 * ctx->command = &ctx->pipe->cmds[0];
3557 */
3558 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003559 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003560 }
3561 debug_printf_parse("done_pipe return\n");
3562}
3563
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003564static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003565{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003566 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003567 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003568 /* Create the memory for command, roughly:
3569 * ctx->pipe->cmds = new struct command;
3570 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003571 */
3572 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003573}
3574
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003575/* If a reserved word is found and processed, parse context is modified
3576 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003577 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003578#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003579struct reserved_combo {
3580 char literal[6];
3581 unsigned char res;
3582 unsigned char assignment_flag;
3583 int flag;
3584};
3585enum {
3586 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003587# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003588 FLAG_IF = (1 << RES_IF ),
3589 FLAG_THEN = (1 << RES_THEN ),
3590 FLAG_ELIF = (1 << RES_ELIF ),
3591 FLAG_ELSE = (1 << RES_ELSE ),
3592 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003593# endif
3594# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003595 FLAG_FOR = (1 << RES_FOR ),
3596 FLAG_WHILE = (1 << RES_WHILE),
3597 FLAG_UNTIL = (1 << RES_UNTIL),
3598 FLAG_DO = (1 << RES_DO ),
3599 FLAG_DONE = (1 << RES_DONE ),
3600 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003601# endif
3602# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003603 FLAG_MATCH = (1 << RES_MATCH),
3604 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003605# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003606 FLAG_START = (1 << RES_XXXX ),
3607};
3608
3609static const struct reserved_combo* match_reserved_word(o_string *word)
3610{
Eric Andersen25f27032001-04-26 23:22:31 +00003611 /* Mostly a list of accepted follow-up reserved words.
3612 * FLAG_END means we are done with the sequence, and are ready
3613 * to turn the compound list into a command.
3614 * FLAG_START means the word must start a new compound list.
3615 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003616 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003617# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003618 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3619 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3620 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3621 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3622 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3623 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003624# endif
3625# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003626 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3627 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3628 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3629 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3630 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3631 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003632# endif
3633# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003634 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3635 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003636# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003637 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003638 const struct reserved_combo *r;
3639
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003640 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003641 if (strcmp(word->data, r->literal) == 0)
3642 return r;
3643 }
3644 return NULL;
3645}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003646/* Return 0: not a keyword, 1: keyword
3647 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003648static int reserved_word(o_string *word, struct parse_context *ctx)
3649{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003650# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003651 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003652 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003653 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003654# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003655 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003656
Denys Vlasenko38292b62010-09-05 14:49:40 +02003657 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003658 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003659 r = match_reserved_word(word);
3660 if (!r)
3661 return 0;
3662
3663 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003664# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003665 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3666 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003667 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003668 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003669# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003670 if (r->flag == 0) { /* '!' */
3671 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003672 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003673 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003674 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003675 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003676 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003677 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003678 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003679 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003680
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003681 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003682 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003683 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003684 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003685 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003686 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003687 ctx->ctx_res_w = RES_SNTX;
3688 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003689 } else {
3690 /* "{...} fi" is ok. "{...} if" is not
3691 * Example:
3692 * if { echo foo; } then { echo bar; } fi */
3693 if (ctx->command->group)
3694 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003695 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003696
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003697 ctx->ctx_res_w = r->res;
3698 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003699 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003700 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003701
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003702 if (ctx->old_flag & FLAG_END) {
3703 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003704
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003705 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003706 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003707 old = ctx->stack;
3708 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003709 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003710# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003711 /* At this point, the compound command's string is in
3712 * ctx->as_string... except for the leading keyword!
3713 * Consider this example: "echo a | if true; then echo a; fi"
3714 * ctx->as_string will contain "true; then echo a; fi",
3715 * with "if " remaining in old->as_string!
3716 */
3717 {
3718 char *str;
3719 int len = old->as_string.length;
3720 /* Concatenate halves */
3721 o_addstr(&old->as_string, ctx->as_string.data);
3722 o_free_unsafe(&ctx->as_string);
3723 /* Find where leading keyword starts in first half */
3724 str = old->as_string.data + len;
3725 if (str > old->as_string.data)
3726 str--; /* skip whitespace after keyword */
3727 while (str > old->as_string.data && isalpha(str[-1]))
3728 str--;
3729 /* Ugh, we're done with this horrid hack */
3730 old->command->group_as_string = xstrdup(str);
3731 debug_printf_parse("pop, remembering as:'%s'\n",
3732 old->command->group_as_string);
3733 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003734# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003735 *ctx = *old; /* physical copy */
3736 free(old);
3737 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003738 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003739}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003740#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003741
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003742/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003743 * Normal return is 0. Syntax errors return 1.
3744 * Note: on return, word is reset, but not o_free'd!
3745 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003746static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003747{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003748 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003749
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003750 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003751 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003752 debug_printf_parse("done_word return 0: true null, ignored\n");
3753 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003754 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003755
Eric Andersen25f27032001-04-26 23:22:31 +00003756 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003757 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3758 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003759 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3760 * "2.7 Redirection
3761 * ...the word that follows the redirection operator
3762 * shall be subjected to tilde expansion, parameter expansion,
3763 * command substitution, arithmetic expansion, and quote
3764 * removal. Pathname expansion shall not be performed
3765 * on the word by a non-interactive shell; an interactive
3766 * shell may perform it, but shall do so only when
3767 * the expansion would result in one word."
3768 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003769 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003770 /* Cater for >\file case:
3771 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3772 * Same with heredocs:
3773 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3774 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003775 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3776 unbackslash(ctx->pending_redirect->rd_filename);
3777 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003778 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003779 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3780 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003781 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003782 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003783 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003784 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003785#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003786# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003787 if (ctx->ctx_dsemicolon
3788 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3789 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003790 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003791 /* ctx->ctx_res_w = RES_MATCH; */
3792 ctx->ctx_dsemicolon = 0;
3793 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003794# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003795 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003796# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003797 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3798 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003799# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003800# if ENABLE_HUSH_CASE
3801 && ctx->ctx_res_w != RES_CASE
3802# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003803 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003804 int reserved = reserved_word(word, ctx);
3805 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3806 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003807 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003808 debug_printf_parse("done_word return %d\n",
3809 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003810 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003811 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01003812# if BASH_TEST2
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003813 if (strcmp(word->data, "[[") == 0) {
3814 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3815 }
3816 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003817# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003818 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003819#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003820 if (command->group) {
3821 /* "{ echo foo; } echo bar" - bad */
3822 syntax_error_at(word->data);
3823 debug_printf_parse("done_word return 1: syntax error, "
3824 "groups and arglists don't mix\n");
3825 return 1;
3826 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003827
3828 /* If this word wasn't an assignment, next ones definitely
3829 * can't be assignments. Even if they look like ones. */
3830 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3831 && word->o_assignment != WORD_IS_KEYWORD
3832 ) {
3833 word->o_assignment = NOT_ASSIGNMENT;
3834 } else {
3835 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3836 command->assignment_cnt++;
3837 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3838 }
3839 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3840 word->o_assignment = MAYBE_ASSIGNMENT;
3841 }
3842 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3843
Denys Vlasenko38292b62010-09-05 14:49:40 +02003844 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003845 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3846 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003847 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003848 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003849 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003850 char *p = word->data;
3851 while (p[0] == SPECIAL_VAR_SYMBOL
3852 && (p[1] & 0x7f) == '@'
3853 && p[2] == SPECIAL_VAR_SYMBOL
3854 ) {
3855 p += 3;
3856 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003857 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003858 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003859 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003860 }
Eric Andersen25f27032001-04-26 23:22:31 +00003861
Denis Vlasenko06810332007-05-21 23:30:54 +00003862#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003863 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003864 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003865 || !is_well_formed_var_name(command->argv[0], '\0')
3866 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003867 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003868 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003869 return 1;
3870 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003871 /* Force FOR to have just one word (variable name) */
3872 /* NB: basically, this makes hush see "for v in ..."
3873 * syntax as if it is "for v; in ...". FOR and IN become
3874 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003875 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003876 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003877#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003878#if ENABLE_HUSH_CASE
3879 /* Force CASE to have just one word */
3880 if (ctx->ctx_res_w == RES_CASE) {
3881 done_pipe(ctx, PIPE_SEQ);
3882 }
3883#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003884
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003885 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003886
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003887 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003888 return 0;
3889}
3890
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003891
3892/* Peek ahead in the input to find out if we have a "&n" construct,
3893 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003894 * Return:
3895 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3896 * REDIRFD_SYNTAX_ERR if syntax error,
3897 * REDIRFD_TO_FILE if no & was seen,
3898 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003899 */
3900#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003901#define parse_redir_right_fd(as_string, input) \
3902 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003903#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003904static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003905{
3906 int ch, d, ok;
3907
3908 ch = i_peek(input);
3909 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003910 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003911
3912 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003913 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003914 ch = i_peek(input);
3915 if (ch == '-') {
3916 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003917 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003918 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003919 }
3920 d = 0;
3921 ok = 0;
3922 while (ch != EOF && isdigit(ch)) {
3923 d = d*10 + (ch-'0');
3924 ok = 1;
3925 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003926 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003927 ch = i_peek(input);
3928 }
3929 if (ok) return d;
3930
3931//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3932
3933 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003934 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003935}
3936
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003937/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003938 */
3939static int parse_redirect(struct parse_context *ctx,
3940 int fd,
3941 redir_type style,
3942 struct in_str *input)
3943{
3944 struct command *command = ctx->command;
3945 struct redir_struct *redir;
3946 struct redir_struct **redirp;
3947 int dup_num;
3948
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003949 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003950 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003951 /* Check for a '>&1' type redirect */
3952 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3953 if (dup_num == REDIRFD_SYNTAX_ERR)
3954 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003955 } else {
3956 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003957 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003958 if (dup_num) { /* <<-... */
3959 ch = i_getch(input);
3960 nommu_addchr(&ctx->as_string, ch);
3961 ch = i_peek(input);
3962 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003963 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003964
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003965 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003966 int ch = i_peek(input);
3967 if (ch == '|') {
3968 /* >|FILE redirect ("clobbering" >).
3969 * Since we do not support "set -o noclobber" yet,
3970 * >| and > are the same for now. Just eat |.
3971 */
3972 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003973 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003974 }
3975 }
3976
3977 /* Create a new redir_struct and append it to the linked list */
3978 redirp = &command->redirects;
3979 while ((redir = *redirp) != NULL) {
3980 redirp = &(redir->next);
3981 }
3982 *redirp = redir = xzalloc(sizeof(*redir));
3983 /* redir->next = NULL; */
3984 /* redir->rd_filename = NULL; */
3985 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003986 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003987
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003988 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3989 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003990
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003991 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003992 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003993 /* Erik had a check here that the file descriptor in question
3994 * is legit; I postpone that to "run time"
3995 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003996 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3997 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003998 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003999#if 0 /* Instead we emit error message at run time */
4000 if (ctx->pending_redirect) {
4001 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004002 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004003 }
4004#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004005 /* Set ctx->pending_redirect, so we know what to do at the
4006 * end of the next parsed word. */
4007 ctx->pending_redirect = redir;
4008 }
4009 return 0;
4010}
4011
Eric Andersen25f27032001-04-26 23:22:31 +00004012/* If a redirect is immediately preceded by a number, that number is
4013 * supposed to tell which file descriptor to redirect. This routine
4014 * looks for such preceding numbers. In an ideal world this routine
4015 * needs to handle all the following classes of redirects...
4016 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4017 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4018 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4019 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004020 *
4021 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4022 * "2.7 Redirection
4023 * ... If n is quoted, the number shall not be recognized as part of
4024 * the redirection expression. For example:
4025 * echo \2>a
4026 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004027 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004028 *
4029 * A -1 return means no valid number was found,
4030 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004031 */
4032static int redirect_opt_num(o_string *o)
4033{
4034 int num;
4035
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004036 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004037 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004038 num = bb_strtou(o->data, NULL, 10);
4039 if (errno || num < 0)
4040 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004041 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004042 return num;
4043}
4044
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004045#if BB_MMU
4046#define fetch_till_str(as_string, input, word, skip_tabs) \
4047 fetch_till_str(input, word, skip_tabs)
4048#endif
4049static char *fetch_till_str(o_string *as_string,
4050 struct in_str *input,
4051 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004052 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004053{
4054 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004055 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004056 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004057 int ch;
4058
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004059 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004060
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004061 while (1) {
4062 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004063 if (ch != EOF)
4064 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004065 if (ch == '\n' || ch == EOF) {
4066 check_heredoc_end:
4067 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4068 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4069 heredoc.data[past_EOL] = '\0';
4070 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4071 return heredoc.data;
4072 }
4073 if (ch == '\n') {
4074 /* This is a new line.
4075 * Remember position and backslash-escaping status.
4076 */
4077 o_addchr(&heredoc, ch);
4078 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004079 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004080 past_EOL = heredoc.length;
4081 /* Get 1st char of next line, possibly skipping leading tabs */
4082 do {
4083 ch = i_getch(input);
4084 if (ch != EOF)
4085 nommu_addchr(as_string, ch);
4086 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4087 /* If this immediately ended the line,
4088 * go back to end-of-line checks.
4089 */
4090 if (ch == '\n')
4091 goto check_heredoc_end;
4092 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004093 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004094 }
4095 if (ch == EOF) {
4096 o_free_unsafe(&heredoc);
4097 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004098 }
4099 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004100 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004101 if (prev == '\\' && ch == '\\')
4102 /* Correctly handle foo\\<eol> (not a line cont.) */
4103 prev = 0; /* not \ */
4104 else
4105 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004106 }
4107}
4108
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004109/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4110 * and load them all. There should be exactly heredoc_cnt of them.
4111 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004112static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4113{
4114 struct pipe *pi = ctx->list_head;
4115
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004116 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004117 int i;
4118 struct command *cmd = pi->cmds;
4119
4120 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4121 pi->num_cmds,
4122 cmd->argv ? cmd->argv[0] : "NONE");
4123 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004124 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004125
4126 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4127 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004128 while (redir) {
4129 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004130 char *p;
4131
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004132 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004133 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004134 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004135 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004136 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004137 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004138 return 1;
4139 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004140 free(redir->rd_filename);
4141 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004142 heredoc_cnt--;
4143 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004144 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004145 }
4146 cmd++;
4147 }
4148 pi = pi->next;
4149 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004150#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004151 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004152 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004153 bb_error_msg_and_die("heredoc BUG 2");
4154#endif
4155 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004156}
4157
4158
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004159static int run_list(struct pipe *pi);
4160#if BB_MMU
4161#define parse_stream(pstring, input, end_trigger) \
4162 parse_stream(input, end_trigger)
4163#endif
4164static struct pipe *parse_stream(char **pstring,
4165 struct in_str *input,
4166 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004167
Eric Andersen25f27032001-04-26 23:22:31 +00004168
Denys Vlasenkoc2704542009-11-20 19:14:19 +01004169#if !ENABLE_HUSH_FUNCTIONS
4170#define parse_group(dest, ctx, input, ch) \
4171 parse_group(ctx, input, ch)
4172#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004173static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004174 struct in_str *input, int ch)
4175{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004176 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004177 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004178 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004179 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004180 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004181 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004182
4183 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004184#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02004185 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004186 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004187 if (done_word(dest, ctx))
4188 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004189 if (!command->argv)
4190 goto skip; /* (... */
4191 if (command->argv[1]) { /* word word ... (... */
4192 syntax_error_unexpected_ch('(');
4193 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004194 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004195 /* it is "word(..." or "word (..." */
4196 do
4197 ch = i_getch(input);
4198 while (ch == ' ' || ch == '\t');
4199 if (ch != ')') {
4200 syntax_error_unexpected_ch(ch);
4201 return 1;
4202 }
4203 nommu_addchr(&ctx->as_string, ch);
4204 do
4205 ch = i_getch(input);
4206 while (ch == ' ' || ch == '\t' || ch == '\n');
4207 if (ch != '{') {
4208 syntax_error_unexpected_ch(ch);
4209 return 1;
4210 }
4211 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004212 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004213 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004214 }
4215#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004216
4217#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004218 if (command->argv /* word [word]{... */
4219 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004220 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004221 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004222 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004223 debug_printf_parse("parse_group return 1: "
4224 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004225 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004226 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004227#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004228
4229#if ENABLE_HUSH_FUNCTIONS
4230 skip:
4231#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004232 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004233 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004234 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004235 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004236 } else {
4237 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004238 ch = i_peek(input);
4239 if (ch != ' ' && ch != '\t' && ch != '\n'
4240 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4241 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004242 syntax_error_unexpected_ch(ch);
4243 return 1;
4244 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004245 if (ch != '(') {
4246 ch = i_getch(input);
4247 nommu_addchr(&ctx->as_string, ch);
4248 }
Eric Andersen25f27032001-04-26 23:22:31 +00004249 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004250
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004251 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004252#if BB_MMU
4253# define as_string NULL
4254#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004255 char *as_string = NULL;
4256#endif
4257 pipe_list = parse_stream(&as_string, input, endch);
4258#if !BB_MMU
4259 if (as_string)
4260 o_addstr(&ctx->as_string, as_string);
4261#endif
4262 /* empty ()/{} or parse error? */
4263 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00004264 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004265 if (!BB_MMU)
4266 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004267 debug_printf_parse("parse_group return 1: "
4268 "parse_stream returned %p\n", pipe_list);
4269 return 1;
4270 }
4271 command->group = pipe_list;
4272#if !BB_MMU
4273 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4274 command->group_as_string = as_string;
4275 debug_printf_parse("end of group, remembering as:'%s'\n",
4276 command->group_as_string);
4277#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004278#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004279 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004280 debug_printf_parse("parse_group return 0\n");
4281 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004282 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004283}
4284
Denys Vlasenko46e64982016-09-29 19:50:55 +02004285static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4286{
4287 for (;;) {
4288 int ch, ch2;
4289
4290 ch = i_getch(input);
4291 if (ch != '\\')
4292 return ch;
4293 ch2 = i_peek(input);
4294 if (ch2 != '\n')
4295 return ch;
4296 /* backslash+newline, skip it */
4297 i_getch(input);
4298 }
4299}
4300
Denys Vlasenko657086a2016-09-29 18:07:42 +02004301static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4302{
4303 for (;;) {
4304 int ch, ch2;
4305
4306 ch = i_peek(input);
4307 if (ch != '\\')
4308 return ch;
4309 ch2 = i_peek2(input);
4310 if (ch2 != '\n')
4311 return ch;
4312 /* backslash+newline, skip it */
4313 i_getch(input);
4314 i_getch(input);
4315 }
4316}
4317
Denys Vlasenko0b883582016-12-23 16:49:07 +01004318#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004319/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004320static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004321/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004322static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004323{
4324 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004325 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004326 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004327 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004328 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004329 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004330 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004331 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004332 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004333 }
4334}
4335/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004336static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004337{
4338 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004339 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004340 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004341 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004342 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004343 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004344 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004345 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004346 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004347 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004348 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004349 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004350 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004351 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004352 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4353 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004354 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004355 continue;
4356 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004357 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004358 }
4359}
4360/* Process `cmd` - copy contents until "`" is seen. Complicated by
4361 * \` quoting.
4362 * "Within the backquoted style of command substitution, backslash
4363 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4364 * The search for the matching backquote shall be satisfied by the first
4365 * backquote found without a preceding backslash; during this search,
4366 * if a non-escaped backquote is encountered within a shell comment,
4367 * a here-document, an embedded command substitution of the $(command)
4368 * form, or a quoted string, undefined results occur. A single-quoted
4369 * or double-quoted string that begins, but does not end, within the
4370 * "`...`" sequence produces undefined results."
4371 * Example Output
4372 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4373 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004374static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004375{
4376 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004377 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004378 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004379 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004380 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004381 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4382 ch = i_getch(input);
4383 if (ch != '`'
4384 && ch != '$'
4385 && ch != '\\'
4386 && (!in_dquote || ch != '"')
4387 ) {
4388 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004389 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004390 }
4391 if (ch == EOF) {
4392 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004393 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004394 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004395 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004396 }
4397}
4398/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4399 * quoting and nested ()s.
4400 * "With the $(command) style of command substitution, all characters
4401 * following the open parenthesis to the matching closing parenthesis
4402 * constitute the command. Any valid shell script can be used for command,
4403 * except a script consisting solely of redirections which produces
4404 * unspecified results."
4405 * Example Output
4406 * echo $(echo '(TEST)' BEST) (TEST) BEST
4407 * echo $(echo 'TEST)' BEST) TEST) BEST
4408 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004409 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004410 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004411 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004412 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4413 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004414 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004415#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004416static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004417{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004418 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004419 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004420# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004421 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004422# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004423 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4424
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004425 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004426 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004427 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004428 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004429 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004430 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004431 if (ch == end_ch
4432# if BASH_SUBSTR || BASH_PATTERN_SUBST
4433 || ch == end_char2
4434# endif
4435 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004436 if (!dbl)
4437 break;
4438 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004439 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004440 i_getch(input); /* eat second ')' */
4441 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004442 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004443 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004444 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004445 if (ch == '(' || ch == '{') {
4446 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004447 if (!add_till_closing_bracket(dest, input, ch))
4448 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004449 o_addchr(dest, ch);
4450 continue;
4451 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004452 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004453 if (!add_till_single_quote(dest, input))
4454 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004455 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004456 continue;
4457 }
4458 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004459 if (!add_till_double_quote(dest, input))
4460 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004461 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004462 continue;
4463 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004464 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004465 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4466 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004467 o_addchr(dest, ch);
4468 continue;
4469 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004470 if (ch == '\\') {
4471 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004472 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004473 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004474 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004475 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004476 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004477#if 0
4478 if (ch == '\n') {
4479 /* "backslash+newline", ignore both */
4480 o_delchr(dest); /* undo insertion of '\' */
4481 continue;
4482 }
4483#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004484 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004485 continue;
4486 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004487 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004488 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004489}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004490#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004491
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004492/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004493#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004494#define parse_dollar(as_string, dest, input, quote_mask) \
4495 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004496#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004497#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004498static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004499 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004500 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004501{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004502 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004503
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004504 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004505 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004506 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004507 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004508 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004509 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004510 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004511 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004512 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004513 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004514 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004515 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004516 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004517 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004518 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004519 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004520 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004521 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004522 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004523 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004524 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004525 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004526 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004527 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004528 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004529 o_addchr(dest, ch | quote_mask);
4530 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004531 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004532 case '$': /* pid */
4533 case '!': /* last bg pid */
4534 case '?': /* last exit code */
4535 case '#': /* number of args */
4536 case '*': /* args */
4537 case '@': /* args */
4538 goto make_one_char_var;
4539 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004540 char len_single_ch;
4541
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004542 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4543
Denys Vlasenko74369502010-05-21 19:52:01 +02004544 ch = i_getch(input); /* eat '{' */
4545 nommu_addchr(as_string, ch);
4546
Denys Vlasenko46e64982016-09-29 19:50:55 +02004547 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004548 /* It should be ${?}, or ${#var},
4549 * or even ${?+subst} - operator acting on a special variable,
4550 * or the beginning of variable name.
4551 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004552 if (ch == EOF
4553 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4554 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004555 bad_dollar_syntax:
4556 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004557 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4558 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004559 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004560 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004561 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004562 ch |= quote_mask;
4563
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004564 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004565 * However, this regresses some of our testsuite cases
4566 * which check invalid constructs like ${%}.
4567 * Oh well... let's check that the var name part is fine... */
4568
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004569 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004570 unsigned pos;
4571
Denys Vlasenko74369502010-05-21 19:52:01 +02004572 o_addchr(dest, ch);
4573 debug_printf_parse(": '%c'\n", ch);
4574
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004575 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004576 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004577 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004578 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004579
Denys Vlasenko74369502010-05-21 19:52:01 +02004580 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004581 unsigned end_ch;
4582 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004583 /* handle parameter expansions
4584 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4585 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004586 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4587 if (len_single_ch != '#'
4588 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4589 || i_peek(input) != '}'
4590 ) {
4591 goto bad_dollar_syntax;
4592 }
4593 /* else: it's "length of C" ${#C} op,
4594 * where C is a single char
4595 * special var name, e.g. ${#!}.
4596 */
4597 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004598 /* Eat everything until closing '}' (or ':') */
4599 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004600 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004601 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004602 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004603 ) {
4604 /* It's ${var:N[:M]} thing */
4605 end_ch = '}' * 0x100 + ':';
4606 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004607 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004608 && ch == '/'
4609 ) {
4610 /* It's ${var/[/]pattern[/repl]} thing */
4611 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4612 i_getch(input);
4613 nommu_addchr(as_string, '/');
4614 ch = '\\';
4615 }
4616 end_ch = '}' * 0x100 + '/';
4617 }
4618 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004619 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004620 if (!BB_MMU)
4621 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004622#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004623 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004624 if (last_ch == 0) /* error? */
4625 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004626#else
4627#error Simple code to only allow ${var} is not implemented
4628#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004629 if (as_string) {
4630 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004631 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004632 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004633
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004634 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4635 && (end_ch & 0xff00)
4636 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004637 /* close the first block: */
4638 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004639 /* while parsing N from ${var:N[:M]}
4640 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004641 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004642 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004643 end_ch = '}';
4644 goto again;
4645 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004646 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004647 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004648 /* it's ${var:N} - emulate :999999999 */
4649 o_addstr(dest, "999999999");
4650 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004651 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004652 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004653 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004654 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004655 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004656 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4657 break;
4658 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004659#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004660 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004661 unsigned pos;
4662
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004663 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004664 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004665# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004666 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004667 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004668 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004669 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4670 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004671 if (!BB_MMU)
4672 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004673 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4674 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004675 if (as_string) {
4676 o_addstr(as_string, dest->data + pos);
4677 o_addchr(as_string, ')');
4678 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004679 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004680 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004681 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004682 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004683# endif
4684# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004685 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4686 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004687 if (!BB_MMU)
4688 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004689 if (!add_till_closing_bracket(dest, input, ')'))
4690 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004691 if (as_string) {
4692 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004693 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004694 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004695 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004696# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004697 break;
4698 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004699#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004700 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004701 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004702 nommu_addchr(as_string, ch);
Denys Vlasenko657086a2016-09-29 18:07:42 +02004703 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004704 if (isalnum(ch)) { /* it's $_name or $_123 */
4705 ch = '_';
4706 goto make_var;
4707 }
4708 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004709 /* TODO: $_ and $-: */
4710 /* $_ Shell or shell script name; or last argument of last command
4711 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4712 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004713 /* $- Option flags set by set builtin or shell options (-i etc) */
4714 default:
4715 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004716 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004717 debug_printf_parse("parse_dollar return 1 (ok)\n");
4718 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004719#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004720}
4721
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004722#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004723# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004724#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4725 encode_string(dest, input, dquote_end, process_bkslash)
4726# else
4727/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4728#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4729 encode_string(dest, input, dquote_end)
4730# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004731#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004732
4733#else /* !MMU */
4734
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004735# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004736/* all parameters are needed, no macro tricks */
4737# else
4738#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4739 encode_string(as_string, dest, input, dquote_end)
4740# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004741#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004742static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004743 o_string *dest,
4744 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004745 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004746 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004747{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004748#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004749 const int process_bkslash = 1;
4750#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004751 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004752 int next;
4753
4754 again:
4755 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004756 if (ch != EOF)
4757 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004758 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004759 debug_printf_parse("encode_string return 1 (ok)\n");
4760 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004761 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004762 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004763 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004764 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004765 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004766 }
4767 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004768 if (ch != '\n') {
4769 next = i_peek(input);
4770 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004771 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004772 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004773 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004774 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004775 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004776 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004777 }
4778 /* bash:
4779 * "The backslash retains its special meaning [in "..."]
4780 * only when followed by one of the following characters:
4781 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004782 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004783 * NB: in (unquoted) heredoc, above does not apply to ",
4784 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004785 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004786 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004787 ch = i_getch(input); /* eat next */
4788 if (ch == '\n')
4789 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004790 } /* else: ch remains == '\\', and we double it below: */
4791 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004792 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004793 goto again;
4794 }
4795 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004796 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4797 debug_printf_parse("encode_string return 0: "
4798 "parse_dollar returned 0 (error)\n");
4799 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004800 }
4801 goto again;
4802 }
4803#if ENABLE_HUSH_TICK
4804 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004805 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004806 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4807 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004808 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4809 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004810 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4811 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004812 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004813 }
4814#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004815 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004816 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004817#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004818}
4819
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004820/*
4821 * Scan input until EOF or end_trigger char.
4822 * Return a list of pipes to execute, or NULL on EOF
4823 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004824 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004825 * reset parsing machinery and start parsing anew,
4826 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004827 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004828static struct pipe *parse_stream(char **pstring,
4829 struct in_str *input,
4830 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004831{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004832 struct parse_context ctx;
4833 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004834 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004835
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004836 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004837 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004838 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004839 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004840 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004841 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004842
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004843 /* If very first arg is "" or '', dest.data may end up NULL.
4844 * Preventing this: */
4845 o_addchr(&dest, '\0');
4846 dest.length = 0;
4847
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004848 /* We used to separate words on $IFS here. This was wrong.
4849 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004850 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004851 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004852
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004853 if (MAYBE_ASSIGNMENT != 0)
4854 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004855 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004856 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004857 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004858 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004859 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004860 int ch;
4861 int next;
4862 int redir_fd;
4863 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004864
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004865 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004866 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004867 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004868 if (ch == EOF) {
4869 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004870
4871 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004872 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004873 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004874 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004875 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004876 syntax_error_unterm_ch('(');
4877 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004878 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004879 if (end_trigger == '}') {
4880 syntax_error_unterm_ch('{');
4881 goto parse_error;
4882 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004883
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004884 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004885 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004886 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004887 o_free(&dest);
4888 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004889 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004890 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004891 /* (this makes bare "&" cmd a no-op.
4892 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004893 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004894 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004895 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004896 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004897 pi = NULL;
4898 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004899#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004900 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004901 if (pstring)
4902 *pstring = ctx.as_string.data;
4903 else
4904 o_free_unsafe(&ctx.as_string);
4905#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004906 debug_leave();
4907 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004908 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004909 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004910 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004911
4912 next = '\0';
4913 if (ch != '\n')
4914 next = i_peek(input);
4915
4916 is_special = "{}<>;&|()#'" /* special outside of "str" */
4917 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4918 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004919 if (ctx.command->argv /* word [word]{... - non-special */
4920 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004921 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004922 || (next != ';' /* }; - special */
4923 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004924 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004925 && next != '&' /* }& and }&& ... - special */
4926 && next != '|' /* }|| ... - special */
4927 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004928 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004929 ) {
4930 /* They are not special, skip "{}" */
4931 is_special += 2;
4932 }
4933 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004934 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004935
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004936 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004937 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004938 o_addQchr(&dest, ch);
4939 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4940 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004941 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004942 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004943 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004944 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004945 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004946 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004947 continue;
4948 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004949
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004950 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004951 if (done_word(&dest, &ctx)) {
4952 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004953 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004954 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004955 /* Is this a case when newline is simply ignored?
4956 * Some examples:
4957 * "cmd | <newline> cmd ..."
4958 * "case ... in <newline> word) ..."
4959 */
4960 if (IS_NULL_CMD(ctx.command)
4961 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004962 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004963 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004964 * Without check #1, interactive shell
4965 * ignores even bare <newline>,
4966 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004967 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004968 * ps2> _ <=== wrong, should be ps1
4969 * Without check #2, "cmd & <newline>"
4970 * is similarly mistreated.
4971 * (BTW, this makes "cmd & cmd"
4972 * and "cmd && cmd" non-orthogonal.
4973 * Really, ask yourself, why
4974 * "cmd && <newline>" doesn't start
4975 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02004976 * The only reason is that it might be
4977 * a "cmd1 && <nl> cmd2 &" construct,
4978 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004979 */
4980 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004981 if (pi->num_cmds != 0 /* check #1 */
4982 && pi->followup != PIPE_BG /* check #2 */
4983 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004984 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004985 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004986 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004987 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004988 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004989 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4990 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004991 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004992 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004993 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004994 heredoc_cnt = 0;
4995 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004996 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004997 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004998 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004999 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005000 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005001 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005002 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005003
5004 /* "cmd}" or "cmd }..." without semicolon or &:
5005 * } is an ordinary char in this case, even inside { cmd; }
5006 * Pathological example: { ""}; } should exec "}" cmd
5007 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005008 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005009 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005010 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005011 ) {
5012 goto ordinary_char;
5013 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005014 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5015 /* Generally, there should be semicolon: "cmd; }"
5016 * However, bash allows to omit it if "cmd" is
5017 * a group. Examples:
5018 * { { echo 1; } }
5019 * {(echo 1)}
5020 * { echo 0 >&2 | { echo 1; } }
5021 * { while false; do :; done }
5022 * { case a in b) ;; esac }
5023 */
5024 if (ctx.command->group)
5025 goto term_group;
5026 goto ordinary_char;
5027 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005028 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005029 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005030 goto skip_end_trigger;
5031 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005032 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005033 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005034 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005035 && (ch != ';' || heredoc_cnt == 0)
5036#if ENABLE_HUSH_CASE
5037 && (ch != ')'
5038 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02005039 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005040 )
5041#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005042 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005043 if (heredoc_cnt) {
5044 /* This is technically valid:
5045 * { cat <<HERE; }; echo Ok
5046 * heredoc
5047 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005048 * HERE
5049 * but we don't support this.
5050 * We require heredoc to be in enclosing {}/(),
5051 * if any.
5052 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005053 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005054 goto parse_error;
5055 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005056 if (done_word(&dest, &ctx)) {
5057 goto parse_error;
5058 }
5059 done_pipe(&ctx, PIPE_SEQ);
5060 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005061 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005062 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005063 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005064 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005065 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005066 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005067#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005068 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005069 if (pstring)
5070 *pstring = ctx.as_string.data;
5071 else
5072 o_free_unsafe(&ctx.as_string);
5073#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005074 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5075 /* Example: bare "{ }", "()" */
5076 G.last_exitcode = 2; /* bash compat */
5077 syntax_error_unexpected_ch(ch);
5078 goto parse_error2;
5079 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005080 debug_printf_parse("parse_stream return %p: "
5081 "end_trigger char found\n",
5082 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005083 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005084 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005085 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005086 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005087 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005088 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005089 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005090
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005091 /* Catch <, > before deciding whether this word is
5092 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5093 switch (ch) {
5094 case '>':
5095 redir_fd = redirect_opt_num(&dest);
5096 if (done_word(&dest, &ctx)) {
5097 goto parse_error;
5098 }
5099 redir_style = REDIRECT_OVERWRITE;
5100 if (next == '>') {
5101 redir_style = REDIRECT_APPEND;
5102 ch = i_getch(input);
5103 nommu_addchr(&ctx.as_string, ch);
5104 }
5105#if 0
5106 else if (next == '(') {
5107 syntax_error(">(process) not supported");
5108 goto parse_error;
5109 }
5110#endif
5111 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5112 goto parse_error;
5113 continue; /* back to top of while (1) */
5114 case '<':
5115 redir_fd = redirect_opt_num(&dest);
5116 if (done_word(&dest, &ctx)) {
5117 goto parse_error;
5118 }
5119 redir_style = REDIRECT_INPUT;
5120 if (next == '<') {
5121 redir_style = REDIRECT_HEREDOC;
5122 heredoc_cnt++;
5123 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5124 ch = i_getch(input);
5125 nommu_addchr(&ctx.as_string, ch);
5126 } else if (next == '>') {
5127 redir_style = REDIRECT_IO;
5128 ch = i_getch(input);
5129 nommu_addchr(&ctx.as_string, ch);
5130 }
5131#if 0
5132 else if (next == '(') {
5133 syntax_error("<(process) not supported");
5134 goto parse_error;
5135 }
5136#endif
5137 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5138 goto parse_error;
5139 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005140 case '#':
5141 if (dest.length == 0 && !dest.has_quoted_part) {
5142 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005143 /* note: we do not add it to &ctx.as_string */
5144/* TODO: in bash:
5145 * comment inside $() goes to the next \n, even inside quoted string (!):
5146 * cmd "$(cmd2 #comment)" - syntax error
5147 * cmd "`cmd2 #comment`" - ok
5148 * We accept both (comment ends where command subst ends, in both cases).
5149 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005150 while (1) {
5151 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005152 if (ch == '\n') {
5153 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005154 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005155 }
5156 ch = i_getch(input);
5157 if (ch == EOF)
5158 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005159 }
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005160 continue; /* back to top of while (1) */
5161 }
5162 break;
5163 case '\\':
5164 if (next == '\n') {
5165 /* It's "\<newline>" */
5166#if !BB_MMU
5167 /* Remove trailing '\' from ctx.as_string */
5168 ctx.as_string.data[--ctx.as_string.length] = '\0';
5169#endif
5170 ch = i_getch(input); /* eat it */
5171 continue; /* back to top of while (1) */
5172 }
5173 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005174 }
5175
5176 if (dest.o_assignment == MAYBE_ASSIGNMENT
5177 /* check that we are not in word in "a=1 2>word b=1": */
5178 && !ctx.pending_redirect
5179 ) {
5180 /* ch is a special char and thus this word
5181 * cannot be an assignment */
5182 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005183 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005184 }
5185
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005186 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5187
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005188 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005189 case '#': /* non-comment #: "echo a#b" etc */
5190 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005191 break;
5192 case '\\':
5193 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005194 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005195 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005196 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005197 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005198 /* note: ch != '\n' (that case does not reach this place) */
5199 o_addchr(&dest, '\\');
5200 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5201 o_addchr(&dest, ch);
5202 nommu_addchr(&ctx.as_string, ch);
5203 /* Example: echo Hello \2>file
5204 * we need to know that word 2 is quoted */
5205 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005206 break;
5207 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005208 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005209 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005210 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005211 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005212 }
Eric Andersen25f27032001-04-26 23:22:31 +00005213 break;
5214 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005215 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005216 if (next == '\'' && !ctx.pending_redirect) {
5217 insert_empty_quoted_str_marker:
5218 nommu_addchr(&ctx.as_string, next);
5219 i_getch(input); /* eat second ' */
5220 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5221 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5222 } else {
5223 while (1) {
5224 ch = i_getch(input);
5225 if (ch == EOF) {
5226 syntax_error_unterm_ch('\'');
5227 goto parse_error;
5228 }
5229 nommu_addchr(&ctx.as_string, ch);
5230 if (ch == '\'')
5231 break;
5232 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005233 }
Eric Andersen25f27032001-04-26 23:22:31 +00005234 }
Eric Andersen25f27032001-04-26 23:22:31 +00005235 break;
5236 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005237 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005238 if (next == '"' && !ctx.pending_redirect)
5239 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005240 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005241 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005242 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005243 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005244 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00005245 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005246#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005247 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005248 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005249
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005250 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5251 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02005252 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005253 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5254 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005255# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005256 o_addstr(&ctx.as_string, dest.data + pos);
5257 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005258# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005259 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5260 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005261 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005262 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005263#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005264 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005265#if ENABLE_HUSH_CASE
5266 case_semi:
5267#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005268 if (done_word(&dest, &ctx)) {
5269 goto parse_error;
5270 }
5271 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005272#if ENABLE_HUSH_CASE
5273 /* Eat multiple semicolons, detect
5274 * whether it means something special */
5275 while (1) {
5276 ch = i_peek(input);
5277 if (ch != ';')
5278 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005279 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005280 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005281 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005282 ctx.ctx_dsemicolon = 1;
5283 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005284 break;
5285 }
5286 }
5287#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005288 new_cmd:
5289 /* We just finished a cmd. New one may start
5290 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005291 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005292 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00005293 break;
5294 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005295 if (done_word(&dest, &ctx)) {
5296 goto parse_error;
5297 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005298 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005299 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005300 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005301 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005302 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005303 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005304 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005305 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005306 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005307 if (done_word(&dest, &ctx)) {
5308 goto parse_error;
5309 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005310#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005311 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005312 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005313#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005314 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005315 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005316 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005317 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005318 } else {
5319 /* we could pick up a file descriptor choice here
5320 * with redirect_opt_num(), but bash doesn't do it.
5321 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005322 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005323 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005324 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005325 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005326#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005327 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005328 if (ctx.ctx_res_w == RES_MATCH
5329 && ctx.command->argv == NULL /* not (word|(... */
5330 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005331 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005332 ) {
5333 continue;
5334 }
5335#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005336 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005337 if (parse_group(&dest, &ctx, input, ch) != 0) {
5338 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005339 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005340 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005341 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005342#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005343 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005344 goto case_semi;
5345#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005346 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005347 /* proper use of this character is caught by end_trigger:
5348 * if we see {, we call parse_group(..., end_trigger='}')
5349 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005350 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005351 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005352 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005353 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005354 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005355 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005356 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005357 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005358
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005359 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005360 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005361 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005362 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005363 struct parse_context *pctx;
5364 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005365
5366 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005367 * Sample for finding leaks on syntax error recovery path.
5368 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005369 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005370 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005371 * while if (true | { true;}); then echo ok; fi; do break; done
5372 * 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 +00005373 */
5374 pctx = &ctx;
5375 do {
5376 /* Update pipe/command counts,
5377 * otherwise freeing may miss some */
5378 done_pipe(pctx, PIPE_SEQ);
5379 debug_printf_clean("freeing list %p from ctx %p\n",
5380 pctx->list_head, pctx);
5381 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005382 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005383 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005384#if !BB_MMU
5385 o_free_unsafe(&pctx->as_string);
5386#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005387 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005388 if (pctx != &ctx) {
5389 free(pctx);
5390 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005391 IF_HAS_KEYWORDS(pctx = p2;)
5392 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005393
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005394 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005395#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005396 if (pstring)
5397 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005398#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005399 debug_leave();
5400 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005401 }
Eric Andersen25f27032001-04-26 23:22:31 +00005402}
5403
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005404
5405/*** Execution routines ***/
5406
5407/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005408#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005409/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5410#define expand_string_to_string(str, do_unbackslash) \
5411 expand_string_to_string(str)
5412#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005413static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005414#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005415static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005416#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005417
5418/* expand_strvec_to_strvec() takes a list of strings, expands
5419 * all variable references within and returns a pointer to
5420 * a list of expanded strings, possibly with larger number
5421 * of strings. (Think VAR="a b"; echo $VAR).
5422 * This new list is allocated as a single malloc block.
5423 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005424 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005425 * Caller can deallocate entire list by single free(list). */
5426
Denys Vlasenko238081f2010-10-03 14:26:26 +02005427/* A horde of its helpers come first: */
5428
5429static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5430{
5431 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005432 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005433
Denys Vlasenko9e800222010-10-03 14:28:04 +02005434#if ENABLE_HUSH_BRACE_EXPANSION
5435 if (c == '{' || c == '}') {
5436 /* { -> \{, } -> \} */
5437 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005438 /* And now we want to add { or } and continue:
5439 * o_addchr(o, c);
5440 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005441 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005442 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005443 }
5444#endif
5445 o_addchr(o, c);
5446 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005447 /* \z -> \\\z; \<eol> -> \\<eol> */
5448 o_addchr(o, '\\');
5449 if (len) {
5450 len--;
5451 o_addchr(o, '\\');
5452 o_addchr(o, *str++);
5453 }
5454 }
5455 }
5456}
5457
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005458/* Store given string, finalizing the word and starting new one whenever
5459 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005460 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5461 * Return in *ended_with_ifs:
5462 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5463 */
5464static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005465{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005466 int last_is_ifs = 0;
5467
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005468 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005469 int word_len;
5470
5471 if (!*str) /* EOL - do not finalize word */
5472 break;
5473 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005474 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005475 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005476 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005477 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005478 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005479 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005480 * Example: "v='\*'; echo b$v" prints "b\*"
5481 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005482 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005483 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005484 /*/ Why can't we do it easier? */
5485 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5486 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5487 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005488 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005489 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005490 if (!*str) /* EOL - do not finalize word */
5491 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005492 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005493
5494 /* We know str here points to at least one IFS char */
5495 last_is_ifs = 1;
5496 str += strspn(str, G.ifs); /* skip IFS chars */
5497 if (!*str) /* EOL - do not finalize word */
5498 break;
5499
5500 /* Start new word... but not always! */
5501 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005502 if (output->has_quoted_part
5503 /* Case "v=' a'; echo $v":
5504 * here nothing precedes the space in $v expansion,
5505 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005506 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005507 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005508 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005509 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005510 o_addchr(output, '\0');
5511 debug_print_list("expand_on_ifs", output, n);
5512 n = o_save_ptr(output, n);
5513 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005514 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005515
5516 if (ended_with_ifs)
5517 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005518 debug_print_list("expand_on_ifs[1]", output, n);
5519 return n;
5520}
5521
5522/* Helper to expand $((...)) and heredoc body. These act as if
5523 * they are in double quotes, with the exception that they are not :).
5524 * Just the rules are similar: "expand only $var and `cmd`"
5525 *
5526 * Returns malloced string.
5527 * As an optimization, we return NULL if expansion is not needed.
5528 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005529#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005530/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5531#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5532 encode_then_expand_string(str)
5533#endif
5534static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005535{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005536#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005537 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005538#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005539 char *exp_str;
5540 struct in_str input;
5541 o_string dest = NULL_O_STRING;
5542
5543 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005544 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005545#if ENABLE_HUSH_TICK
5546 && !strchr(str, '`')
5547#endif
5548 ) {
5549 return NULL;
5550 }
5551
5552 /* We need to expand. Example:
5553 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5554 */
5555 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005556 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005557//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005558 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005559 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005560 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5561 o_free_unsafe(&dest);
5562 return exp_str;
5563}
5564
Denys Vlasenko0b883582016-12-23 16:49:07 +01005565#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005566static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005567{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005568 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005569 arith_t res;
5570 char *exp_str;
5571
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005572 math_state.lookupvar = get_local_var_value;
5573 math_state.setvar = set_local_var_from_halves;
5574 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005575 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005576 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005577 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005578 if (errmsg_p)
5579 *errmsg_p = math_state.errmsg;
5580 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005581 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005582 return res;
5583}
5584#endif
5585
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005586#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005587/* ${var/[/]pattern[/repl]} helpers */
5588static char *strstr_pattern(char *val, const char *pattern, int *size)
5589{
5590 while (1) {
5591 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5592 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5593 if (end) {
5594 *size = end - val;
5595 return val;
5596 }
5597 if (*val == '\0')
5598 return NULL;
5599 /* Optimization: if "*pat" did not match the start of "string",
5600 * we know that "tring", "ring" etc will not match too:
5601 */
5602 if (pattern[0] == '*')
5603 return NULL;
5604 val++;
5605 }
5606}
5607static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5608{
5609 char *result = NULL;
5610 unsigned res_len = 0;
5611 unsigned repl_len = strlen(repl);
5612
5613 while (1) {
5614 int size;
5615 char *s = strstr_pattern(val, pattern, &size);
5616 if (!s)
5617 break;
5618
5619 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005620 strcpy(mempcpy(result + res_len, val, s - val), repl);
5621 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005622 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5623
5624 val = s + size;
5625 if (exp_op == '/')
5626 break;
5627 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005628 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005629 result = xrealloc(result, res_len + strlen(val) + 1);
5630 strcpy(result + res_len, val);
5631 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5632 }
5633 debug_printf_varexp("result:'%s'\n", result);
5634 return result;
5635}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005636#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005637
5638/* Helper:
5639 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5640 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005641static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005642{
5643 const char *val = NULL;
5644 char *to_be_freed = NULL;
5645 char *p = *pp;
5646 char *var;
5647 char first_char;
5648 char exp_op;
5649 char exp_save = exp_save; /* for compiler */
5650 char *exp_saveptr; /* points to expansion operator */
5651 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005652 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005653
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005654 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005655 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005656 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005657 arg0 = arg[0];
5658 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005659 exp_op = 0;
5660
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005661 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5662 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5663 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5664 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005665 ) {
5666 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005667 var++;
5668 exp_op = 'L';
5669 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005670 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005671 if (exp_saveptr /* if 2nd char is one of expansion operators */
5672 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5673 ) {
5674 /* ${?:0}, ${#[:]%0} etc */
5675 exp_saveptr = var + 1;
5676 } else {
5677 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5678 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5679 }
5680 exp_op = exp_save = *exp_saveptr;
5681 if (exp_op) {
5682 exp_word = exp_saveptr + 1;
5683 if (exp_op == ':') {
5684 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005685//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005686 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005687 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005688 ) {
5689 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5690 exp_op = ':';
5691 exp_word--;
5692 }
5693 }
5694 *exp_saveptr = '\0';
5695 } /* else: it's not an expansion op, but bare ${var} */
5696 }
5697
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005698 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005699 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005700 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005701 int n = xatoi_positive(var);
5702 if (n < G.global_argc)
5703 val = G.global_argv[n];
5704 /* else val remains NULL: $N with too big N */
5705 } else {
5706 switch (var[0]) {
5707 case '$': /* pid */
5708 val = utoa(G.root_pid);
5709 break;
5710 case '!': /* bg pid */
5711 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5712 break;
5713 case '?': /* exitcode */
5714 val = utoa(G.last_exitcode);
5715 break;
5716 case '#': /* argc */
5717 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5718 break;
5719 default:
5720 val = get_local_var_value(var);
5721 }
5722 }
5723
5724 /* Handle any expansions */
5725 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005726 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005727 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005728 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005729 debug_printf_expand("%s\n", val);
5730 } else if (exp_op) {
5731 if (exp_op == '%' || exp_op == '#') {
5732 /* Standard-mandated substring removal ops:
5733 * ${parameter%word} - remove smallest suffix pattern
5734 * ${parameter%%word} - remove largest suffix pattern
5735 * ${parameter#word} - remove smallest prefix pattern
5736 * ${parameter##word} - remove largest prefix pattern
5737 *
5738 * Word is expanded to produce a glob pattern.
5739 * Then var's value is matched to it and matching part removed.
5740 */
5741 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005742 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005743 char *exp_exp_word;
5744 char *loc;
5745 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005746 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005747 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005748 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005749 if (exp_exp_word)
5750 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005751 /* HACK ALERT. We depend here on the fact that
5752 * G.global_argv and results of utoa and get_local_var_value
5753 * are actually in writable memory:
5754 * scan_and_match momentarily stores NULs there. */
5755 t = (char*)val;
5756 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005757 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005758 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005759 free(exp_exp_word);
5760 if (loc) { /* match was found */
5761 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005762 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005763 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005764 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005765 }
5766 }
5767 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005768#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005769 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005770 /* It's ${var/[/]pattern[/repl]} thing.
5771 * Note that in encoded form it has TWO parts:
5772 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005773 * and if // is used, it is encoded as \:
5774 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005775 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005776 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005777 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005778 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005779 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005780 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005781 * by the usual expansion rules:
5782 * >az; >bz;
5783 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5784 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5785 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5786 * v='a bz'; echo ${v/a*z/\z} prints "z"
5787 * (note that a*z _pattern_ is never globbed!)
5788 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005789 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005790 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005791 if (!pattern)
5792 pattern = xstrdup(exp_word);
5793 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5794 *p++ = SPECIAL_VAR_SYMBOL;
5795 exp_word = p;
5796 p = strchr(p, SPECIAL_VAR_SYMBOL);
5797 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005798 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005799 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5800 /* HACK ALERT. We depend here on the fact that
5801 * G.global_argv and results of utoa and get_local_var_value
5802 * are actually in writable memory:
5803 * replace_pattern momentarily stores NULs there. */
5804 t = (char*)val;
5805 to_be_freed = replace_pattern(t,
5806 pattern,
5807 (repl ? repl : exp_word),
5808 exp_op);
5809 if (to_be_freed) /* at least one replace happened */
5810 val = to_be_freed;
5811 free(pattern);
5812 free(repl);
5813 }
5814 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005815#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005816 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005817#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005818 /* It's ${var:N[:M]} bashism.
5819 * Note that in encoded form it has TWO parts:
5820 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5821 */
5822 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005823 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005824
Denys Vlasenko063847d2010-09-15 13:33:02 +02005825 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5826 if (errmsg)
5827 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005828 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5829 *p++ = SPECIAL_VAR_SYMBOL;
5830 exp_word = p;
5831 p = strchr(p, SPECIAL_VAR_SYMBOL);
5832 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005833 len = expand_and_evaluate_arith(exp_word, &errmsg);
5834 if (errmsg)
5835 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005836 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005837 if (beg < 0) {
5838 /* negative beg counts from the end */
5839 beg = (arith_t)strlen(val) + beg;
5840 if (beg < 0) /* ${v: -999999} is "" */
5841 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005842 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005843 debug_printf_varexp("from val:'%s'\n", val);
5844 if (len < 0) {
5845 /* in bash, len=-n means strlen()-n */
5846 len = (arith_t)strlen(val) - beg + len;
5847 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02005848 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005849 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02005850 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005851 arith_err:
5852 val = NULL;
5853 } else {
5854 /* Paranoia. What if user entered 9999999999999
5855 * which fits in arith_t but not int? */
5856 if (len >= INT_MAX)
5857 len = INT_MAX;
5858 val = to_be_freed = xstrndup(val + beg, len);
5859 }
5860 debug_printf_varexp("val:'%s'\n", val);
5861#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02005862 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005863 val = NULL;
5864#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005865 } else { /* one of "-=+?" */
5866 /* Standard-mandated substitution ops:
5867 * ${var?word} - indicate error if unset
5868 * If var is unset, word (or a message indicating it is unset
5869 * if word is null) is written to standard error
5870 * and the shell exits with a non-zero exit status.
5871 * Otherwise, the value of var is substituted.
5872 * ${var-word} - use default value
5873 * If var is unset, word is substituted.
5874 * ${var=word} - assign and use default value
5875 * If var is unset, word is assigned to var.
5876 * In all cases, final value of var is substituted.
5877 * ${var+word} - use alternative value
5878 * If var is unset, null is substituted.
5879 * Otherwise, word is substituted.
5880 *
5881 * Word is subjected to tilde expansion, parameter expansion,
5882 * command substitution, and arithmetic expansion.
5883 * If word is not needed, it is not expanded.
5884 *
5885 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5886 * but also treat null var as if it is unset.
5887 */
5888 int use_word = (!val || ((exp_save == ':') && !val[0]));
5889 if (exp_op == '+')
5890 use_word = !use_word;
5891 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5892 (exp_save == ':') ? "true" : "false", use_word);
5893 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005894 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005895 if (to_be_freed)
5896 exp_word = to_be_freed;
5897 if (exp_op == '?') {
5898 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02005899 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005900 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02005901 exp_word[0]
5902 ? exp_word
5903 : "parameter null or not set"
5904 /* ash has more specific messages, a-la: */
5905 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005906 );
5907//TODO: how interactive bash aborts expansion mid-command?
5908 } else {
5909 val = exp_word;
5910 }
5911
5912 if (exp_op == '=') {
5913 /* ${var=[word]} or ${var:=[word]} */
5914 if (isdigit(var[0]) || var[0] == '#') {
5915 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02005916 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005917 val = NULL;
5918 } else {
5919 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02005920 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005921 }
5922 }
5923 }
5924 } /* one of "-=+?" */
5925
5926 *exp_saveptr = exp_save;
5927 } /* if (exp_op) */
5928
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005929 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005930
5931 *pp = p;
5932 *to_be_freed_pp = to_be_freed;
5933 return val;
5934}
5935
5936/* Expand all variable references in given string, adding words to list[]
5937 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5938 * to be filled). This routine is extremely tricky: has to deal with
5939 * variables/parameters with whitespace, $* and $@, and constructs like
5940 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005941static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005942{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005943 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005944 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005945 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005946 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005947 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005948 char *p;
5949
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005950 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5951 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005952 debug_print_list("expand_vars_to_list", output, n);
5953 n = o_save_ptr(output, n);
5954 debug_print_list("expand_vars_to_list[0]", output, n);
5955
5956 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5957 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005958 char *to_be_freed = NULL;
5959 const char *val = NULL;
5960#if ENABLE_HUSH_TICK
5961 o_string subst_result = NULL_O_STRING;
5962#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01005963#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005964 char arith_buf[sizeof(arith_t)*3 + 2];
5965#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005966
5967 if (ended_in_ifs) {
5968 o_addchr(output, '\0');
5969 n = o_save_ptr(output, n);
5970 ended_in_ifs = 0;
5971 }
5972
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005973 o_addblock(output, arg, p - arg);
5974 debug_print_list("expand_vars_to_list[1]", output, n);
5975 arg = ++p;
5976 p = strchr(p, SPECIAL_VAR_SYMBOL);
5977
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005978 /* Fetch special var name (if it is indeed one of them)
5979 * and quote bit, force the bit on if singleword expansion -
5980 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005981 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005982
5983 /* Is this variable quoted and thus expansion can't be null?
5984 * "$@" is special. Even if quoted, it can still
5985 * expand to nothing (not even an empty string),
5986 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005987 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005988 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005989
5990 switch (first_ch & 0x7f) {
5991 /* Highest bit in first_ch indicates that var is double-quoted */
5992 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005993 case '@': {
5994 int i;
5995 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005996 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005997 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005998 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005999 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006000 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006001 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006002 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6003 if (G.global_argv[i++][0] && G.global_argv[i]) {
6004 /* this argv[] is not empty and not last:
6005 * put terminating NUL, start new word */
6006 o_addchr(output, '\0');
6007 debug_print_list("expand_vars_to_list[2]", output, n);
6008 n = o_save_ptr(output, n);
6009 debug_print_list("expand_vars_to_list[3]", output, n);
6010 }
6011 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006012 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006013 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006014 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006015 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006016 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006017 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006018 while (1) {
6019 o_addQstr(output, G.global_argv[i]);
6020 if (++i >= G.global_argc)
6021 break;
6022 o_addchr(output, '\0');
6023 debug_print_list("expand_vars_to_list[4]", output, n);
6024 n = o_save_ptr(output, n);
6025 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006026 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006027 while (1) {
6028 o_addQstr(output, G.global_argv[i]);
6029 if (!G.global_argv[++i])
6030 break;
6031 if (G.ifs[0])
6032 o_addchr(output, G.ifs[0]);
6033 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006034 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006035 }
6036 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006037 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006038 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6039 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006040 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006041 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006042 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006043 break;
6044#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 Vlasenkobd43c672017-07-05 23:12:15 +02006202/* Used for "eval" builtin and case string */
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}
6224
6225static char **expand_assignments(char **argv, int count)
6226{
6227 int i;
6228 char **p;
6229
6230 G.expanded_assignments = p = NULL;
6231 /* Expand assignments into one string each */
6232 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006233 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006234 }
6235 G.expanded_assignments = NULL;
6236 return p;
6237}
6238
6239
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006240static void switch_off_special_sigs(unsigned mask)
6241{
6242 unsigned sig = 0;
6243 while ((mask >>= 1) != 0) {
6244 sig++;
6245 if (!(mask & 1))
6246 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006247#if ENABLE_HUSH_TRAP
6248 if (G_traps) {
6249 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006250 /* trap is '', has to remain SIG_IGN */
6251 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006252 free(G_traps[sig]);
6253 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006254 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006255#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006256 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006257 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006258 }
6259}
6260
Denys Vlasenkob347df92011-08-09 22:49:15 +02006261#if BB_MMU
6262/* never called */
6263void re_execute_shell(char ***to_free, const char *s,
6264 char *g_argv0, char **g_argv,
6265 char **builtin_argv) NORETURN;
6266
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006267static void reset_traps_to_defaults(void)
6268{
6269 /* This function is always called in a child shell
6270 * after fork (not vfork, NOMMU doesn't use this function).
6271 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006272 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006273 unsigned mask;
6274
6275 /* Child shells are not interactive.
6276 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6277 * Testcase: (while :; do :; done) + ^Z should background.
6278 * Same goes for SIGTERM, SIGHUP, SIGINT.
6279 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006280 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006281 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006282 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006283
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006284 /* Switch off special sigs */
6285 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006286# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006287 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006288# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006289 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006290 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6291 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006292
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006293# if ENABLE_HUSH_TRAP
6294 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006295 return;
6296
6297 /* Reset all sigs to default except ones with empty traps */
6298 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006299 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006300 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006301 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006302 continue; /* empty trap: has to remain SIG_IGN */
6303 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006304 free(G_traps[sig]);
6305 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006306 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006307 if (sig == 0)
6308 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006309 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006310 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006311# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006312}
6313
6314#else /* !BB_MMU */
6315
6316static void re_execute_shell(char ***to_free, const char *s,
6317 char *g_argv0, char **g_argv,
6318 char **builtin_argv) NORETURN;
6319static void re_execute_shell(char ***to_free, const char *s,
6320 char *g_argv0, char **g_argv,
6321 char **builtin_argv)
6322{
6323# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6324 /* delims + 2 * (number of bytes in printed hex numbers) */
6325 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6326 char *heredoc_argv[4];
6327 struct variable *cur;
6328# if ENABLE_HUSH_FUNCTIONS
6329 struct function *funcp;
6330# endif
6331 char **argv, **pp;
6332 unsigned cnt;
6333 unsigned long long empty_trap_mask;
6334
6335 if (!g_argv0) { /* heredoc */
6336 argv = heredoc_argv;
6337 argv[0] = (char *) G.argv0_for_re_execing;
6338 argv[1] = (char *) "-<";
6339 argv[2] = (char *) s;
6340 argv[3] = NULL;
6341 pp = &argv[3]; /* used as pointer to empty environment */
6342 goto do_exec;
6343 }
6344
6345 cnt = 0;
6346 pp = builtin_argv;
6347 if (pp) while (*pp++)
6348 cnt++;
6349
6350 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006351 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006352 int sig;
6353 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006354 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006355 empty_trap_mask |= 1LL << sig;
6356 }
6357 }
6358
6359 sprintf(param_buf, NOMMU_HACK_FMT
6360 , (unsigned) G.root_pid
6361 , (unsigned) G.root_ppid
6362 , (unsigned) G.last_bg_pid
6363 , (unsigned) G.last_exitcode
6364 , cnt
6365 , empty_trap_mask
6366 IF_HUSH_LOOPS(, G.depth_of_loop)
6367 );
6368# undef NOMMU_HACK_FMT
6369 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6370 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6371 */
6372 cnt += 6;
6373 for (cur = G.top_var; cur; cur = cur->next) {
6374 if (!cur->flg_export || cur->flg_read_only)
6375 cnt += 2;
6376 }
6377# if ENABLE_HUSH_FUNCTIONS
6378 for (funcp = G.top_func; funcp; funcp = funcp->next)
6379 cnt += 3;
6380# endif
6381 pp = g_argv;
6382 while (*pp++)
6383 cnt++;
6384 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6385 *pp++ = (char *) G.argv0_for_re_execing;
6386 *pp++ = param_buf;
6387 for (cur = G.top_var; cur; cur = cur->next) {
6388 if (strcmp(cur->varstr, hush_version_str) == 0)
6389 continue;
6390 if (cur->flg_read_only) {
6391 *pp++ = (char *) "-R";
6392 *pp++ = cur->varstr;
6393 } else if (!cur->flg_export) {
6394 *pp++ = (char *) "-V";
6395 *pp++ = cur->varstr;
6396 }
6397 }
6398# if ENABLE_HUSH_FUNCTIONS
6399 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6400 *pp++ = (char *) "-F";
6401 *pp++ = funcp->name;
6402 *pp++ = funcp->body_as_string;
6403 }
6404# endif
6405 /* We can pass activated traps here. Say, -Tnn:trap_string
6406 *
6407 * However, POSIX says that subshells reset signals with traps
6408 * to SIG_DFL.
6409 * I tested bash-3.2 and it not only does that with true subshells
6410 * of the form ( list ), but with any forked children shells.
6411 * I set trap "echo W" WINCH; and then tried:
6412 *
6413 * { echo 1; sleep 20; echo 2; } &
6414 * while true; do echo 1; sleep 20; echo 2; break; done &
6415 * true | { echo 1; sleep 20; echo 2; } | cat
6416 *
6417 * In all these cases sending SIGWINCH to the child shell
6418 * did not run the trap. If I add trap "echo V" WINCH;
6419 * _inside_ group (just before echo 1), it works.
6420 *
6421 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006422 */
6423 *pp++ = (char *) "-c";
6424 *pp++ = (char *) s;
6425 if (builtin_argv) {
6426 while (*++builtin_argv)
6427 *pp++ = *builtin_argv;
6428 *pp++ = (char *) "";
6429 }
6430 *pp++ = g_argv0;
6431 while (*g_argv)
6432 *pp++ = *g_argv++;
6433 /* *pp = NULL; - is already there */
6434 pp = environ;
6435
6436 do_exec:
6437 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006438 /* Don't propagate SIG_IGN to the child */
6439 if (SPECIAL_JOBSTOP_SIGS != 0)
6440 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006441 execve(bb_busybox_exec_path, argv, pp);
6442 /* Fallback. Useful for init=/bin/hush usage etc */
6443 if (argv[0][0] == '/')
6444 execve(argv[0], argv, pp);
6445 xfunc_error_retval = 127;
6446 bb_error_msg_and_die("can't re-execute the shell");
6447}
6448#endif /* !BB_MMU */
6449
6450
6451static int run_and_free_list(struct pipe *pi);
6452
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006453/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006454 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6455 * end_trigger controls how often we stop parsing
6456 * NUL: parse all, execute, return
6457 * ';': parse till ';' or newline, execute, repeat till EOF
6458 */
6459static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006460{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006461 /* Why we need empty flag?
6462 * An obscure corner case "false; ``; echo $?":
6463 * empty command in `` should still set $? to 0.
6464 * But we can't just set $? to 0 at the start,
6465 * this breaks "false; echo `echo $?`" case.
6466 */
6467 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006468 while (1) {
6469 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006470
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006471#if ENABLE_HUSH_INTERACTIVE
6472 if (end_trigger == ';')
6473 inp->promptmode = 0; /* PS1 */
6474#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006475 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006476 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6477 /* If we are in "big" script
6478 * (not in `cmd` or something similar)...
6479 */
6480 if (pipe_list == ERR_PTR && end_trigger == ';') {
6481 /* Discard cached input (rest of line) */
6482 int ch = inp->last_char;
6483 while (ch != EOF && ch != '\n') {
6484 //bb_error_msg("Discarded:'%c'", ch);
6485 ch = i_getch(inp);
6486 }
6487 /* Force prompt */
6488 inp->p = NULL;
6489 /* This stream isn't empty */
6490 empty = 0;
6491 continue;
6492 }
6493 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006494 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006495 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006496 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006497 debug_print_tree(pipe_list, 0);
6498 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6499 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006500 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006501 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006502 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006503 }
Eric Andersen25f27032001-04-26 23:22:31 +00006504}
6505
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006506static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006507{
6508 struct in_str input;
6509 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006510 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006511}
6512
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006513static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006514{
Eric Andersen25f27032001-04-26 23:22:31 +00006515 struct in_str input;
6516 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006517 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006518}
6519
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006520#if ENABLE_HUSH_TICK
6521static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6522{
6523 pid_t pid;
6524 int channel[2];
6525# if !BB_MMU
6526 char **to_free = NULL;
6527# endif
6528
6529 xpipe(channel);
6530 pid = BB_MMU ? xfork() : xvfork();
6531 if (pid == 0) { /* child */
6532 disable_restore_tty_pgrp_on_exit();
6533 /* Process substitution is not considered to be usual
6534 * 'command execution'.
6535 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6536 */
6537 bb_signals(0
6538 + (1 << SIGTSTP)
6539 + (1 << SIGTTIN)
6540 + (1 << SIGTTOU)
6541 , SIG_IGN);
6542 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6543 close(channel[0]); /* NB: close _first_, then move fd! */
6544 xmove_fd(channel[1], 1);
6545 /* Prevent it from trying to handle ctrl-z etc */
6546 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006547# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006548 /* Awful hack for `trap` or $(trap).
6549 *
6550 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6551 * contains an example where "trap" is executed in a subshell:
6552 *
6553 * save_traps=$(trap)
6554 * ...
6555 * eval "$save_traps"
6556 *
6557 * Standard does not say that "trap" in subshell shall print
6558 * parent shell's traps. It only says that its output
6559 * must have suitable form, but then, in the above example
6560 * (which is not supposed to be normative), it implies that.
6561 *
6562 * bash (and probably other shell) does implement it
6563 * (traps are reset to defaults, but "trap" still shows them),
6564 * but as a result, "trap" logic is hopelessly messed up:
6565 *
6566 * # trap
6567 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6568 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6569 * # true | trap <--- trap is in subshell - no output (ditto)
6570 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6571 * trap -- 'echo Ho' SIGWINCH
6572 * # echo `(trap)` <--- in subshell in subshell - output
6573 * trap -- 'echo Ho' SIGWINCH
6574 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6575 * trap -- 'echo Ho' SIGWINCH
6576 *
6577 * The rules when to forget and when to not forget traps
6578 * get really complex and nonsensical.
6579 *
6580 * Our solution: ONLY bare $(trap) or `trap` is special.
6581 */
6582 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006583 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006584 && skip_whitespace(s + 4)[0] == '\0'
6585 ) {
6586 static const char *const argv[] = { NULL, NULL };
6587 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006588 fflush_all(); /* important */
6589 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006590 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006591# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006592# if BB_MMU
6593 reset_traps_to_defaults();
6594 parse_and_run_string(s);
6595 _exit(G.last_exitcode);
6596# else
6597 /* We re-execute after vfork on NOMMU. This makes this script safe:
6598 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6599 * huge=`cat BIG` # was blocking here forever
6600 * echo OK
6601 */
6602 re_execute_shell(&to_free,
6603 s,
6604 G.global_argv[0],
6605 G.global_argv + 1,
6606 NULL);
6607# endif
6608 }
6609
6610 /* parent */
6611 *pid_p = pid;
6612# if ENABLE_HUSH_FAST
6613 G.count_SIGCHLD++;
6614//bb_error_msg("[%d] fork in generate_stream_from_string:"
6615// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6616// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6617# endif
6618 enable_restore_tty_pgrp_on_exit();
6619# if !BB_MMU
6620 free(to_free);
6621# endif
6622 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006623 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006624}
6625
6626/* Return code is exit status of the process that is run. */
6627static int process_command_subs(o_string *dest, const char *s)
6628{
6629 FILE *fp;
6630 struct in_str pipe_str;
6631 pid_t pid;
6632 int status, ch, eol_cnt;
6633
6634 fp = generate_stream_from_string(s, &pid);
6635
6636 /* Now send results of command back into original context */
6637 setup_file_in_str(&pipe_str, fp);
6638 eol_cnt = 0;
6639 while ((ch = i_getch(&pipe_str)) != EOF) {
6640 if (ch == '\n') {
6641 eol_cnt++;
6642 continue;
6643 }
6644 while (eol_cnt) {
6645 o_addchr(dest, '\n');
6646 eol_cnt--;
6647 }
6648 o_addQchr(dest, ch);
6649 }
6650
6651 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006652 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006653 /* We need to extract exitcode. Test case
6654 * "true; echo `sleep 1; false` $?"
6655 * should print 1 */
6656 safe_waitpid(pid, &status, 0);
6657 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6658 return WEXITSTATUS(status);
6659}
6660#endif /* ENABLE_HUSH_TICK */
6661
6662
6663static void setup_heredoc(struct redir_struct *redir)
6664{
6665 struct fd_pair pair;
6666 pid_t pid;
6667 int len, written;
6668 /* the _body_ of heredoc (misleading field name) */
6669 const char *heredoc = redir->rd_filename;
6670 char *expanded;
6671#if !BB_MMU
6672 char **to_free;
6673#endif
6674
6675 expanded = NULL;
6676 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006677 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006678 if (expanded)
6679 heredoc = expanded;
6680 }
6681 len = strlen(heredoc);
6682
6683 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6684 xpiped_pair(pair);
6685 xmove_fd(pair.rd, redir->rd_fd);
6686
6687 /* Try writing without forking. Newer kernels have
6688 * dynamically growing pipes. Must use non-blocking write! */
6689 ndelay_on(pair.wr);
6690 while (1) {
6691 written = write(pair.wr, heredoc, len);
6692 if (written <= 0)
6693 break;
6694 len -= written;
6695 if (len == 0) {
6696 close(pair.wr);
6697 free(expanded);
6698 return;
6699 }
6700 heredoc += written;
6701 }
6702 ndelay_off(pair.wr);
6703
6704 /* Okay, pipe buffer was not big enough */
6705 /* Note: we must not create a stray child (bastard? :)
6706 * for the unsuspecting parent process. Child creates a grandchild
6707 * and exits before parent execs the process which consumes heredoc
6708 * (that exec happens after we return from this function) */
6709#if !BB_MMU
6710 to_free = NULL;
6711#endif
6712 pid = xvfork();
6713 if (pid == 0) {
6714 /* child */
6715 disable_restore_tty_pgrp_on_exit();
6716 pid = BB_MMU ? xfork() : xvfork();
6717 if (pid != 0)
6718 _exit(0);
6719 /* grandchild */
6720 close(redir->rd_fd); /* read side of the pipe */
6721#if BB_MMU
6722 full_write(pair.wr, heredoc, len); /* may loop or block */
6723 _exit(0);
6724#else
6725 /* Delegate blocking writes to another process */
6726 xmove_fd(pair.wr, STDOUT_FILENO);
6727 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6728#endif
6729 }
6730 /* parent */
6731#if ENABLE_HUSH_FAST
6732 G.count_SIGCHLD++;
6733//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6734#endif
6735 enable_restore_tty_pgrp_on_exit();
6736#if !BB_MMU
6737 free(to_free);
6738#endif
6739 close(pair.wr);
6740 free(expanded);
6741 wait(NULL); /* wait till child has died */
6742}
6743
Denys Vlasenko2db74612017-07-07 22:07:28 +02006744struct squirrel {
6745 int orig_fd;
6746 int moved_to;
6747 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6748 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6749};
6750
Denys Vlasenko621fc502017-07-24 12:42:17 +02006751static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6752{
6753 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6754 sq[i].orig_fd = orig;
6755 sq[i].moved_to = moved;
6756 sq[i+1].orig_fd = -1; /* end marker */
6757 return sq;
6758}
6759
Denys Vlasenko2db74612017-07-07 22:07:28 +02006760static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6761{
Denys Vlasenko621fc502017-07-24 12:42:17 +02006762 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006763 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02006764
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006765 i = 0;
6766 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006767 /* If we collide with an already moved fd... */
6768 if (fd == sq[i].moved_to) {
6769 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6770 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6771 if (sq[i].moved_to < 0) /* what? */
6772 xfunc_die();
6773 return sq;
6774 }
6775 if (fd == sq[i].orig_fd) {
6776 /* Example: echo Hello >/dev/null 1>&2 */
6777 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6778 return sq;
6779 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006780 }
6781
Denys Vlasenko2db74612017-07-07 22:07:28 +02006782 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko621fc502017-07-24 12:42:17 +02006783 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6784 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6785 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02006786 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02006787 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006788}
6789
Denys Vlasenko657e9002017-07-30 23:34:04 +02006790static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6791{
6792 int i;
6793
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006794 i = 0;
6795 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006796 /* If we collide with an already moved fd... */
6797 if (fd == sq[i].orig_fd) {
6798 /* Examples:
6799 * "echo 3>FILE 3>&- 3>FILE"
6800 * "echo 3>&- 3>FILE"
6801 * No need for last redirect to insert
6802 * another "need to close 3" indicator.
6803 */
6804 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6805 return sq;
6806 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006807 }
6808
6809 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6810 return append_squirrel(sq, i, fd, -1);
6811}
6812
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006813/* fd: redirect wants this fd to be used (e.g. 3>file).
6814 * Move all conflicting internally used fds,
6815 * and remember them so that we can restore them later.
6816 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006817static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006818{
Denys Vlasenko2db74612017-07-07 22:07:28 +02006819 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6820 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006821
6822#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006823 if (fd == G.interactive_fd) {
6824 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006825 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006826 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6827 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006828 }
6829#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006830 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6831 * (1) Redirect in a forked child. No need to save FILEs' fds,
6832 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02006833 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6834 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006835 * "fileno(fd) = new_fd" can't be done.
6836 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02006837 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006838 return 0;
6839
Denys Vlasenko2db74612017-07-07 22:07:28 +02006840 /* If this one of script's fds? */
6841 if (save_FILEs_on_redirect(fd, avoid_fd))
6842 return 1; /* yes. "we closed fd" */
6843
6844 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6845 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6846 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006847}
6848
Denys Vlasenko2db74612017-07-07 22:07:28 +02006849static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006850{
Denys Vlasenko2db74612017-07-07 22:07:28 +02006851 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006852 int i;
6853 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006854 if (sq[i].moved_to >= 0) {
6855 /* We simply die on error */
6856 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6857 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6858 } else {
6859 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6860 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6861 close(sq[i].orig_fd);
6862 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006863 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006864 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006865 }
6866
Denys Vlasenko2db74612017-07-07 22:07:28 +02006867 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006868
6869 restore_redirected_FILEs();
6870}
6871
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02006872#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02006873static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02006874{
6875 if (G_interactive_fd)
6876 close(G_interactive_fd);
6877 close_all_FILE_list();
6878}
6879#endif
6880
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006881static int internally_opened_fd(int fd, struct squirrel *sq)
6882{
6883 int i;
6884
6885#if ENABLE_HUSH_INTERACTIVE
6886 if (fd == G.interactive_fd)
6887 return 1;
6888#endif
6889 /* If this one of script's fds? */
6890 if (fd_in_FILEs(fd))
6891 return 1;
6892
6893 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6894 if (fd == sq[i].moved_to)
6895 return 1;
6896 }
6897 return 0;
6898}
6899
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006900/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6901 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02006902static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006903{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006904 struct redir_struct *redir;
6905
6906 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006907 int newfd;
6908 int closed;
6909
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006910 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006911 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006912 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006913 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6914 * of the heredoc */
6915 debug_printf_parse("set heredoc '%s'\n",
6916 redir->rd_filename);
6917 setup_heredoc(redir);
6918 continue;
6919 }
6920
6921 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006922 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006923 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02006924 int mode;
6925
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006926 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02006927 /*
6928 * Examples:
6929 * "cmd >" (no filename)
6930 * "cmd > <file" (2nd redirect starts too early)
6931 */
Denys Vlasenko39701202017-08-02 19:44:05 +02006932 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006933 continue;
6934 }
6935 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006936 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02006937 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006938 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02006939 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006940 /* Error message from open_or_warn can be lost
6941 * if stderr has been redirected, but bash
6942 * and ash both lose it as well
6943 * (though zsh doesn't!)
6944 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006945 return 1;
6946 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006947 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02006948 /* open() gave us precisely the fd we wanted.
6949 * This means that this fd was not busy
6950 * (not opened to anywhere).
6951 * Remember to close it on restore:
6952 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006953 *sqp = add_squirrel_closed(*sqp, newfd);
6954 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02006955 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006956 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006957 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
6958 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006959 }
6960
Denys Vlasenko657e9002017-07-30 23:34:04 +02006961 if (newfd == redir->rd_fd)
6962 continue;
6963
6964 /* if "N>FILE": move newfd to redir->rd_fd */
6965 /* if "N>&M": dup newfd to redir->rd_fd */
6966 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
6967
6968 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
6969 if (newfd == REDIRFD_CLOSE) {
6970 /* "N>&-" means "close me" */
6971 if (!closed) {
6972 /* ^^^ optimization: saving may already
6973 * have closed it. If not... */
6974 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006975 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006976 /* Sometimes we do another close on restore, getting EBADF.
6977 * Consider "echo 3>FILE 3>&-"
6978 * first redirect remembers "need to close 3",
6979 * and second redirect closes 3! Restore code then closes 3 again.
6980 */
6981 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006982 /* if newfd is a script fd or saved fd, simulate EBADF */
6983 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
6984 //errno = EBADF;
6985 //bb_perror_msg_and_die("can't duplicate file descriptor");
6986 newfd = -1; /* same effect as code above */
6987 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006988 xdup2(newfd, redir->rd_fd);
6989 if (redir->rd_dup == REDIRFD_TO_FILE)
6990 /* "rd_fd > FILE" */
6991 close(newfd);
6992 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006993 }
6994 }
6995 return 0;
6996}
6997
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006998static char *find_in_path(const char *arg)
6999{
7000 char *ret = NULL;
7001 const char *PATH = get_local_var_value("PATH");
7002
7003 if (!PATH)
7004 return NULL;
7005
7006 while (1) {
7007 const char *end = strchrnul(PATH, ':');
7008 int sz = end - PATH; /* must be int! */
7009
7010 free(ret);
7011 if (sz != 0) {
7012 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7013 } else {
7014 /* We have xxx::yyyy in $PATH,
7015 * it means "use current dir" */
7016 ret = xstrdup(arg);
7017 }
7018 if (access(ret, F_OK) == 0)
7019 break;
7020
7021 if (*end == '\0') {
7022 free(ret);
7023 return NULL;
7024 }
7025 PATH = end + 1;
7026 }
7027
7028 return ret;
7029}
7030
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007031static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007032 const struct built_in_command *x,
7033 const struct built_in_command *end)
7034{
7035 while (x != end) {
7036 if (strcmp(name, x->b_cmd) != 0) {
7037 x++;
7038 continue;
7039 }
7040 debug_printf_exec("found builtin '%s'\n", name);
7041 return x;
7042 }
7043 return NULL;
7044}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007045static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007046{
7047 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7048}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007049static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007050{
7051 const struct built_in_command *x = find_builtin1(name);
7052 if (x)
7053 return x;
7054 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7055}
7056
7057#if ENABLE_HUSH_FUNCTIONS
7058static struct function **find_function_slot(const char *name)
7059{
7060 struct function **funcpp = &G.top_func;
7061 while (*funcpp) {
7062 if (strcmp(name, (*funcpp)->name) == 0) {
7063 break;
7064 }
7065 funcpp = &(*funcpp)->next;
7066 }
7067 return funcpp;
7068}
7069
7070static const struct function *find_function(const char *name)
7071{
7072 const struct function *funcp = *find_function_slot(name);
7073 if (funcp)
7074 debug_printf_exec("found function '%s'\n", name);
7075 return funcp;
7076}
7077
7078/* Note: takes ownership on name ptr */
7079static struct function *new_function(char *name)
7080{
7081 struct function **funcpp = find_function_slot(name);
7082 struct function *funcp = *funcpp;
7083
7084 if (funcp != NULL) {
7085 struct command *cmd = funcp->parent_cmd;
7086 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7087 if (!cmd) {
7088 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7089 free(funcp->name);
7090 /* Note: if !funcp->body, do not free body_as_string!
7091 * This is a special case of "-F name body" function:
7092 * body_as_string was not malloced! */
7093 if (funcp->body) {
7094 free_pipe_list(funcp->body);
7095# if !BB_MMU
7096 free(funcp->body_as_string);
7097# endif
7098 }
7099 } else {
7100 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7101 cmd->argv[0] = funcp->name;
7102 cmd->group = funcp->body;
7103# if !BB_MMU
7104 cmd->group_as_string = funcp->body_as_string;
7105# endif
7106 }
7107 } else {
7108 debug_printf_exec("remembering new function '%s'\n", name);
7109 funcp = *funcpp = xzalloc(sizeof(*funcp));
7110 /*funcp->next = NULL;*/
7111 }
7112
7113 funcp->name = name;
7114 return funcp;
7115}
7116
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007117# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007118static void unset_func(const char *name)
7119{
7120 struct function **funcpp = find_function_slot(name);
7121 struct function *funcp = *funcpp;
7122
7123 if (funcp != NULL) {
7124 debug_printf_exec("freeing function '%s'\n", funcp->name);
7125 *funcpp = funcp->next;
7126 /* funcp is unlinked now, deleting it.
7127 * Note: if !funcp->body, the function was created by
7128 * "-F name body", do not free ->body_as_string
7129 * and ->name as they were not malloced. */
7130 if (funcp->body) {
7131 free_pipe_list(funcp->body);
7132 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007133# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007134 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007135# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007136 }
7137 free(funcp);
7138 }
7139}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007140# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007141
7142# if BB_MMU
7143#define exec_function(to_free, funcp, argv) \
7144 exec_function(funcp, argv)
7145# endif
7146static void exec_function(char ***to_free,
7147 const struct function *funcp,
7148 char **argv) NORETURN;
7149static void exec_function(char ***to_free,
7150 const struct function *funcp,
7151 char **argv)
7152{
7153# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007154 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007155
7156 argv[0] = G.global_argv[0];
7157 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007158 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007159
7160// Example when we are here: "cmd | func"
7161// func will run with saved-redirect fds open.
7162// $ f() { echo /proc/self/fd/*; }
7163// $ true | f
7164// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7165// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7166// Same in script:
7167// $ . ./SCRIPT
7168// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7169// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7170// They are CLOEXEC so external programs won't see them, but
7171// for "more correctness" we might want to close those extra fds here:
7172//? close_saved_fds_and_FILE_fds();
7173
7174 /* "we are in function, ok to use return" */
7175 G_flag_return_in_progress = -1;
7176 IF_HUSH_LOCAL(G.func_nest_level++;)
7177
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007178 /* On MMU, funcp->body is always non-NULL */
7179 n = run_list(funcp->body);
7180 fflush_all();
7181 _exit(n);
7182# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007183//? close_saved_fds_and_FILE_fds();
7184
7185//TODO: check whether "true | func_with_return" works
7186
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007187 re_execute_shell(to_free,
7188 funcp->body_as_string,
7189 G.global_argv[0],
7190 argv + 1,
7191 NULL);
7192# endif
7193}
7194
7195static int run_function(const struct function *funcp, char **argv)
7196{
7197 int rc;
7198 save_arg_t sv;
7199 smallint sv_flg;
7200
7201 save_and_replace_G_args(&sv, argv);
7202
7203 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007204 sv_flg = G_flag_return_in_progress;
7205 G_flag_return_in_progress = -1;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007206 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007207
7208 /* On MMU, funcp->body is always non-NULL */
7209# if !BB_MMU
7210 if (!funcp->body) {
7211 /* Function defined by -F */
7212 parse_and_run_string(funcp->body_as_string);
7213 rc = G.last_exitcode;
7214 } else
7215# endif
7216 {
7217 rc = run_list(funcp->body);
7218 }
7219
7220# if ENABLE_HUSH_LOCAL
7221 {
7222 struct variable *var;
7223 struct variable **var_pp;
7224
7225 var_pp = &G.top_var;
7226 while ((var = *var_pp) != NULL) {
7227 if (var->func_nest_level < G.func_nest_level) {
7228 var_pp = &var->next;
7229 continue;
7230 }
7231 /* Unexport */
7232 if (var->flg_export)
7233 bb_unsetenv(var->varstr);
7234 /* Remove from global list */
7235 *var_pp = var->next;
7236 /* Free */
7237 if (!var->max_len)
7238 free(var->varstr);
7239 free(var);
7240 }
7241 G.func_nest_level--;
7242 }
7243# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007244 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007245
7246 restore_G_args(&sv, argv);
7247
7248 return rc;
7249}
7250#endif /* ENABLE_HUSH_FUNCTIONS */
7251
7252
7253#if BB_MMU
7254#define exec_builtin(to_free, x, argv) \
7255 exec_builtin(x, argv)
7256#else
7257#define exec_builtin(to_free, x, argv) \
7258 exec_builtin(to_free, argv)
7259#endif
7260static void exec_builtin(char ***to_free,
7261 const struct built_in_command *x,
7262 char **argv) NORETURN;
7263static void exec_builtin(char ***to_free,
7264 const struct built_in_command *x,
7265 char **argv)
7266{
7267#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007268 int rcode;
7269 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007270//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007271 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007272 fflush_all();
7273 _exit(rcode);
7274#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007275 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007276 /* On NOMMU, we must never block!
7277 * Example: { sleep 99 | read line; } & echo Ok
7278 */
7279 re_execute_shell(to_free,
7280 argv[0],
7281 G.global_argv[0],
7282 G.global_argv + 1,
7283 argv);
7284#endif
7285}
7286
7287
7288static void execvp_or_die(char **argv) NORETURN;
7289static void execvp_or_die(char **argv)
7290{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007291 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007292 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007293 /* Don't propagate SIG_IGN to the child */
7294 if (SPECIAL_JOBSTOP_SIGS != 0)
7295 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007296 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007297 e = 2;
7298 if (errno == EACCES) e = 126;
7299 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007300 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007301 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007302}
7303
7304#if ENABLE_HUSH_MODE_X
7305static void dump_cmd_in_x_mode(char **argv)
7306{
7307 if (G_x_mode && argv) {
7308 /* We want to output the line in one write op */
7309 char *buf, *p;
7310 int len;
7311 int n;
7312
7313 len = 3;
7314 n = 0;
7315 while (argv[n])
7316 len += strlen(argv[n++]) + 1;
7317 buf = xmalloc(len);
7318 buf[0] = '+';
7319 p = buf + 1;
7320 n = 0;
7321 while (argv[n])
7322 p += sprintf(p, " %s", argv[n++]);
7323 *p++ = '\n';
7324 *p = '\0';
7325 fputs(buf, stderr);
7326 free(buf);
7327 }
7328}
7329#else
7330# define dump_cmd_in_x_mode(argv) ((void)0)
7331#endif
7332
7333#if BB_MMU
7334#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7335 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7336#define pseudo_exec(nommu_save, command, argv_expanded) \
7337 pseudo_exec(command, argv_expanded)
7338#endif
7339
7340/* Called after [v]fork() in run_pipe, or from builtin_exec.
7341 * Never returns.
7342 * Don't exit() here. If you don't exec, use _exit instead.
7343 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007344 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007345 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007346static void pseudo_exec_argv(nommu_save_t *nommu_save,
7347 char **argv, int assignment_cnt,
7348 char **argv_expanded) NORETURN;
7349static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7350 char **argv, int assignment_cnt,
7351 char **argv_expanded)
7352{
7353 char **new_env;
7354
7355 new_env = expand_assignments(argv, assignment_cnt);
7356 dump_cmd_in_x_mode(new_env);
7357
7358 if (!argv[assignment_cnt]) {
7359 /* Case when we are here: ... | var=val | ...
7360 * (note that we do not exit early, i.e., do not optimize out
7361 * expand_assignments(): think about ... | var=`sleep 1` | ...
7362 */
7363 free_strings(new_env);
7364 _exit(EXIT_SUCCESS);
7365 }
7366
7367#if BB_MMU
7368 set_vars_and_save_old(new_env);
7369 free(new_env); /* optional */
7370 /* we can also destroy set_vars_and_save_old's return value,
7371 * to save memory */
7372#else
7373 nommu_save->new_env = new_env;
7374 nommu_save->old_vars = set_vars_and_save_old(new_env);
7375#endif
7376
7377 if (argv_expanded) {
7378 argv = argv_expanded;
7379 } else {
7380 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7381#if !BB_MMU
7382 nommu_save->argv = argv;
7383#endif
7384 }
7385 dump_cmd_in_x_mode(argv);
7386
7387#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7388 if (strchr(argv[0], '/') != NULL)
7389 goto skip;
7390#endif
7391
Denys Vlasenko75481d32017-07-31 05:27:09 +02007392#if ENABLE_HUSH_FUNCTIONS
7393 /* Check if the command matches any functions (this goes before bltins) */
7394 {
7395 const struct function *funcp = find_function(argv[0]);
7396 if (funcp) {
7397 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7398 }
7399 }
7400#endif
7401
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007402 /* Check if the command matches any of the builtins.
7403 * Depending on context, this might be redundant. But it's
7404 * easier to waste a few CPU cycles than it is to figure out
7405 * if this is one of those cases.
7406 */
7407 {
7408 /* On NOMMU, it is more expensive to re-execute shell
7409 * just in order to run echo or test builtin.
7410 * It's better to skip it here and run corresponding
7411 * non-builtin later. */
7412 const struct built_in_command *x;
7413 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7414 if (x) {
7415 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7416 }
7417 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007418
7419#if ENABLE_FEATURE_SH_STANDALONE
7420 /* Check if the command matches any busybox applets */
7421 {
7422 int a = find_applet_by_name(argv[0]);
7423 if (a >= 0) {
7424# if BB_MMU /* see above why on NOMMU it is not allowed */
7425 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007426 /* Do not leak open fds from opened script files etc.
7427 * Testcase: interactive "ls -l /proc/self/fd"
7428 * should not show tty fd open.
7429 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007430 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007431//FIXME: should also close saved redir fds
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007432 /* Without this, "rm -i FILE" can't be ^C'ed: */
7433 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007434 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007435 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007436 }
7437# endif
7438 /* Re-exec ourselves */
7439 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007440 /* Don't propagate SIG_IGN to the child */
7441 if (SPECIAL_JOBSTOP_SIGS != 0)
7442 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007443 execv(bb_busybox_exec_path, argv);
7444 /* If they called chroot or otherwise made the binary no longer
7445 * executable, fall through */
7446 }
7447 }
7448#endif
7449
7450#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7451 skip:
7452#endif
7453 execvp_or_die(argv);
7454}
7455
7456/* Called after [v]fork() in run_pipe
7457 */
7458static void pseudo_exec(nommu_save_t *nommu_save,
7459 struct command *command,
7460 char **argv_expanded) NORETURN;
7461static void pseudo_exec(nommu_save_t *nommu_save,
7462 struct command *command,
7463 char **argv_expanded)
7464{
7465 if (command->argv) {
7466 pseudo_exec_argv(nommu_save, command->argv,
7467 command->assignment_cnt, argv_expanded);
7468 }
7469
7470 if (command->group) {
7471 /* Cases when we are here:
7472 * ( list )
7473 * { list } &
7474 * ... | ( list ) | ...
7475 * ... | { list } | ...
7476 */
7477#if BB_MMU
7478 int rcode;
7479 debug_printf_exec("pseudo_exec: run_list\n");
7480 reset_traps_to_defaults();
7481 rcode = run_list(command->group);
7482 /* OK to leak memory by not calling free_pipe_list,
7483 * since this process is about to exit */
7484 _exit(rcode);
7485#else
7486 re_execute_shell(&nommu_save->argv_from_re_execing,
7487 command->group_as_string,
7488 G.global_argv[0],
7489 G.global_argv + 1,
7490 NULL);
7491#endif
7492 }
7493
7494 /* Case when we are here: ... | >file */
7495 debug_printf_exec("pseudo_exec'ed null command\n");
7496 _exit(EXIT_SUCCESS);
7497}
7498
7499#if ENABLE_HUSH_JOB
7500static const char *get_cmdtext(struct pipe *pi)
7501{
7502 char **argv;
7503 char *p;
7504 int len;
7505
7506 /* This is subtle. ->cmdtext is created only on first backgrounding.
7507 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7508 * On subsequent bg argv is trashed, but we won't use it */
7509 if (pi->cmdtext)
7510 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007511
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007512 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007513 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007514 pi->cmdtext = xzalloc(1);
7515 return pi->cmdtext;
7516 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007517 len = 0;
7518 do {
7519 len += strlen(*argv) + 1;
7520 } while (*++argv);
7521 p = xmalloc(len);
7522 pi->cmdtext = p;
7523 argv = pi->cmds[0].argv;
7524 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007525 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007526 *p++ = ' ';
7527 } while (*++argv);
7528 p[-1] = '\0';
7529 return pi->cmdtext;
7530}
7531
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007532static void remove_job_from_table(struct pipe *pi)
7533{
7534 struct pipe *prev_pipe;
7535
7536 if (pi == G.job_list) {
7537 G.job_list = pi->next;
7538 } else {
7539 prev_pipe = G.job_list;
7540 while (prev_pipe->next != pi)
7541 prev_pipe = prev_pipe->next;
7542 prev_pipe->next = pi->next;
7543 }
7544 G.last_jobid = 0;
7545 if (G.job_list)
7546 G.last_jobid = G.job_list->jobid;
7547}
7548
7549static void delete_finished_job(struct pipe *pi)
7550{
7551 remove_job_from_table(pi);
7552 free_pipe(pi);
7553}
7554
7555static void clean_up_last_dead_job(void)
7556{
7557 if (G.job_list && !G.job_list->alive_cmds)
7558 delete_finished_job(G.job_list);
7559}
7560
Denys Vlasenko16096292017-07-10 10:00:28 +02007561static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007562{
7563 struct pipe *job, **jobp;
7564 int i;
7565
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007566 clean_up_last_dead_job();
7567
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007568 /* Find the end of the list, and find next job ID to use */
7569 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007570 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007571 while ((job = *jobp) != NULL) {
7572 if (job->jobid > i)
7573 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007574 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007575 }
7576 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007577
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007578 /* Create a new job struct at the end */
7579 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007580 job->next = NULL;
7581 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7582 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7583 for (i = 0; i < pi->num_cmds; i++) {
7584 job->cmds[i].pid = pi->cmds[i].pid;
7585 /* all other fields are not used and stay zero */
7586 }
7587 job->cmdtext = xstrdup(get_cmdtext(pi));
7588
7589 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007590 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007591 G.last_jobid = job->jobid;
7592}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007593#endif /* JOB */
7594
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007595static int job_exited_or_stopped(struct pipe *pi)
7596{
7597 int rcode, i;
7598
7599 if (pi->alive_cmds != pi->stopped_cmds)
7600 return -1;
7601
7602 /* All processes in fg pipe have exited or stopped */
7603 rcode = 0;
7604 i = pi->num_cmds;
7605 while (--i >= 0) {
7606 rcode = pi->cmds[i].cmd_exitcode;
7607 /* usually last process gives overall exitstatus,
7608 * but with "set -o pipefail", last *failed* process does */
7609 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7610 break;
7611 }
7612 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7613 return rcode;
7614}
7615
Denys Vlasenko7e675362016-10-28 21:57:31 +02007616static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007617{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007618#if ENABLE_HUSH_JOB
7619 struct pipe *pi;
7620#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007621 int i, dead;
7622
7623 dead = WIFEXITED(status) || WIFSIGNALED(status);
7624
7625#if DEBUG_JOBS
7626 if (WIFSTOPPED(status))
7627 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7628 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7629 if (WIFSIGNALED(status))
7630 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7631 childpid, WTERMSIG(status), WEXITSTATUS(status));
7632 if (WIFEXITED(status))
7633 debug_printf_jobs("pid %d exited, exitcode %d\n",
7634 childpid, WEXITSTATUS(status));
7635#endif
7636 /* Were we asked to wait for a fg pipe? */
7637 if (fg_pipe) {
7638 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007639
Denys Vlasenko7e675362016-10-28 21:57:31 +02007640 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007641 int rcode;
7642
Denys Vlasenko7e675362016-10-28 21:57:31 +02007643 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7644 if (fg_pipe->cmds[i].pid != childpid)
7645 continue;
7646 if (dead) {
7647 int ex;
7648 fg_pipe->cmds[i].pid = 0;
7649 fg_pipe->alive_cmds--;
7650 ex = WEXITSTATUS(status);
7651 /* bash prints killer signal's name for *last*
7652 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7653 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7654 */
7655 if (WIFSIGNALED(status)) {
7656 int sig = WTERMSIG(status);
7657 if (i == fg_pipe->num_cmds-1)
7658 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7659 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7660 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7661 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7662 * Maybe we need to use sig | 128? */
7663 ex = sig + 128;
7664 }
7665 fg_pipe->cmds[i].cmd_exitcode = ex;
7666 } else {
7667 fg_pipe->stopped_cmds++;
7668 }
7669 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7670 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007671 rcode = job_exited_or_stopped(fg_pipe);
7672 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007673/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7674 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7675 * and "killall -STOP cat" */
7676 if (G_interactive_fd) {
7677#if ENABLE_HUSH_JOB
7678 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02007679 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007680#endif
7681 return rcode;
7682 }
7683 if (fg_pipe->alive_cmds == 0)
7684 return rcode;
7685 }
7686 /* There are still running processes in the fg_pipe */
7687 return -1;
7688 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02007689 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02007690 }
7691
7692#if ENABLE_HUSH_JOB
7693 /* We were asked to wait for bg or orphaned children */
7694 /* No need to remember exitcode in this case */
7695 for (pi = G.job_list; pi; pi = pi->next) {
7696 for (i = 0; i < pi->num_cmds; i++) {
7697 if (pi->cmds[i].pid == childpid)
7698 goto found_pi_and_prognum;
7699 }
7700 }
7701 /* Happens when shell is used as init process (init=/bin/sh) */
7702 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7703 return -1; /* this wasn't a process from fg_pipe */
7704
7705 found_pi_and_prognum:
7706 if (dead) {
7707 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02007708 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007709 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02007710 rcode = 128 + WTERMSIG(status);
7711 pi->cmds[i].cmd_exitcode = rcode;
7712 if (G.last_bg_pid == pi->cmds[i].pid)
7713 G.last_bg_pid_exitcode = rcode;
7714 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007715 pi->alive_cmds--;
7716 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007717 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007718 printf(JOB_STATUS_FORMAT, pi->jobid,
7719 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007720 delete_finished_job(pi);
7721 } else {
7722/*
7723 * bash deletes finished jobs from job table only in interactive mode,
7724 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7725 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7726 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7727 * We only retain one "dead" job, if it's the single job on the list.
7728 * This covers most of real-world scenarios where this is useful.
7729 */
7730 if (pi != G.job_list)
7731 delete_finished_job(pi);
7732 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007733 }
7734 } else {
7735 /* child stopped */
7736 pi->stopped_cmds++;
7737 }
7738#endif
7739 return -1; /* this wasn't a process from fg_pipe */
7740}
7741
7742/* Check to see if any processes have exited -- if they have,
7743 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007744 *
7745 * If non-NULL fg_pipe: wait for its completion or stop.
7746 * Return its exitcode or zero if stopped.
7747 *
7748 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7749 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7750 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7751 * or 0 if no children changed status.
7752 *
7753 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7754 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7755 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007756 */
7757static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7758{
7759 int attributes;
7760 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007761 int rcode = 0;
7762
7763 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7764
7765 attributes = WUNTRACED;
7766 if (fg_pipe == NULL)
7767 attributes |= WNOHANG;
7768
7769 errno = 0;
7770#if ENABLE_HUSH_FAST
7771 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7772//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7773//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7774 /* There was neither fork nor SIGCHLD since last waitpid */
7775 /* Avoid doing waitpid syscall if possible */
7776 if (!G.we_have_children) {
7777 errno = ECHILD;
7778 return -1;
7779 }
7780 if (fg_pipe == NULL) { /* is WNOHANG set? */
7781 /* We have children, but they did not exit
7782 * or stop yet (we saw no SIGCHLD) */
7783 return 0;
7784 }
7785 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7786 }
7787#endif
7788
7789/* Do we do this right?
7790 * bash-3.00# sleep 20 | false
7791 * <ctrl-Z pressed>
7792 * [3]+ Stopped sleep 20 | false
7793 * bash-3.00# echo $?
7794 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7795 * [hush 1.14.0: yes we do it right]
7796 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007797 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007798 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007799#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02007800 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007801 i = G.count_SIGCHLD;
7802#endif
7803 childpid = waitpid(-1, &status, attributes);
7804 if (childpid <= 0) {
7805 if (childpid && errno != ECHILD)
7806 bb_perror_msg("waitpid");
7807#if ENABLE_HUSH_FAST
7808 else { /* Until next SIGCHLD, waitpid's are useless */
7809 G.we_have_children = (childpid == 0);
7810 G.handled_SIGCHLD = i;
7811//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7812 }
7813#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007814 /* ECHILD (no children), or 0 (no change in children status) */
7815 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007816 break;
7817 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007818 rcode = process_wait_result(fg_pipe, childpid, status);
7819 if (rcode >= 0) {
7820 /* fg_pipe exited or stopped */
7821 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007822 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007823 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007824 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007825 rcode = WEXITSTATUS(status);
7826 if (WIFSIGNALED(status))
7827 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007828 if (WIFSTOPPED(status))
7829 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7830 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007831 rcode++;
7832 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007833 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007834 /* This wasn't one of our processes, or */
7835 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007836 } /* while (waitpid succeeds)... */
7837
7838 return rcode;
7839}
7840
7841#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007842static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007843{
7844 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007845 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007846 if (G_saved_tty_pgrp) {
7847 /* Job finished, move the shell to the foreground */
7848 p = getpgrp(); /* our process group id */
7849 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7850 tcsetpgrp(G_interactive_fd, p);
7851 }
7852 return rcode;
7853}
7854#endif
7855
7856/* Start all the jobs, but don't wait for anything to finish.
7857 * See checkjobs().
7858 *
7859 * Return code is normally -1, when the caller has to wait for children
7860 * to finish to determine the exit status of the pipe. If the pipe
7861 * is a simple builtin command, however, the action is done by the
7862 * time run_pipe returns, and the exit code is provided as the
7863 * return value.
7864 *
7865 * Returns -1 only if started some children. IOW: we have to
7866 * mask out retvals of builtins etc with 0xff!
7867 *
7868 * The only case when we do not need to [v]fork is when the pipe
7869 * is single, non-backgrounded, non-subshell command. Examples:
7870 * cmd ; ... { list } ; ...
7871 * cmd && ... { list } && ...
7872 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007873 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007874 * or (if SH_STANDALONE) an applet, and we can run the { list }
7875 * with run_list. If it isn't one of these, we fork and exec cmd.
7876 *
7877 * Cases when we must fork:
7878 * non-single: cmd | cmd
7879 * backgrounded: cmd & { list } &
7880 * subshell: ( list ) [&]
7881 */
7882#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007883#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007884 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7885#endif
7886static int redirect_and_varexp_helper(char ***new_env_p,
7887 struct variable **old_vars_p,
7888 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02007889 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007890 char **argv_expanded)
7891{
7892 /* setup_redirects acts on file descriptors, not FILEs.
7893 * This is perfect for work that comes after exec().
7894 * Is it really safe for inline use? Experimentally,
7895 * things seem to work. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007896 int rcode = setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007897 if (rcode == 0) {
7898 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7899 *new_env_p = new_env;
7900 dump_cmd_in_x_mode(new_env);
7901 dump_cmd_in_x_mode(argv_expanded);
7902 if (old_vars_p)
7903 *old_vars_p = set_vars_and_save_old(new_env);
7904 }
7905 return rcode;
7906}
7907static NOINLINE int run_pipe(struct pipe *pi)
7908{
7909 static const char *const null_ptr = NULL;
7910
7911 int cmd_no;
7912 int next_infd;
7913 struct command *command;
7914 char **argv_expanded;
7915 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02007916 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007917 int rcode;
7918
7919 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7920 debug_enter();
7921
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007922 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7923 * Result should be 3 lines: q w e, qwe, q w e
7924 */
7925 G.ifs = get_local_var_value("IFS");
7926 if (!G.ifs)
7927 G.ifs = defifs;
7928
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007929 IF_HUSH_JOB(pi->pgrp = -1;)
7930 pi->stopped_cmds = 0;
7931 command = &pi->cmds[0];
7932 argv_expanded = NULL;
7933
7934 if (pi->num_cmds != 1
7935 || pi->followup == PIPE_BG
7936 || command->cmd_type == CMD_SUBSHELL
7937 ) {
7938 goto must_fork;
7939 }
7940
7941 pi->alive_cmds = 1;
7942
7943 debug_printf_exec(": group:%p argv:'%s'\n",
7944 command->group, command->argv ? command->argv[0] : "NONE");
7945
7946 if (command->group) {
7947#if ENABLE_HUSH_FUNCTIONS
7948 if (command->cmd_type == CMD_FUNCDEF) {
7949 /* "executing" func () { list } */
7950 struct function *funcp;
7951
7952 funcp = new_function(command->argv[0]);
7953 /* funcp->name is already set to argv[0] */
7954 funcp->body = command->group;
7955# if !BB_MMU
7956 funcp->body_as_string = command->group_as_string;
7957 command->group_as_string = NULL;
7958# endif
7959 command->group = NULL;
7960 command->argv[0] = NULL;
7961 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7962 funcp->parent_cmd = command;
7963 command->child_func = funcp;
7964
7965 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7966 debug_leave();
7967 return EXIT_SUCCESS;
7968 }
7969#endif
7970 /* { list } */
7971 debug_printf("non-subshell group\n");
7972 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007973 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007974 debug_printf_exec(": run_list\n");
7975 rcode = run_list(command->group) & 0xff;
7976 }
7977 restore_redirects(squirrel);
7978 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7979 debug_leave();
7980 debug_printf_exec("run_pipe: return %d\n", rcode);
7981 return rcode;
7982 }
7983
7984 argv = command->argv ? command->argv : (char **) &null_ptr;
7985 {
7986 const struct built_in_command *x;
7987#if ENABLE_HUSH_FUNCTIONS
7988 const struct function *funcp;
7989#else
7990 enum { funcp = 0 };
7991#endif
7992 char **new_env = NULL;
7993 struct variable *old_vars = NULL;
7994
7995 if (argv[command->assignment_cnt] == NULL) {
7996 /* Assignments, but no command */
7997 /* Ensure redirects take effect (that is, create files).
7998 * Try "a=t >file" */
7999#if 0 /* A few cases in testsuite fail with this code. FIXME */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008000 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008001 /* Set shell variables */
8002 if (new_env) {
8003 argv = new_env;
8004 while (*argv) {
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008005 if (set_local_var(*argv, /*flag:*/ 0)) {
8006 /* assignment to readonly var / putenv error? */
8007 rcode = 1;
8008 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008009 argv++;
8010 }
8011 }
8012 /* Redirect error sets $? to 1. Otherwise,
8013 * if evaluating assignment value set $?, retain it.
8014 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8015 if (rcode == 0)
8016 rcode = G.last_exitcode;
8017 /* Exit, _skipping_ variable restoring code: */
8018 goto clean_up_and_ret0;
8019
8020#else /* Older, bigger, but more correct code */
8021
Denys Vlasenko2db74612017-07-07 22:07:28 +02008022 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008023 restore_redirects(squirrel);
8024 /* Set shell variables */
8025 if (G_x_mode)
8026 bb_putchar_stderr('+');
8027 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02008028 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008029 if (G_x_mode)
8030 fprintf(stderr, " %s", p);
8031 debug_printf_exec("set shell var:'%s'->'%s'\n",
8032 *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008033 if (set_local_var(p, /*flag:*/ 0)) {
8034 /* assignment to readonly var / putenv error? */
8035 rcode = 1;
8036 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008037 argv++;
8038 }
8039 if (G_x_mode)
8040 bb_putchar_stderr('\n');
8041 /* Redirect error sets $? to 1. Otherwise,
8042 * if evaluating assignment value set $?, retain it.
8043 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8044 if (rcode == 0)
8045 rcode = G.last_exitcode;
8046 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8047 debug_leave();
8048 debug_printf_exec("run_pipe: return %d\n", rcode);
8049 return rcode;
8050#endif
8051 }
8052
8053 /* Expand the rest into (possibly) many strings each */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01008054#if BASH_TEST2
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008055 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008056 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008057 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008058#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008059 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008060 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8061 }
8062
8063 /* if someone gives us an empty string: `cmd with empty output` */
8064 if (!argv_expanded[0]) {
8065 free(argv_expanded);
8066 debug_leave();
8067 return G.last_exitcode;
8068 }
8069
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008070#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko75481d32017-07-31 05:27:09 +02008071 /* Check if argv[0] matches any functions (this goes before bltins) */
8072 funcp = find_function(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008073#endif
Denys Vlasenko75481d32017-07-31 05:27:09 +02008074 x = NULL;
8075 if (!funcp)
8076 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008077 if (x || funcp) {
8078 if (!funcp) {
8079 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8080 debug_printf("exec with redirects only\n");
8081 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008082 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008083 goto clean_up_and_ret1;
8084 }
8085 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02008086 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008087 if (rcode == 0) {
8088 if (!funcp) {
8089 debug_printf_exec(": builtin '%s' '%s'...\n",
8090 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008091 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008092 rcode = x->b_function(argv_expanded) & 0xff;
8093 fflush_all();
8094 }
8095#if ENABLE_HUSH_FUNCTIONS
8096 else {
8097# if ENABLE_HUSH_LOCAL
8098 struct variable **sv;
8099 sv = G.shadowed_vars_pp;
8100 G.shadowed_vars_pp = &old_vars;
8101# endif
8102 debug_printf_exec(": function '%s' '%s'...\n",
8103 funcp->name, argv_expanded[1]);
8104 rcode = run_function(funcp, argv_expanded) & 0xff;
8105# if ENABLE_HUSH_LOCAL
8106 G.shadowed_vars_pp = sv;
8107# endif
8108 }
8109#endif
8110 }
8111 clean_up_and_ret:
8112 unset_vars(new_env);
8113 add_vars(old_vars);
8114/* clean_up_and_ret0: */
8115 restore_redirects(squirrel);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008116 /*
8117 * Try "usleep 99999999" + ^C + "echo $?"
8118 * with FEATURE_SH_NOFORK=y.
8119 */
8120 if (!funcp) {
8121 /* It was builtin or nofork.
8122 * if this would be a real fork/execed program,
8123 * it should have died if a fatal sig was received.
8124 * But OTOH, there was no separate process,
8125 * the sig was sent to _shell_, not to non-existing
8126 * child.
8127 * Let's just handle ^C only, this one is obvious:
8128 * we aren't ok with exitcode 0 when ^C was pressed
8129 * during builtin/nofork.
8130 */
8131 if (sigismember(&G.pending_set, SIGINT))
8132 rcode = 128 + SIGINT;
8133 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008134 clean_up_and_ret1:
8135 free(argv_expanded);
8136 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8137 debug_leave();
8138 debug_printf_exec("run_pipe return %d\n", rcode);
8139 return rcode;
8140 }
8141
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008142 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008143 int n = find_applet_by_name(argv_expanded[0]);
8144 if (n >= 0 && APPLET_IS_NOFORK(n)) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02008145 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008146 if (rcode == 0) {
8147 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8148 argv_expanded[0], argv_expanded[1]);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008149 /*
8150 * Note: signals (^C) can't interrupt here.
8151 * We remember them and they will be acted upon
8152 * after applet returns.
8153 * This makes applets which can run for a long time
8154 * and/or wait for user input ineligible for NOFORK:
8155 * for example, "yes" or "rm" (rm -i waits for input).
8156 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008157 rcode = run_nofork_applet(n, argv_expanded);
8158 }
8159 goto clean_up_and_ret;
8160 }
8161 }
8162 /* It is neither builtin nor applet. We must fork. */
8163 }
8164
8165 must_fork:
8166 /* NB: argv_expanded may already be created, and that
8167 * might include `cmd` runs! Do not rerun it! We *must*
8168 * use argv_expanded if it's non-NULL */
8169
8170 /* Going to fork a child per each pipe member */
8171 pi->alive_cmds = 0;
8172 next_infd = 0;
8173
8174 cmd_no = 0;
8175 while (cmd_no < pi->num_cmds) {
8176 struct fd_pair pipefds;
8177#if !BB_MMU
8178 volatile nommu_save_t nommu_save;
8179 nommu_save.new_env = NULL;
8180 nommu_save.old_vars = NULL;
8181 nommu_save.argv = NULL;
8182 nommu_save.argv_from_re_execing = NULL;
8183#endif
8184 command = &pi->cmds[cmd_no];
8185 cmd_no++;
8186 if (command->argv) {
8187 debug_printf_exec(": pipe member '%s' '%s'...\n",
8188 command->argv[0], command->argv[1]);
8189 } else {
8190 debug_printf_exec(": pipe member with no argv\n");
8191 }
8192
8193 /* pipes are inserted between pairs of commands */
8194 pipefds.rd = 0;
8195 pipefds.wr = 1;
8196 if (cmd_no < pi->num_cmds)
8197 xpiped_pair(pipefds);
8198
8199 command->pid = BB_MMU ? fork() : vfork();
8200 if (!command->pid) { /* child */
8201#if ENABLE_HUSH_JOB
8202 disable_restore_tty_pgrp_on_exit();
8203 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8204
8205 /* Every child adds itself to new process group
8206 * with pgid == pid_of_first_child_in_pipe */
8207 if (G.run_list_level == 1 && G_interactive_fd) {
8208 pid_t pgrp;
8209 pgrp = pi->pgrp;
8210 if (pgrp < 0) /* true for 1st process only */
8211 pgrp = getpid();
8212 if (setpgid(0, pgrp) == 0
8213 && pi->followup != PIPE_BG
8214 && G_saved_tty_pgrp /* we have ctty */
8215 ) {
8216 /* We do it in *every* child, not just first,
8217 * to avoid races */
8218 tcsetpgrp(G_interactive_fd, pgrp);
8219 }
8220 }
8221#endif
8222 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8223 /* 1st cmd in backgrounded pipe
8224 * should have its stdin /dev/null'ed */
8225 close(0);
8226 if (open(bb_dev_null, O_RDONLY))
8227 xopen("/", O_RDONLY);
8228 } else {
8229 xmove_fd(next_infd, 0);
8230 }
8231 xmove_fd(pipefds.wr, 1);
8232 if (pipefds.rd > 1)
8233 close(pipefds.rd);
8234 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008235 * and the pipe fd (fd#1) is available for dup'ing:
8236 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8237 * of cmd1 goes into pipe.
8238 */
8239 if (setup_redirects(command, NULL)) {
8240 /* Happens when redir file can't be opened:
8241 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8242 * FOO
8243 * hush: can't open '/qwe/rty': No such file or directory
8244 * BAZ
8245 * (echo BAR is not executed, it hits _exit(1) below)
8246 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008247 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008248 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008249
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008250 /* Stores to nommu_save list of env vars putenv'ed
8251 * (NOMMU, on MMU we don't need that) */
8252 /* cast away volatility... */
8253 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8254 /* pseudo_exec() does not return */
8255 }
8256
8257 /* parent or error */
8258#if ENABLE_HUSH_FAST
8259 G.count_SIGCHLD++;
8260//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8261#endif
8262 enable_restore_tty_pgrp_on_exit();
8263#if !BB_MMU
8264 /* Clean up after vforked child */
8265 free(nommu_save.argv);
8266 free(nommu_save.argv_from_re_execing);
8267 unset_vars(nommu_save.new_env);
8268 add_vars(nommu_save.old_vars);
8269#endif
8270 free(argv_expanded);
8271 argv_expanded = NULL;
8272 if (command->pid < 0) { /* [v]fork failed */
8273 /* Clearly indicate, was it fork or vfork */
8274 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8275 } else {
8276 pi->alive_cmds++;
8277#if ENABLE_HUSH_JOB
8278 /* Second and next children need to know pid of first one */
8279 if (pi->pgrp < 0)
8280 pi->pgrp = command->pid;
8281#endif
8282 }
8283
8284 if (cmd_no > 1)
8285 close(next_infd);
8286 if (cmd_no < pi->num_cmds)
8287 close(pipefds.wr);
8288 /* Pass read (output) pipe end to next iteration */
8289 next_infd = pipefds.rd;
8290 }
8291
8292 if (!pi->alive_cmds) {
8293 debug_leave();
8294 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8295 return 1;
8296 }
8297
8298 debug_leave();
8299 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8300 return -1;
8301}
8302
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008303/* NB: called by pseudo_exec, and therefore must not modify any
8304 * global data until exec/_exit (we can be a child after vfork!) */
8305static int run_list(struct pipe *pi)
8306{
8307#if ENABLE_HUSH_CASE
8308 char *case_word = NULL;
8309#endif
8310#if ENABLE_HUSH_LOOPS
8311 struct pipe *loop_top = NULL;
8312 char **for_lcur = NULL;
8313 char **for_list = NULL;
8314#endif
8315 smallint last_followup;
8316 smalluint rcode;
8317#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8318 smalluint cond_code = 0;
8319#else
8320 enum { cond_code = 0 };
8321#endif
8322#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008323 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008324 smallint last_rword; /* ditto */
8325#endif
8326
8327 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8328 debug_enter();
8329
8330#if ENABLE_HUSH_LOOPS
8331 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008332 {
8333 struct pipe *cpipe;
8334 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8335 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8336 continue;
8337 /* current word is FOR or IN (BOLD in comments below) */
8338 if (cpipe->next == NULL) {
8339 syntax_error("malformed for");
8340 debug_leave();
8341 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8342 return 1;
8343 }
8344 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8345 if (cpipe->next->res_word == RES_DO)
8346 continue;
8347 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8348 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8349 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8350 ) {
8351 syntax_error("malformed for");
8352 debug_leave();
8353 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8354 return 1;
8355 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008356 }
8357 }
8358#endif
8359
8360 /* Past this point, all code paths should jump to ret: label
8361 * in order to return, no direct "return" statements please.
8362 * This helps to ensure that no memory is leaked. */
8363
8364#if ENABLE_HUSH_JOB
8365 G.run_list_level++;
8366#endif
8367
8368#if HAS_KEYWORDS
8369 rword = RES_NONE;
8370 last_rword = RES_XXXX;
8371#endif
8372 last_followup = PIPE_SEQ;
8373 rcode = G.last_exitcode;
8374
8375 /* Go through list of pipes, (maybe) executing them. */
8376 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008377 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008378 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008379
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008380 if (G.flag_SIGINT)
8381 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008382 if (G_flag_return_in_progress == 1)
8383 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008384
8385 IF_HAS_KEYWORDS(rword = pi->res_word;)
8386 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8387 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008388
8389 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008390 if (
8391#if ENABLE_HUSH_IF
8392 rword == RES_IF || rword == RES_ELIF ||
8393#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008394 pi->followup != PIPE_SEQ
8395 ) {
8396 G.errexit_depth++;
8397 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008398#if ENABLE_HUSH_LOOPS
8399 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8400 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8401 ) {
8402 /* start of a loop: remember where loop starts */
8403 loop_top = pi;
8404 G.depth_of_loop++;
8405 }
8406#endif
8407 /* Still in the same "if...", "then..." or "do..." branch? */
8408 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8409 if ((rcode == 0 && last_followup == PIPE_OR)
8410 || (rcode != 0 && last_followup == PIPE_AND)
8411 ) {
8412 /* It is "<true> || CMD" or "<false> && CMD"
8413 * and we should not execute CMD */
8414 debug_printf_exec("skipped cmd because of || or &&\n");
8415 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008416 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008417 }
8418 }
8419 last_followup = pi->followup;
8420 IF_HAS_KEYWORDS(last_rword = rword;)
8421#if ENABLE_HUSH_IF
8422 if (cond_code) {
8423 if (rword == RES_THEN) {
8424 /* if false; then ... fi has exitcode 0! */
8425 G.last_exitcode = rcode = EXIT_SUCCESS;
8426 /* "if <false> THEN cmd": skip cmd */
8427 continue;
8428 }
8429 } else {
8430 if (rword == RES_ELSE || rword == RES_ELIF) {
8431 /* "if <true> then ... ELSE/ELIF cmd":
8432 * skip cmd and all following ones */
8433 break;
8434 }
8435 }
8436#endif
8437#if ENABLE_HUSH_LOOPS
8438 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8439 if (!for_lcur) {
8440 /* first loop through for */
8441
8442 static const char encoded_dollar_at[] ALIGN1 = {
8443 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8444 }; /* encoded representation of "$@" */
8445 static const char *const encoded_dollar_at_argv[] = {
8446 encoded_dollar_at, NULL
8447 }; /* argv list with one element: "$@" */
8448 char **vals;
8449
8450 vals = (char**)encoded_dollar_at_argv;
8451 if (pi->next->res_word == RES_IN) {
8452 /* if no variable values after "in" we skip "for" */
8453 if (!pi->next->cmds[0].argv) {
8454 G.last_exitcode = rcode = EXIT_SUCCESS;
8455 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8456 break;
8457 }
8458 vals = pi->next->cmds[0].argv;
8459 } /* else: "for var; do..." -> assume "$@" list */
8460 /* create list of variable values */
8461 debug_print_strings("for_list made from", vals);
8462 for_list = expand_strvec_to_strvec(vals);
8463 for_lcur = for_list;
8464 debug_print_strings("for_list", for_list);
8465 }
8466 if (!*for_lcur) {
8467 /* "for" loop is over, clean up */
8468 free(for_list);
8469 for_list = NULL;
8470 for_lcur = NULL;
8471 break;
8472 }
8473 /* Insert next value from for_lcur */
8474 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008475 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008476 continue;
8477 }
8478 if (rword == RES_IN) {
8479 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8480 }
8481 if (rword == RES_DONE) {
8482 continue; /* "done" has no cmds too */
8483 }
8484#endif
8485#if ENABLE_HUSH_CASE
8486 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008487 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008488 case_word = expand_strvec_to_string(pi->cmds->argv);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008489 unbackslash(case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008490 continue;
8491 }
8492 if (rword == RES_MATCH) {
8493 char **argv;
8494
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008495 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008496 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8497 break;
8498 /* all prev words didn't match, does this one match? */
8499 argv = pi->cmds->argv;
8500 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008501 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008502 /* TODO: which FNM_xxx flags to use? */
8503 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008504 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008505 free(pattern);
8506 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008507 free(case_word);
8508 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008509 break;
8510 }
8511 argv++;
8512 }
8513 continue;
8514 }
8515 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008516 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008517 if (cond_code != 0)
8518 continue; /* not matched yet, skip this pipe */
8519 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008520 if (rword == RES_ESAC) {
8521 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8522 if (case_word) {
8523 /* "case" did not match anything: still set $? (to 0) */
8524 G.last_exitcode = rcode = EXIT_SUCCESS;
8525 }
8526 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008527#endif
8528 /* Just pressing <enter> in shell should check for jobs.
8529 * OTOH, in non-interactive shell this is useless
8530 * and only leads to extra job checks */
8531 if (pi->num_cmds == 0) {
8532 if (G_interactive_fd)
8533 goto check_jobs_and_continue;
8534 continue;
8535 }
8536
8537 /* After analyzing all keywords and conditions, we decided
8538 * to execute this pipe. NB: have to do checkjobs(NULL)
8539 * after run_pipe to collect any background children,
8540 * even if list execution is to be stopped. */
8541 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008542#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008543 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008544#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008545 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8546 if (r != -1) {
8547 /* We ran a builtin, function, or group.
8548 * rcode is already known
8549 * and we don't need to wait for anything. */
8550 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8551 G.last_exitcode = rcode;
8552 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008553#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008554 /* Was it "break" or "continue"? */
8555 if (G.flag_break_continue) {
8556 smallint fbc = G.flag_break_continue;
8557 /* We might fall into outer *loop*,
8558 * don't want to break it too */
8559 if (loop_top) {
8560 G.depth_break_continue--;
8561 if (G.depth_break_continue == 0)
8562 G.flag_break_continue = 0;
8563 /* else: e.g. "continue 2" should *break* once, *then* continue */
8564 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8565 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008566 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008567 break;
8568 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008569 /* "continue": simulate end of loop */
8570 rword = RES_DONE;
8571 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008572 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008573#endif
8574 if (G_flag_return_in_progress == 1) {
8575 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8576 break;
8577 }
8578 } else if (pi->followup == PIPE_BG) {
8579 /* What does bash do with attempts to background builtins? */
8580 /* even bash 3.2 doesn't do that well with nested bg:
8581 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8582 * I'm NOT treating inner &'s as jobs */
8583#if ENABLE_HUSH_JOB
8584 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008585 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008586#endif
8587 /* Last command's pid goes to $! */
8588 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008589 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008590 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008591/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008592 rcode = EXIT_SUCCESS;
8593 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008594 } else {
8595#if ENABLE_HUSH_JOB
8596 if (G.run_list_level == 1 && G_interactive_fd) {
8597 /* Waits for completion, then fg's main shell */
8598 rcode = checkjobs_and_fg_shell(pi);
8599 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008600 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008601 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008602#endif
8603 /* This one just waits for completion */
8604 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8605 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8606 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008607 G.last_exitcode = rcode;
8608 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008609 }
8610
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008611 /* Handle "set -e" */
8612 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8613 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8614 if (G.errexit_depth == 0)
8615 hush_exit(rcode);
8616 }
8617 G.errexit_depth = sv_errexit_depth;
8618
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008619 /* Analyze how result affects subsequent commands */
8620#if ENABLE_HUSH_IF
8621 if (rword == RES_IF || rword == RES_ELIF)
8622 cond_code = rcode;
8623#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008624 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008625 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008626 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008627#if ENABLE_HUSH_LOOPS
8628 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008629 if (pi->next
8630 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008631 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008632 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008633 if (rword == RES_WHILE) {
8634 if (rcode) {
8635 /* "while false; do...done" - exitcode 0 */
8636 G.last_exitcode = rcode = EXIT_SUCCESS;
8637 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008638 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008639 }
8640 }
8641 if (rword == RES_UNTIL) {
8642 if (!rcode) {
8643 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008644 break;
8645 }
8646 }
8647 }
8648#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008649 } /* for (pi) */
8650
8651#if ENABLE_HUSH_JOB
8652 G.run_list_level--;
8653#endif
8654#if ENABLE_HUSH_LOOPS
8655 if (loop_top)
8656 G.depth_of_loop--;
8657 free(for_list);
8658#endif
8659#if ENABLE_HUSH_CASE
8660 free(case_word);
8661#endif
8662 debug_leave();
8663 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8664 return rcode;
8665}
8666
8667/* Select which version we will use */
8668static int run_and_free_list(struct pipe *pi)
8669{
8670 int rcode = 0;
8671 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008672 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008673 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8674 rcode = run_list(pi);
8675 }
8676 /* free_pipe_list has the side effect of clearing memory.
8677 * In the long run that function can be merged with run_list,
8678 * but doing that now would hobble the debugging effort. */
8679 free_pipe_list(pi);
8680 debug_printf_exec("run_and_free_list return %d\n", rcode);
8681 return rcode;
8682}
8683
8684
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008685static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008686{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008687 sighandler_t old_handler;
8688 unsigned sig = 0;
8689 while ((mask >>= 1) != 0) {
8690 sig++;
8691 if (!(mask & 1))
8692 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008693 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008694 /* POSIX allows shell to re-enable SIGCHLD
8695 * even if it was SIG_IGN on entry.
8696 * Therefore we skip IGN check for it:
8697 */
8698 if (sig == SIGCHLD)
8699 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02008700 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8701 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8702 */
8703 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008704 if (old_handler == SIG_IGN) {
8705 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008706 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008707#if ENABLE_HUSH_TRAP
8708 if (!G_traps)
8709 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8710 free(G_traps[sig]);
8711 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8712#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008713 }
8714 }
8715}
8716
8717/* Called a few times only (or even once if "sh -c") */
8718static void install_special_sighandlers(void)
8719{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008720 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008721
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008722 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008723 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008724 if (G_interactive_fd) {
8725 mask |= SPECIAL_INTERACTIVE_SIGS;
8726 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008727 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008728 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008729 /* Careful, do not re-install handlers we already installed */
8730 if (G.special_sig_mask != mask) {
8731 unsigned diff = mask & ~G.special_sig_mask;
8732 G.special_sig_mask = mask;
8733 install_sighandlers(diff);
8734 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008735}
8736
8737#if ENABLE_HUSH_JOB
8738/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008739/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008740static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008741{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008742 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008743
8744 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008745 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008746 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8747 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008748 + (1 << SIGBUS ) * HUSH_DEBUG
8749 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008750 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008751 + (1 << SIGABRT)
8752 /* bash 3.2 seems to handle these just like 'fatal' ones */
8753 + (1 << SIGPIPE)
8754 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008755 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008756 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008757 * we never want to restore pgrp on exit, and this fn is not called
8758 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008759 /*+ (1 << SIGHUP )*/
8760 /*+ (1 << SIGTERM)*/
8761 /*+ (1 << SIGINT )*/
8762 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008763 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008764
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008765 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008766}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00008767#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00008768
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008769static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00008770{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008771 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008772 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008773 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008774 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008775 break;
8776 case 'x':
8777 IF_HUSH_MODE_X(G_x_mode = state;)
8778 break;
8779 case 'o':
8780 if (!o_opt) {
8781 /* "set -+o" without parameter.
8782 * in bash, set -o produces this output:
8783 * pipefail off
8784 * and set +o:
8785 * set +o pipefail
8786 * We always use the second form.
8787 */
8788 const char *p = o_opt_strings;
8789 idx = 0;
8790 while (*p) {
8791 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8792 idx++;
8793 p += strlen(p) + 1;
8794 }
8795 break;
8796 }
8797 idx = index_in_strings(o_opt_strings, o_opt);
8798 if (idx >= 0) {
8799 G.o_opt[idx] = state;
8800 break;
8801 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008802 case 'e':
8803 G.o_opt[OPT_O_ERREXIT] = state;
8804 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008805 default:
8806 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008807 }
8808 return EXIT_SUCCESS;
8809}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008810
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00008811int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00008812int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00008813{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008814 enum {
8815 OPT_login = (1 << 0),
8816 };
8817 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00008818 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008819 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008820 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008821 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008822 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00008823
Denis Vlasenko574f2f42008-02-27 18:41:59 +00008824 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02008825 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008826 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008827
Denys Vlasenko10c01312011-05-11 11:49:21 +02008828#if ENABLE_HUSH_FAST
8829 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8830#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008831#if !BB_MMU
8832 G.argv0_for_re_execing = argv[0];
8833#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008834 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008835 shell_ver = xzalloc(sizeof(*shell_ver));
8836 shell_ver->flg_export = 1;
8837 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02008838 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02008839 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008840 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02008841 /* Create shell local variables from the values
8842 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00008843 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008844 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008845 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008846 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008847 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008848 if (e) while (*e) {
8849 char *value = strchr(*e, '=');
8850 if (value) { /* paranoia */
8851 cur_var->next = xzalloc(sizeof(*cur_var));
8852 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008853 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008854 cur_var->max_len = strlen(*e);
8855 cur_var->flg_export = 1;
8856 }
8857 e++;
8858 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008859 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008860 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8861 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008862
8863 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008864 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008865
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01008866#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008867 /* Set (but not export) HOSTNAME unless already set */
8868 if (!get_local_var_value("HOSTNAME")) {
8869 struct utsname uts;
8870 uname(&uts);
8871 set_local_var_from_halves("HOSTNAME", uts.nodename);
8872 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008873 /* bash also exports SHLVL and _,
8874 * and sets (but doesn't export) the following variables:
8875 * BASH=/bin/bash
8876 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8877 * BASH_VERSION='3.2.0(1)-release'
8878 * HOSTTYPE=i386
8879 * MACHTYPE=i386-pc-linux-gnu
8880 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008881 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008882 * EUID=<NNNNN>
8883 * UID=<NNNNN>
8884 * GROUPS=()
8885 * LINES=<NNN>
8886 * COLUMNS=<NNN>
8887 * BASH_ARGC=()
8888 * BASH_ARGV=()
8889 * BASH_LINENO=()
8890 * BASH_SOURCE=()
8891 * DIRSTACK=()
8892 * PIPESTATUS=([0]="0")
8893 * HISTFILE=/<xxx>/.bash_history
8894 * HISTFILESIZE=500
8895 * HISTSIZE=500
8896 * MAILCHECK=60
8897 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8898 * SHELL=/bin/bash
8899 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8900 * TERM=dumb
8901 * OPTERR=1
8902 * OPTIND=1
8903 * IFS=$' \t\n'
8904 * PS1='\s-\v\$ '
8905 * PS2='> '
8906 * PS4='+ '
8907 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008908#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008909
Denis Vlasenko38f63192007-01-22 09:03:07 +00008910#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008911 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008912#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008913
Eric Andersen94ac2442001-05-22 19:05:18 +00008914 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008915 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008916
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008917 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008918
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008919 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008920 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008921 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008922 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008923 * in order to intercept (more) signals.
8924 */
8925
8926 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008927 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008928 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008929 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008930 while (1) {
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008931 opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008932#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00008933 "<:$:R:V:"
8934# if ENABLE_HUSH_FUNCTIONS
8935 "F:"
8936# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008937#endif
8938 );
8939 if (opt <= 0)
8940 break;
Eric Andersen25f27032001-04-26 23:22:31 +00008941 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008942 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008943 /* Possibilities:
8944 * sh ... -c 'script'
8945 * sh ... -c 'script' ARG0 [ARG1...]
8946 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01008947 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008948 * "" needs to be replaced with NULL
8949 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01008950 * Note: the form without ARG0 never happens:
8951 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008952 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02008953 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008954 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008955 G.root_ppid = getppid();
8956 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008957 G.global_argv = argv + optind;
8958 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008959 if (builtin_argc) {
8960 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8961 const struct built_in_command *x;
8962
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008963 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008964 x = find_builtin(optarg);
8965 if (x) { /* paranoia */
8966 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8967 G.global_argv += builtin_argc;
8968 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008969 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01008970 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008971 }
8972 goto final_return;
8973 }
8974 if (!G.global_argv[0]) {
8975 /* -c 'script' (no params): prevent empty $0 */
8976 G.global_argv--; /* points to argv[i] of 'script' */
8977 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02008978 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008979 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008980 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008981 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008982 goto final_return;
8983 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00008984 /* Well, we cannot just declare interactiveness,
8985 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008986 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008987 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008988 case 's':
8989 /* "-s" means "read from stdin", but this is how we always
8990 * operate, so simply do nothing here. */
8991 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008992 case 'l':
8993 flags |= OPT_login;
8994 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008995#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008996 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02008997 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008998 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008999 case '$': {
9000 unsigned long long empty_trap_mask;
9001
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009002 G.root_pid = bb_strtou(optarg, &optarg, 16);
9003 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009004 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9005 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009006 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9007 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009008 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009009 optarg++;
9010 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009011 optarg++;
9012 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9013 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009014 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009015 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009016# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009017 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009018 for (sig = 1; sig < NSIG; sig++) {
9019 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009020 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009021 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009022 }
9023 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009024# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009025 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009026# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009027 optarg++;
9028 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009029# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009030 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009031 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009032 case 'R':
9033 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009034 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009035 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009036# if ENABLE_HUSH_FUNCTIONS
9037 case 'F': {
9038 struct function *funcp = new_function(optarg);
9039 /* funcp->name is already set to optarg */
9040 /* funcp->body is set to NULL. It's a special case. */
9041 funcp->body_as_string = argv[optind];
9042 optind++;
9043 break;
9044 }
9045# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009046#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009047 case 'n':
9048 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009049 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009050 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009051 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009052 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009053#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009054 fprintf(stderr, "Usage: sh [FILE]...\n"
9055 " or: sh -c command [args]...\n\n");
9056 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009057#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009058 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009059#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009060 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009061 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009062
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009063 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9064 G.global_argc = argc - (optind - 1);
9065 G.global_argv = argv + (optind - 1);
9066 G.global_argv[0] = argv[0];
9067
Denys Vlasenkodea47882009-10-09 15:40:49 +02009068 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009069 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009070 G.root_ppid = getppid();
9071 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009072
9073 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009074 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009075 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009076 debug_printf("sourcing /etc/profile\n");
9077 input = fopen_for_read("/etc/profile");
9078 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009079 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009080 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009081 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009082 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009083 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009084 /* bash: after sourcing /etc/profile,
9085 * tries to source (in the given order):
9086 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009087 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009088 * bash also sources ~/.bash_logout on exit.
9089 * If called as sh, skips .bash_XXX files.
9090 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009091 }
9092
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009093 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009094 FILE *input;
9095 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009096 * "bash <script>" (which is never interactive (unless -i?))
9097 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009098 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009099 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009100 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009101 G.global_argc--;
9102 G.global_argv++;
9103 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009104 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009105 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009106 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009107 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009108 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009109 parse_and_run_file(input);
9110#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009111 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009112#endif
9113 goto final_return;
9114 }
9115
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009116 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009117 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009118 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009119
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009120 /* A shell is interactive if the '-i' flag was given,
9121 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009122 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009123 * no arguments remaining or the -s flag given
9124 * standard input is a terminal
9125 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009126 * Refer to Posix.2, the description of the 'sh' utility.
9127 */
9128#if ENABLE_HUSH_JOB
9129 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009130 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9131 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9132 if (G_saved_tty_pgrp < 0)
9133 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009134
9135 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009136 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009137 if (G_interactive_fd < 0) {
9138 /* try to dup to any fd */
9139 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009140 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009141 /* give up */
9142 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009143 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009144 }
9145 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009146// TODO: track & disallow any attempts of user
9147// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009148 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009149 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009150 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009151 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009152
Mike Frysinger38478a62009-05-20 04:48:06 -04009153 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009154 /* If we were run as 'hush &', sleep until we are
9155 * in the foreground (tty pgrp == our pgrp).
9156 * If we get started under a job aware app (like bash),
9157 * make sure we are now in charge so we don't fight over
9158 * who gets the foreground */
9159 while (1) {
9160 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009161 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9162 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009163 break;
9164 /* send TTIN to ourself (should stop us) */
9165 kill(- shell_pgrp, SIGTTIN);
9166 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009167 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009168
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009169 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009170 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009171
Mike Frysinger38478a62009-05-20 04:48:06 -04009172 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009173 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009174 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009175 /* Put ourselves in our own process group
9176 * (bash, too, does this only if ctty is available) */
9177 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9178 /* Grab control of the terminal */
9179 tcsetpgrp(G_interactive_fd, getpid());
9180 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009181 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009182
9183# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9184 {
9185 const char *hp = get_local_var_value("HISTFILE");
9186 if (!hp) {
9187 hp = get_local_var_value("HOME");
9188 if (hp)
9189 hp = concat_path_file(hp, ".hush_history");
9190 } else {
9191 hp = xstrdup(hp);
9192 }
9193 if (hp) {
9194 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009195 //set_local_var(xasprintf("HISTFILE=%s", ...));
9196 }
9197# if ENABLE_FEATURE_SH_HISTFILESIZE
9198 hp = get_local_var_value("HISTFILESIZE");
9199 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9200# endif
9201 }
9202# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009203 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009204 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009205 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009206#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009207 /* No job control compiled in, only prompt/line editing */
9208 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02009209 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009210 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009211 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009212 G_interactive_fd = dup(STDIN_FILENO);
9213 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009214 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009215 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009216 }
9217 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009218 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009219 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009220 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009221 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009222#else
9223 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009224 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009225#endif
9226 /* bash:
9227 * if interactive but not a login shell, sources ~/.bashrc
9228 * (--norc turns this off, --rcfile <file> overrides)
9229 */
9230
9231 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009232 /* note: ash and hush share this string */
9233 printf("\n\n%s %s\n"
9234 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9235 "\n",
9236 bb_banner,
9237 "hush - the humble shell"
9238 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009239 }
9240
Denis Vlasenkof9375282009-04-05 19:13:39 +00009241 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009242
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009243 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009244 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009245}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009246
9247
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009248/*
9249 * Built-ins
9250 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009251static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009252{
9253 return 0;
9254}
9255
Denys Vlasenko265062d2017-01-10 15:13:30 +01009256#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009257static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009258{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009259 int argc = string_array_len(argv);
9260 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009261}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009262#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009263#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009264static int FAST_FUNC builtin_test(char **argv)
9265{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009266 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009267}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009268#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009269#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009270static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009271{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009272 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009273}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009274#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009275#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009276static int FAST_FUNC builtin_printf(char **argv)
9277{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009278 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009279}
9280#endif
9281
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009282#if ENABLE_HUSH_HELP
9283static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9284{
9285 const struct built_in_command *x;
9286
9287 printf(
9288 "Built-in commands:\n"
9289 "------------------\n");
9290 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9291 if (x->b_descr)
9292 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9293 }
9294 return EXIT_SUCCESS;
9295}
9296#endif
9297
9298#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9299static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9300{
9301 show_history(G.line_input_state);
9302 return EXIT_SUCCESS;
9303}
9304#endif
9305
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009306static char **skip_dash_dash(char **argv)
9307{
9308 argv++;
9309 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9310 argv++;
9311 return argv;
9312}
9313
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009314static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009315{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009316 const char *newdir;
9317
9318 argv = skip_dash_dash(argv);
9319 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009320 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009321 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009322 * bash says "bash: cd: HOME not set" and does nothing
9323 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009324 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009325 const char *home = get_local_var_value("HOME");
9326 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009327 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009328 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009329 /* Mimic bash message exactly */
9330 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009331 return EXIT_FAILURE;
9332 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009333 /* Read current dir (get_cwd(1) is inside) and set PWD.
9334 * Note: do not enforce exporting. If PWD was unset or unexported,
9335 * set it again, but do not export. bash does the same.
9336 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009337 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009338 return EXIT_SUCCESS;
9339}
9340
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009341static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9342{
9343 puts(get_cwd(0));
9344 return EXIT_SUCCESS;
9345}
9346
9347static int FAST_FUNC builtin_eval(char **argv)
9348{
9349 int rcode = EXIT_SUCCESS;
9350
9351 argv = skip_dash_dash(argv);
9352 if (*argv) {
9353 char *str = expand_strvec_to_string(argv);
9354 /* bash:
9355 * eval "echo Hi; done" ("done" is syntax error):
9356 * "echo Hi" will not execute too.
9357 */
9358 parse_and_run_string(str);
9359 free(str);
9360 rcode = G.last_exitcode;
9361 }
9362 return rcode;
9363}
9364
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009365static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009366{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009367 argv = skip_dash_dash(argv);
9368 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009369 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009370
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009371 /* Careful: we can end up here after [v]fork. Do not restore
9372 * tty pgrp then, only top-level shell process does that */
9373 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9374 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9375
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009376 /* Saved-redirect fds, script fds and G_interactive_fd are still
9377 * open here. However, they are all CLOEXEC, and execv below
9378 * closes them. Try interactive "exec ls -l /proc/self/fd",
9379 * it should show no extra open fds in the "ls" process.
9380 * If we'd try to run builtins/NOEXECs, this would need improving.
9381 */
9382 //close_saved_fds_and_FILE_fds();
9383
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009384 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009385 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009386 * and tcsetpgrp, and this is inherently racy.
9387 */
9388 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009389}
9390
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009391static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009392{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009393 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009394
9395 /* interactive bash:
9396 * # trap "echo EEE" EXIT
9397 * # exit
9398 * exit
9399 * There are stopped jobs.
9400 * (if there are _stopped_ jobs, running ones don't count)
9401 * # exit
9402 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009403 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009404 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009405 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009406 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009407
9408 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009409 argv = skip_dash_dash(argv);
9410 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009411 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009412 /* mimic bash: exit 123abc == exit 255 + error msg */
9413 xfunc_error_retval = 255;
9414 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009415 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009416}
9417
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009418#if ENABLE_HUSH_TYPE
9419/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9420static int FAST_FUNC builtin_type(char **argv)
9421{
9422 int ret = EXIT_SUCCESS;
9423
9424 while (*++argv) {
9425 const char *type;
9426 char *path = NULL;
9427
9428 if (0) {} /* make conditional compile easier below */
9429 /*else if (find_alias(*argv))
9430 type = "an alias";*/
9431#if ENABLE_HUSH_FUNCTIONS
9432 else if (find_function(*argv))
9433 type = "a function";
9434#endif
9435 else if (find_builtin(*argv))
9436 type = "a shell builtin";
9437 else if ((path = find_in_path(*argv)) != NULL)
9438 type = path;
9439 else {
9440 bb_error_msg("type: %s: not found", *argv);
9441 ret = EXIT_FAILURE;
9442 continue;
9443 }
9444
9445 printf("%s is %s\n", *argv, type);
9446 free(path);
9447 }
9448
9449 return ret;
9450}
9451#endif
9452
9453#if ENABLE_HUSH_READ
9454/* Interruptibility of read builtin in bash
9455 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9456 *
9457 * Empty trap makes read ignore corresponding signal, for any signal.
9458 *
9459 * SIGINT:
9460 * - terminates non-interactive shell;
9461 * - interrupts read in interactive shell;
9462 * if it has non-empty trap:
9463 * - executes trap and returns to command prompt in interactive shell;
9464 * - executes trap and returns to read in non-interactive shell;
9465 * SIGTERM:
9466 * - is ignored (does not interrupt) read in interactive shell;
9467 * - terminates non-interactive shell;
9468 * if it has non-empty trap:
9469 * - executes trap and returns to read;
9470 * SIGHUP:
9471 * - terminates shell (regardless of interactivity);
9472 * if it has non-empty trap:
9473 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009474 * SIGCHLD from children:
9475 * - does not interrupt read regardless of interactivity:
9476 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009477 */
9478static int FAST_FUNC builtin_read(char **argv)
9479{
9480 const char *r;
9481 char *opt_n = NULL;
9482 char *opt_p = NULL;
9483 char *opt_t = NULL;
9484 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009485 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009486 const char *ifs;
9487 int read_flags;
9488
9489 /* "!": do not abort on errors.
9490 * Option string must start with "sr" to match BUILTIN_READ_xxx
9491 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009492 read_flags = getopt32(argv,
9493#if BASH_READ_D
9494 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9495#else
9496 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9497#endif
9498 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009499 if (read_flags == (uint32_t)-1)
9500 return EXIT_FAILURE;
9501 argv += optind;
9502 ifs = get_local_var_value("IFS"); /* can be NULL */
9503
9504 again:
9505 r = shell_builtin_read(set_local_var_from_halves,
9506 argv,
9507 ifs,
9508 read_flags,
9509 opt_n,
9510 opt_p,
9511 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009512 opt_u,
9513 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009514 );
9515
9516 if ((uintptr_t)r == 1 && errno == EINTR) {
9517 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009518 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009519 goto again;
9520 }
9521
9522 if ((uintptr_t)r > 1) {
9523 bb_error_msg("%s", r);
9524 r = (char*)(uintptr_t)1;
9525 }
9526
9527 return (uintptr_t)r;
9528}
9529#endif
9530
9531#if ENABLE_HUSH_UMASK
9532static int FAST_FUNC builtin_umask(char **argv)
9533{
9534 int rc;
9535 mode_t mask;
9536
9537 rc = 1;
9538 mask = umask(0);
9539 argv = skip_dash_dash(argv);
9540 if (argv[0]) {
9541 mode_t old_mask = mask;
9542
9543 /* numeric umasks are taken as-is */
9544 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9545 if (!isdigit(argv[0][0]))
9546 mask ^= 0777;
9547 mask = bb_parse_mode(argv[0], mask);
9548 if (!isdigit(argv[0][0]))
9549 mask ^= 0777;
9550 if ((unsigned)mask > 0777) {
9551 mask = old_mask;
9552 /* bash messages:
9553 * bash: umask: 'q': invalid symbolic mode operator
9554 * bash: umask: 999: octal number out of range
9555 */
9556 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9557 rc = 0;
9558 }
9559 } else {
9560 /* Mimic bash */
9561 printf("%04o\n", (unsigned) mask);
9562 /* fall through and restore mask which we set to 0 */
9563 }
9564 umask(mask);
9565
9566 return !rc; /* rc != 0 - success */
9567}
9568#endif
9569
Denys Vlasenko41ade052017-01-08 18:56:24 +01009570#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009571static void print_escaped(const char *s)
9572{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009573 if (*s == '\'')
9574 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009575 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009576 const char *p = strchrnul(s, '\'');
9577 /* print 'xxxx', possibly just '' */
9578 printf("'%.*s'", (int)(p - s), s);
9579 if (*p == '\0')
9580 break;
9581 s = p;
9582 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009583 /* s points to '; print "'''...'''" */
9584 putchar('"');
9585 do putchar('\''); while (*++s == '\'');
9586 putchar('"');
9587 } while (*s);
9588}
Denys Vlasenko41ade052017-01-08 18:56:24 +01009589#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009590
Denys Vlasenko1e660422017-07-17 21:10:50 +02009591#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009592static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009593{
9594 do {
9595 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009596 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02009597
9598 /* So far we do not check that name is valid (TODO?) */
9599
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009600 if (*name_end == '\0') {
9601 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009602
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009603 vpp = get_ptr_to_local_var(name, name_end - name);
9604 var = vpp ? *vpp : NULL;
9605
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009606 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009607 /* export -n NAME (without =VALUE) */
9608 if (var) {
9609 var->flg_export = 0;
9610 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9611 unsetenv(name);
9612 } /* else: export -n NOT_EXISTING_VAR: no-op */
9613 continue;
9614 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009615 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009616 /* export NAME (without =VALUE) */
9617 if (var) {
9618 var->flg_export = 1;
9619 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9620 putenv(var->varstr);
9621 continue;
9622 }
9623 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009624 if (flags & SETFLAG_MAKE_RO) {
9625 /* readonly NAME (without =VALUE) */
9626 if (var) {
9627 var->flg_read_only = 1;
9628 continue;
9629 }
9630 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009631# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009632 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009633 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9634 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009635 if (var && var->func_nest_level == lvl) {
9636 /* "local x=abc; ...; local x" - ignore second local decl */
9637 continue;
9638 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02009639 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009640# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009641 /* Exporting non-existing variable.
9642 * bash does not put it in environment,
9643 * but remembers that it is exported,
9644 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +02009645 * We just set it to "" and export.
9646 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009647 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +02009648 * bash sets the value to "".
9649 */
9650 /* Or, it's "readonly NAME" (without =VALUE).
9651 * bash remembers NAME and disallows its creation
9652 * in the future.
9653 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009654 name = xasprintf("%s=", name);
9655 } else {
9656 /* (Un)exporting/making local NAME=VALUE */
9657 name = xstrdup(name);
9658 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009659 if (set_local_var(name, flags))
9660 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009661 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +02009662 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009663}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009664#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009665
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009666#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009667static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009668{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00009669 unsigned opt_unexport;
9670
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02009671#if ENABLE_HUSH_EXPORT_N
9672 /* "!": do not abort on errors */
9673 opt_unexport = getopt32(argv, "!n");
9674 if (opt_unexport == (uint32_t)-1)
9675 return EXIT_FAILURE;
9676 argv += optind;
9677#else
9678 opt_unexport = 0;
9679 argv++;
9680#endif
9681
9682 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009683 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009684 if (e) {
9685 while (*e) {
9686#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009687 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009688#else
9689 /* ash emits: export VAR='VAL'
9690 * bash: declare -x VAR="VAL"
9691 * we follow ash example */
9692 const char *s = *e++;
9693 const char *p = strchr(s, '=');
9694
9695 if (!p) /* wtf? take next variable */
9696 continue;
9697 /* export var= */
9698 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009699 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009700 putchar('\n');
9701#endif
9702 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009703 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009704 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009705 return EXIT_SUCCESS;
9706 }
9707
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009708 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009709}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009710#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009711
Denys Vlasenko295fef82009-06-03 12:47:26 +02009712#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009713static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009714{
9715 if (G.func_nest_level == 0) {
9716 bb_error_msg("%s: not in a function", argv[0]);
9717 return EXIT_FAILURE; /* bash compat */
9718 }
Denys Vlasenko1e660422017-07-17 21:10:50 +02009719 argv++;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009720 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +02009721}
9722#endif
9723
Denys Vlasenko1e660422017-07-17 21:10:50 +02009724#if ENABLE_HUSH_READONLY
9725static int FAST_FUNC builtin_readonly(char **argv)
9726{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009727 argv++;
9728 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +02009729 /* bash: readonly [-p]: list all readonly VARs
9730 * (-p has no effect in bash)
9731 */
9732 struct variable *e;
9733 for (e = G.top_var; e; e = e->next) {
9734 if (e->flg_read_only) {
9735//TODO: quote value: readonly VAR='VAL'
9736 printf("readonly %s\n", e->varstr);
9737 }
9738 }
9739 return EXIT_SUCCESS;
9740 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009741 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +02009742}
9743#endif
9744
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009745#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009746/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9747static int FAST_FUNC builtin_unset(char **argv)
9748{
9749 int ret;
9750 unsigned opts;
9751
9752 /* "!": do not abort on errors */
9753 /* "+": stop at 1st non-option */
9754 opts = getopt32(argv, "!+vf");
9755 if (opts == (unsigned)-1)
9756 return EXIT_FAILURE;
9757 if (opts == 3) {
9758 bb_error_msg("unset: -v and -f are exclusive");
9759 return EXIT_FAILURE;
9760 }
9761 argv += optind;
9762
9763 ret = EXIT_SUCCESS;
9764 while (*argv) {
9765 if (!(opts & 2)) { /* not -f */
9766 if (unset_local_var(*argv)) {
9767 /* unset <nonexistent_var> doesn't fail.
9768 * Error is when one tries to unset RO var.
9769 * Message was printed by unset_local_var. */
9770 ret = EXIT_FAILURE;
9771 }
9772 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009773# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +02009774 else {
9775 unset_func(*argv);
9776 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009777# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009778 argv++;
9779 }
9780 return ret;
9781}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009782#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009783
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009784#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009785/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9786 * built-in 'set' handler
9787 * SUSv3 says:
9788 * set [-abCefhmnuvx] [-o option] [argument...]
9789 * set [+abCefhmnuvx] [+o option] [argument...]
9790 * set -- [argument...]
9791 * set -o
9792 * set +o
9793 * Implementations shall support the options in both their hyphen and
9794 * plus-sign forms. These options can also be specified as options to sh.
9795 * Examples:
9796 * Write out all variables and their values: set
9797 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9798 * Turn on the -x and -v options: set -xv
9799 * Unset all positional parameters: set --
9800 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9801 * Set the positional parameters to the expansion of x, even if x expands
9802 * with a leading '-' or '+': set -- $x
9803 *
9804 * So far, we only support "set -- [argument...]" and some of the short names.
9805 */
9806static int FAST_FUNC builtin_set(char **argv)
9807{
9808 int n;
9809 char **pp, **g_argv;
9810 char *arg = *++argv;
9811
9812 if (arg == NULL) {
9813 struct variable *e;
9814 for (e = G.top_var; e; e = e->next)
9815 puts(e->varstr);
9816 return EXIT_SUCCESS;
9817 }
9818
9819 do {
9820 if (strcmp(arg, "--") == 0) {
9821 ++argv;
9822 goto set_argv;
9823 }
9824 if (arg[0] != '+' && arg[0] != '-')
9825 break;
9826 for (n = 1; arg[n]; ++n) {
9827 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9828 goto error;
9829 if (arg[n] == 'o' && argv[1])
9830 argv++;
9831 }
9832 } while ((arg = *++argv) != NULL);
9833 /* Now argv[0] is 1st argument */
9834
9835 if (arg == NULL)
9836 return EXIT_SUCCESS;
9837 set_argv:
9838
9839 /* NB: G.global_argv[0] ($0) is never freed/changed */
9840 g_argv = G.global_argv;
9841 if (G.global_args_malloced) {
9842 pp = g_argv;
9843 while (*++pp)
9844 free(*pp);
9845 g_argv[1] = NULL;
9846 } else {
9847 G.global_args_malloced = 1;
9848 pp = xzalloc(sizeof(pp[0]) * 2);
9849 pp[0] = g_argv[0]; /* retain $0 */
9850 g_argv = pp;
9851 }
9852 /* This realloc's G.global_argv */
9853 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9854
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009855 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +02009856
9857 return EXIT_SUCCESS;
9858
9859 /* Nothing known, so abort */
9860 error:
9861 bb_error_msg("set: %s: invalid option", arg);
9862 return EXIT_FAILURE;
9863}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009864#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009865
9866static int FAST_FUNC builtin_shift(char **argv)
9867{
9868 int n = 1;
9869 argv = skip_dash_dash(argv);
9870 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +02009871 n = bb_strtou(argv[0], NULL, 10);
9872 if (errno || n < 0) {
9873 /* shared string with ash.c */
9874 bb_error_msg("Illegal number: %s", argv[0]);
9875 /*
9876 * ash aborts in this case.
9877 * bash prints error message and set $? to 1.
9878 * Interestingly, for "shift 99999" bash does not
9879 * print error message, but does set $? to 1
9880 * (and does no shifting at all).
9881 */
9882 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02009883 }
9884 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01009885 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +02009886 int m = 1;
9887 while (m <= n)
9888 free(G.global_argv[m++]);
9889 }
9890 G.global_argc -= n;
9891 memmove(&G.global_argv[1], &G.global_argv[n+1],
9892 G.global_argc * sizeof(G.global_argv[0]));
9893 return EXIT_SUCCESS;
9894 }
9895 return EXIT_FAILURE;
9896}
9897
Denys Vlasenko74d40582017-08-11 01:32:46 +02009898#if ENABLE_HUSH_GETOPTS
9899static int FAST_FUNC builtin_getopts(char **argv)
9900{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +02009901/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
9902
Denys Vlasenko74d40582017-08-11 01:32:46 +02009903TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +02009904If a required argument is not found, and getopts is not silent,
9905a question mark (?) is placed in VAR, OPTARG is unset, and a
9906diagnostic message is printed. If getopts is silent, then a
9907colon (:) is placed in VAR and OPTARG is set to the option
9908character found.
9909
9910Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +02009911
9912"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +02009913*/
9914 char cbuf[2];
9915 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +02009916 int c, n, exitcode, my_opterr;
9917 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +02009918
9919 optstring = *++argv;
9920 if (!optstring || !(var = *++argv)) {
9921 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
9922 return EXIT_FAILURE;
9923 }
9924
Denys Vlasenko238ff982017-08-29 13:38:30 +02009925 if (argv[1])
9926 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
9927 else
9928 argv = G.global_argv;
9929 cbuf[1] = '\0';
9930
9931 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +02009932 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +02009933 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +02009934 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +02009935 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +02009936 }
Denys Vlasenko74d40582017-08-11 01:32:46 +02009937
9938 /* getopts stops on first non-option. Add "+" to force that */
9939 /*if (optstring[0] != '+')*/ {
9940 char *s = alloca(strlen(optstring) + 2);
9941 sprintf(s, "+%s", optstring);
9942 optstring = s;
9943 }
9944
Denys Vlasenko238ff982017-08-29 13:38:30 +02009945 /* Naively, now we should just
9946 * cp = get_local_var_value("OPTIND");
9947 * optind = cp ? atoi(cp) : 0;
9948 * optarg = NULL;
9949 * opterr = my_opterr;
9950 * c = getopt(string_array_len(argv), argv, optstring);
9951 * and be done? Not so fast...
9952 * Unlike normal getopt() usage in C programs, here
9953 * each successive call will (usually) have the same argv[] CONTENTS,
9954 * but not the ADDRESSES. Worse yet, it's possible that between
9955 * invocations of "getopts", there will be calls to shell builtins
9956 * which use getopt() internally. Example:
9957 * while getopts "abc" RES -a -bc -abc de; do
9958 * unset -ff func
9959 * done
9960 * This would not work correctly: getopt() call inside "unset"
9961 * modifies internal libc state which is tracking position in
9962 * multi-option strings ("-abc"). At best, it can skip options
9963 * or return the same option infinitely. With glibc implementation
9964 * of getopt(), it would use outright invalid pointers and return
9965 * garbage even _without_ "unset" mangling internal state.
9966 *
9967 * We resort to resetting getopt() state and calling it N times,
9968 * until we get Nth result (or failure).
9969 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
9970 */
Denys Vlasenko60161812017-08-29 14:32:17 +02009971 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +02009972 count = 0;
9973 n = string_array_len(argv);
9974 do {
9975 optarg = NULL;
9976 opterr = (count < G.getopt_count) ? 0 : my_opterr;
9977 c = getopt(n, argv, optstring);
9978 if (c < 0)
9979 break;
9980 count++;
9981 } while (count <= G.getopt_count);
9982
9983 /* Set OPTIND. Prevent resetting of the magic counter! */
9984 set_local_var_from_halves("OPTIND", utoa(optind));
9985 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +02009986 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +02009987
9988 /* Set OPTARG */
9989 /* Always set or unset, never left as-is, even on exit/error:
9990 * "If no option was found, or if the option that was found
9991 * does not have an option-argument, OPTARG shall be unset."
9992 */
9993 cp = optarg;
9994 if (c == '?') {
9995 /* If ":optstring" and unknown option is seen,
9996 * it is stored to OPTARG.
9997 */
9998 if (optstring[1] == ':') {
9999 cbuf[0] = optopt;
10000 cp = cbuf;
10001 }
10002 }
10003 if (cp)
10004 set_local_var_from_halves("OPTARG", cp);
10005 else
10006 unset_local_var("OPTARG");
10007
10008 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010009 exitcode = EXIT_SUCCESS;
10010 if (c < 0) { /* -1: end of options */
10011 exitcode = EXIT_FAILURE;
10012 c = '?';
10013 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010014
Denys Vlasenko238ff982017-08-29 13:38:30 +020010015 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010016 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010017 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010018
Denys Vlasenko74d40582017-08-11 01:32:46 +020010019 return exitcode;
10020}
10021#endif
10022
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010023static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010024{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010025 char *arg_path, *filename;
10026 FILE *input;
10027 save_arg_t sv;
10028 char *args_need_save;
10029#if ENABLE_HUSH_FUNCTIONS
10030 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010031#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010032
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010033 argv = skip_dash_dash(argv);
10034 filename = argv[0];
10035 if (!filename) {
10036 /* bash says: "bash: .: filename argument required" */
10037 return 2; /* bash compat */
10038 }
10039 arg_path = NULL;
10040 if (!strchr(filename, '/')) {
10041 arg_path = find_in_path(filename);
10042 if (arg_path)
10043 filename = arg_path;
10044 }
10045 input = remember_FILE(fopen_or_warn(filename, "r"));
10046 free(arg_path);
10047 if (!input) {
10048 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10049 /* POSIX: non-interactive shell should abort here,
10050 * not merely fail. So far no one complained :)
10051 */
10052 return EXIT_FAILURE;
10053 }
10054
10055#if ENABLE_HUSH_FUNCTIONS
10056 sv_flg = G_flag_return_in_progress;
10057 /* "we are inside sourced file, ok to use return" */
10058 G_flag_return_in_progress = -1;
10059#endif
10060 args_need_save = argv[1]; /* used as a boolean variable */
10061 if (args_need_save)
10062 save_and_replace_G_args(&sv, argv);
10063
10064 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10065 G.last_exitcode = 0;
10066 parse_and_run_file(input);
10067 fclose_and_forget(input);
10068
10069 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10070 restore_G_args(&sv, argv);
10071#if ENABLE_HUSH_FUNCTIONS
10072 G_flag_return_in_progress = sv_flg;
10073#endif
10074
10075 return G.last_exitcode;
10076}
10077
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010078#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010079static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010080{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010081 int sig;
10082 char *new_cmd;
10083
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010084 if (!G_traps)
10085 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010086
10087 argv++;
10088 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010089 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010090 /* No args: print all trapped */
10091 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010092 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010093 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010094 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010095 /* note: bash adds "SIG", but only if invoked
10096 * as "bash". If called as "sh", or if set -o posix,
10097 * then it prints short signal names.
10098 * We are printing short names: */
10099 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010100 }
10101 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010102 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010103 return EXIT_SUCCESS;
10104 }
10105
10106 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010107 /* If first arg is a number: reset all specified signals */
10108 sig = bb_strtou(*argv, NULL, 10);
10109 if (errno == 0) {
10110 int ret;
10111 process_sig_list:
10112 ret = EXIT_SUCCESS;
10113 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010114 sighandler_t handler;
10115
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010116 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010117 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010118 ret = EXIT_FAILURE;
10119 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010120 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010121 continue;
10122 }
10123
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010124 free(G_traps[sig]);
10125 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010126
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010127 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010128 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010129
10130 /* There is no signal for 0 (EXIT) */
10131 if (sig == 0)
10132 continue;
10133
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010134 if (new_cmd)
10135 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10136 else
10137 /* We are removing trap handler */
10138 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010139 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010140 }
10141 return ret;
10142 }
10143
10144 if (!argv[1]) { /* no second arg */
10145 bb_error_msg("trap: invalid arguments");
10146 return EXIT_FAILURE;
10147 }
10148
10149 /* First arg is "-": reset all specified to default */
10150 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10151 /* Everything else: set arg as signal handler
10152 * (includes "" case, which ignores signal) */
10153 if (argv[0][0] == '-') {
10154 if (argv[0][1] == '\0') { /* "-" */
10155 /* new_cmd remains NULL: "reset these sigs" */
10156 goto reset_traps;
10157 }
10158 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10159 argv++;
10160 }
10161 /* else: "-something", no special meaning */
10162 }
10163 new_cmd = *argv;
10164 reset_traps:
10165 argv++;
10166 goto process_sig_list;
10167}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010168#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010169
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010170#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010171static struct pipe *parse_jobspec(const char *str)
10172{
10173 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010174 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010175
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010176 if (sscanf(str, "%%%u", &jobnum) != 1) {
10177 if (str[0] != '%'
10178 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10179 ) {
10180 bb_error_msg("bad argument '%s'", str);
10181 return NULL;
10182 }
10183 /* It is "%%", "%+" or "%" - current job */
10184 jobnum = G.last_jobid;
10185 if (jobnum == 0) {
10186 bb_error_msg("no current job");
10187 return NULL;
10188 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010189 }
10190 for (pi = G.job_list; pi; pi = pi->next) {
10191 if (pi->jobid == jobnum) {
10192 return pi;
10193 }
10194 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010195 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010196 return NULL;
10197}
10198
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010199static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10200{
10201 struct pipe *job;
10202 const char *status_string;
10203
10204 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10205 for (job = G.job_list; job; job = job->next) {
10206 if (job->alive_cmds == job->stopped_cmds)
10207 status_string = "Stopped";
10208 else
10209 status_string = "Running";
10210
10211 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10212 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010213
10214 clean_up_last_dead_job();
10215
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010216 return EXIT_SUCCESS;
10217}
10218
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010219/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010220static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010221{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010222 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010223 struct pipe *pi;
10224
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010225 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010226 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010227
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010228 /* If they gave us no args, assume they want the last backgrounded task */
10229 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010230 for (pi = G.job_list; pi; pi = pi->next) {
10231 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010232 goto found;
10233 }
10234 }
10235 bb_error_msg("%s: no current job", argv[0]);
10236 return EXIT_FAILURE;
10237 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010238
10239 pi = parse_jobspec(argv[1]);
10240 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010241 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010242 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010243 /* TODO: bash prints a string representation
10244 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010245 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010246 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010247 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010248 }
10249
10250 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010251 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10252 for (i = 0; i < pi->num_cmds; i++) {
10253 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010254 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010255 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010256
10257 i = kill(- pi->pgrp, SIGCONT);
10258 if (i < 0) {
10259 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010260 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010261 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010262 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010263 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010264 }
10265
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010266 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010267 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010268 return checkjobs_and_fg_shell(pi);
10269 }
10270 return EXIT_SUCCESS;
10271}
10272#endif
10273
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010274#if ENABLE_HUSH_KILL
10275static int FAST_FUNC builtin_kill(char **argv)
10276{
10277 int ret = 0;
10278
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010279# if ENABLE_HUSH_JOB
10280 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10281 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010282
10283 do {
10284 struct pipe *pi;
10285 char *dst;
10286 int j, n;
10287
10288 if (argv[i][0] != '%')
10289 continue;
10290 /*
10291 * "kill %N" - job kill
10292 * Converting to pgrp / pid kill
10293 */
10294 pi = parse_jobspec(argv[i]);
10295 if (!pi) {
10296 /* Eat bad jobspec */
10297 j = i;
10298 do {
10299 j++;
10300 argv[j - 1] = argv[j];
10301 } while (argv[j]);
10302 ret = 1;
10303 i--;
10304 continue;
10305 }
10306 /*
10307 * In jobs started under job control, we signal
10308 * entire process group by kill -PGRP_ID.
10309 * This happens, f.e., in interactive shell.
10310 *
10311 * Otherwise, we signal each child via
10312 * kill PID1 PID2 PID3.
10313 * Testcases:
10314 * sh -c 'sleep 1|sleep 1 & kill %1'
10315 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10316 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10317 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010318 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010319 dst = alloca(n * sizeof(int)*4);
10320 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010321 if (G_interactive_fd)
10322 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010323 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010324 struct command *cmd = &pi->cmds[j];
10325 /* Skip exited members of the job */
10326 if (cmd->pid == 0)
10327 continue;
10328 /*
10329 * kill_main has matching code to expect
10330 * leading space. Needed to not confuse
10331 * negative pids with "kill -SIGNAL_NO" syntax
10332 */
10333 dst += sprintf(dst, " %u", (int)cmd->pid);
10334 }
10335 *dst = '\0';
10336 } while (argv[++i]);
10337 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010338# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010339
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010340 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010341 ret = run_applet_main(argv, kill_main);
10342 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010343 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010344 return ret;
10345}
10346#endif
10347
10348#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010349/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010350#if !ENABLE_HUSH_JOB
10351# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10352#endif
10353static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010354{
10355 int ret = 0;
10356 for (;;) {
10357 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010358 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010359
Denys Vlasenko830ea352016-11-08 04:59:11 +010010360 if (!sigisemptyset(&G.pending_set))
10361 goto check_sig;
10362
Denys Vlasenko7e675362016-10-28 21:57:31 +020010363 /* waitpid is not interruptible by SA_RESTARTed
10364 * signals which we use. Thus, this ugly dance:
10365 */
10366
10367 /* Make sure possible SIGCHLD is stored in kernel's
10368 * pending signal mask before we call waitpid.
10369 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010370 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010371 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010372 sigfillset(&oldset); /* block all signals, remember old set */
10373 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010374
10375 if (!sigisemptyset(&G.pending_set)) {
10376 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010377 goto restore;
10378 }
10379
10380 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010381/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010382 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010383 debug_printf_exec("checkjobs:%d\n", ret);
10384#if ENABLE_HUSH_JOB
10385 if (waitfor_pipe) {
10386 int rcode = job_exited_or_stopped(waitfor_pipe);
10387 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10388 if (rcode >= 0) {
10389 ret = rcode;
10390 sigprocmask(SIG_SETMASK, &oldset, NULL);
10391 break;
10392 }
10393 }
10394#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010395 /* if ECHILD, there are no children (ret is -1 or 0) */
10396 /* if ret == 0, no children changed state */
10397 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010398 if (errno == ECHILD || ret) {
10399 ret--;
10400 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010401 ret = 0;
10402 sigprocmask(SIG_SETMASK, &oldset, NULL);
10403 break;
10404 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010405 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010406 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10407 /* Note: sigsuspend invokes signal handler */
10408 sigsuspend(&oldset);
10409 restore:
10410 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010411 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010412 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010413 sig = check_and_run_traps();
10414 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010415 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010416 ret = 128 + sig;
10417 break;
10418 }
10419 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10420 }
10421 return ret;
10422}
10423
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010424static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010425{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010426 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010427 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010428
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010429 argv = skip_dash_dash(argv);
10430 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010431 /* Don't care about wait results */
10432 /* Note 1: must wait until there are no more children */
10433 /* Note 2: must be interruptible */
10434 /* Examples:
10435 * $ sleep 3 & sleep 6 & wait
10436 * [1] 30934 sleep 3
10437 * [2] 30935 sleep 6
10438 * [1] Done sleep 3
10439 * [2] Done sleep 6
10440 * $ sleep 3 & sleep 6 & wait
10441 * [1] 30936 sleep 3
10442 * [2] 30937 sleep 6
10443 * [1] Done sleep 3
10444 * ^C <-- after ~4 sec from keyboard
10445 * $
10446 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010447 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010448 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010449
Denys Vlasenko7e675362016-10-28 21:57:31 +020010450 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010451 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010452 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010453#if ENABLE_HUSH_JOB
10454 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010455 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010456 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010457 wait_pipe = parse_jobspec(*argv);
10458 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010459 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010460 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010461 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010462 } else {
10463 /* waiting on "last dead job" removes it */
10464 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010465 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010466 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010467 /* else: parse_jobspec() already emitted error msg */
10468 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010469 }
10470#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010471 /* mimic bash message */
10472 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010473 ret = EXIT_FAILURE;
10474 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010475 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010476
Denys Vlasenko7e675362016-10-28 21:57:31 +020010477 /* Do we have such child? */
10478 ret = waitpid(pid, &status, WNOHANG);
10479 if (ret < 0) {
10480 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010481 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010482 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010483 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010484 /* "wait $!" but last bg task has already exited. Try:
10485 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10486 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010487 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010488 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010489 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010490 } else {
10491 /* Example: "wait 1". mimic bash message */
10492 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010493 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010494 } else {
10495 /* ??? */
10496 bb_perror_msg("wait %s", *argv);
10497 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010498 continue; /* bash checks all argv[] */
10499 }
10500 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010501 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010502 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010503 } else {
10504 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010505 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010506 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010507 if (WIFSIGNALED(status))
10508 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010509 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010510 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010511
10512 return ret;
10513}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010514#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010515
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010516#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10517static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10518{
10519 if (argv[1]) {
10520 def = bb_strtou(argv[1], NULL, 10);
10521 if (errno || def < def_min || argv[2]) {
10522 bb_error_msg("%s: bad arguments", argv[0]);
10523 def = UINT_MAX;
10524 }
10525 }
10526 return def;
10527}
10528#endif
10529
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010530#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010531static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010532{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010533 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010534 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010535 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010536 /* if we came from builtin_continue(), need to undo "= 1" */
10537 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010538 return EXIT_SUCCESS; /* bash compat */
10539 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010540 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010541
10542 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10543 if (depth == UINT_MAX)
10544 G.flag_break_continue = BC_BREAK;
10545 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010546 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010547
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010548 return EXIT_SUCCESS;
10549}
10550
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010551static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010552{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010553 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10554 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010555}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010556#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010557
10558#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010559static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010560{
10561 int rc;
10562
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010563 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010564 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10565 return EXIT_FAILURE; /* bash compat */
10566 }
10567
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010568 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010569
10570 /* bash:
10571 * out of range: wraps around at 256, does not error out
10572 * non-numeric param:
10573 * f() { false; return qwe; }; f; echo $?
10574 * bash: return: qwe: numeric argument required <== we do this
10575 * 255 <== we also do this
10576 */
10577 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10578 return rc;
10579}
10580#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010581
Denys Vlasenko11f2e992017-08-10 16:34:03 +020010582#if ENABLE_HUSH_TIMES
10583static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10584{
10585 static const uint8_t times_tbl[] ALIGN1 = {
10586 ' ', offsetof(struct tms, tms_utime),
10587 '\n', offsetof(struct tms, tms_stime),
10588 ' ', offsetof(struct tms, tms_cutime),
10589 '\n', offsetof(struct tms, tms_cstime),
10590 0
10591 };
10592 const uint8_t *p;
10593 unsigned clk_tck;
10594 struct tms buf;
10595
10596 clk_tck = bb_clk_tck();
10597
10598 times(&buf);
10599 p = times_tbl;
10600 do {
10601 unsigned sec, frac;
10602 unsigned long t;
10603 t = *(clock_t *)(((char *) &buf) + p[1]);
10604 sec = t / clk_tck;
10605 frac = t % clk_tck;
10606 printf("%um%u.%03us%c",
10607 sec / 60, sec % 60,
10608 (frac * 1000) / clk_tck,
10609 p[0]);
10610 p += 2;
10611 } while (*p);
10612
10613 return EXIT_SUCCESS;
10614}
10615#endif
10616
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010617#if ENABLE_HUSH_MEMLEAK
10618static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10619{
10620 void *p;
10621 unsigned long l;
10622
10623# ifdef M_TRIM_THRESHOLD
10624 /* Optional. Reduces probability of false positives */
10625 malloc_trim(0);
10626# endif
10627 /* Crude attempt to find where "free memory" starts,
10628 * sans fragmentation. */
10629 p = malloc(240);
10630 l = (unsigned long)p;
10631 free(p);
10632 p = malloc(3400);
10633 if (l < (unsigned long)p) l = (unsigned long)p;
10634 free(p);
10635
10636
10637# if 0 /* debug */
10638 {
10639 struct mallinfo mi = mallinfo();
10640 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10641 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10642 }
10643# endif
10644
10645 if (!G.memleak_value)
10646 G.memleak_value = l;
10647
10648 l -= G.memleak_value;
10649 if ((long)l < 0)
10650 l = 0;
10651 l /= 1024;
10652 if (l > 127)
10653 l = 127;
10654
10655 /* Exitcode is "how many kilobytes we leaked since 1st call" */
10656 return l;
10657}
10658#endif